From 84fe56e60ee0668290911fa017fd58ffb9e4cd3e Mon Sep 17 00:00:00 2001 From: Frederik Gladhorn Date: Mon, 14 Oct 2019 09:42:03 +0200 Subject: Bump version Change-Id: I6840c8f666991a2c29a5394069266de9e8c014e2 --- .qmake.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.qmake.conf b/.qmake.conf index b1f6099df..d9464b0c8 100644 --- a/.qmake.conf +++ b/.qmake.conf @@ -3,4 +3,4 @@ QT3D_BUILD_ROOT = $$shadowed($$PWD) load(qt_build_config) -MODULE_VERSION = 5.13.1 +MODULE_VERSION = 5.13.2 -- cgit v1.2.3 From ac1cb9a8ad3236bd14eb644e01c1489eb8723477 Mon Sep 17 00:00:00 2001 From: Mats Honkamaa Date: Thu, 17 Oct 2019 09:27:56 +0300 Subject: Add BufferCapture QML documentation Copied the very basic C++ docs. Task-number: QTBUG-79109 Change-Id: Ib5803dfc06d7d10001e31f9cb0c113509cc23f0f Reviewed-by: Paul Lemire --- src/render/framegraph/qbuffercapture.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/render/framegraph/qbuffercapture.cpp b/src/render/framegraph/qbuffercapture.cpp index d1d301077..8e180a7c3 100644 --- a/src/render/framegraph/qbuffercapture.cpp +++ b/src/render/framegraph/qbuffercapture.cpp @@ -63,6 +63,14 @@ QBufferCapturePrivate::QBufferCapturePrivate() \inmodule Qt3DRender \brief Exchanges buffer data between GPU and CPU. */ + +/*! + \qmltype BufferCapture + \inqmlmodule Qt3D.Render + \instantiates Qt3DRender::QBufferCapture + \brief Exchanges buffer data between GPU and CPU. +*/ + QBufferCapture::QBufferCapture(Qt3DCore::QNode *parent) : QFrameGraphNode(*new QBufferCapturePrivate, parent) { -- cgit v1.2.3 From 2e8842d1c7cea00a9798930f3d5aacc26293b726 Mon Sep 17 00:00:00 2001 From: Mats Honkamaa Date: Wed, 9 Oct 2019 14:39:05 +0300 Subject: Add documentation for PhongAlphaMaterial properties Added documentation for the following PhongAlphaMaterial QML Type properties: blendFunctionArg, destinationAlphaArg, destinationRgbArg, sourceAlphaArg, and sourceRgbArg. Task-number: QTBUG-78480 Change-Id: I392480926f8803e82ad88ee9638130c6f9b74931 Reviewed-by: Paul Lemire --- src/doc/src/qmlextramaterials.qdoc | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/doc/src/qmlextramaterials.qdoc b/src/doc/src/qmlextramaterials.qdoc index e0a2e9edf..338bada09 100644 --- a/src/doc/src/qmlextramaterials.qdoc +++ b/src/doc/src/qmlextramaterials.qdoc @@ -544,6 +544,41 @@ The default value is 0.5. */ +/*! + \qmlproperty BlendEquationArguments::Blending PhongAlphaMaterial::sourceRgbArg + + Holds the blend equation source RGB blending argument. + + \sa Qt3DRender::QBlendEquationArguments::Blending +*/ +/*! + \qmlproperty BlendEquationArguments::Blending PhongAlphaMaterial::destinationRgbArg + + Holds the blend equation destination RGB blending argument. + + \sa Qt3DRender::QBlendEquationArguments::Blending +*/ +/*! + \qmlproperty BlendEquationArguments::Blending PhongAlphaMaterial::sourceAlphaArg + + Holds the blend equation source alpha blending argument. + + \sa Qt3DRender::QBlendEquationArguments::Blending +*/ +/*! + \qmlproperty BlendEquationArguments::Blending PhongAlphaMaterial::destinationAlphaArg + + Holds the blend equation destination alpha blending argument. + + \sa Qt3DRender::QBlendEquationArguments::Blending +*/ +/*! + \qmlproperty BlendEquation::BlendFunction PhongAlphaMaterial::blendFunctionArg + + Holds the blend equation function argument. + + \sa Qt3DRender::QBlendEquation::BlendFunction +*/ /*! \qmltype PhongMaterial -- cgit v1.2.3 From ce4663c2659d9e1611a1647a9b3cd26da8a80604 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Tue, 8 Oct 2019 08:01:10 +0100 Subject: Clean up old property update code Remove useless includes, clear up commented out or unused code Change-Id: Id3382b16108d79f1e2522d43463c8d70aef8fcb2 Reviewed-by: Mike Krus --- src/animation/backend/skeleton.cpp | 1 - src/animation/frontend/qabstractanimationclip.cpp | 1 - src/animation/frontend/qanimationcliploader.cpp | 1 - src/input/backend/keyboardhandler.cpp | 1 - src/input/backend/mousehandler.cpp | 1 - src/input/frontend/qabstractphysicaldeviceproxy.cpp | 1 - src/input/frontend/qaction.cpp | 1 - src/input/frontend/qaxis.cpp | 1 - src/input/frontend/qaxisaccumulator.cpp | 1 - src/input/frontend/qkeyboarddevice.cpp | 11 ----------- src/input/frontend/qkeyboarddevice.h | 1 - src/input/frontend/qkeyboardhandler.cpp | 1 - src/input/frontend/qmousehandler.cpp | 1 - src/render/backend/transform.cpp | 1 - src/render/frontend/qlevelofdetailswitch.cpp | 1 - src/render/io/qsceneloader.cpp | 1 - src/render/io/scene.cpp | 1 - src/render/picking/qobjectpicker_p.h | 1 - src/render/picking/raycaster.cpp | 1 - tests/auto/animation/animationclip/tst_animationclip.cpp | 2 -- .../animation/blendedclipanimator/tst_blendedclipanimator.cpp | 2 -- .../qanimationcliploader/tst_qanimationcliploader.cpp | 1 - tests/auto/animation/skeleton/tst_skeleton.cpp | 1 - tests/auto/input/abstractaxisinput/tst_abstractaxisinput.cpp | 2 -- tests/auto/input/action/tst_action.cpp | 1 - tests/auto/input/analogaxisinput/tst_analogaxisinput.cpp | 2 -- tests/auto/input/axis/tst_axis.cpp | 1 - tests/auto/input/axisaccumulator/tst_axisaccumulator.cpp | 1 - tests/auto/input/buttonaxisinput/tst_buttonaxisinput.cpp | 2 -- .../auto/input/loadproxydevicejob/tst_loadproxydevicejob.cpp | 1 - .../input/physicaldeviceproxy/tst_physicaldeviceproxy.cpp | 2 -- .../tst_qabstractphysicaldeviceproxy.cpp | 1 - tests/auto/input/qaction/tst_qaction.cpp | 1 - tests/auto/input/qaxis/tst_qaxis.cpp | 1 - tests/auto/input/qaxisaccumulator/tst_qaxisaccumulator.cpp | 1 - tests/auto/render/objectpicker/tst_objectpicker.cpp | 1 - tests/auto/render/raycaster/tst_raycaster.cpp | 1 - tests/auto/render/transform/tst_transform.cpp | 1 - 38 files changed, 54 deletions(-) diff --git a/src/animation/backend/skeleton.cpp b/src/animation/backend/skeleton.cpp index 60e436a71..3788fd0f1 100644 --- a/src/animation/backend/skeleton.cpp +++ b/src/animation/backend/skeleton.cpp @@ -35,7 +35,6 @@ ****************************************************************************/ #include "skeleton_p.h" -#include #include QT_BEGIN_NAMESPACE diff --git a/src/animation/frontend/qabstractanimationclip.cpp b/src/animation/frontend/qabstractanimationclip.cpp index e662a1408..cd1cce464 100644 --- a/src/animation/frontend/qabstractanimationclip.cpp +++ b/src/animation/frontend/qabstractanimationclip.cpp @@ -36,7 +36,6 @@ #include "qabstractanimationclip.h" #include "qabstractanimationclip_p.h" -#include QT_BEGIN_NAMESPACE diff --git a/src/animation/frontend/qanimationcliploader.cpp b/src/animation/frontend/qanimationcliploader.cpp index 446995b17..d3b2b5bf4 100644 --- a/src/animation/frontend/qanimationcliploader.cpp +++ b/src/animation/frontend/qanimationcliploader.cpp @@ -36,7 +36,6 @@ #include "qanimationcliploader.h" #include "qanimationcliploader_p.h" -#include QT_BEGIN_NAMESPACE diff --git a/src/input/backend/keyboardhandler.cpp b/src/input/backend/keyboardhandler.cpp index 66af527c9..026012e52 100644 --- a/src/input/backend/keyboardhandler.cpp +++ b/src/input/backend/keyboardhandler.cpp @@ -41,7 +41,6 @@ #include #include -#include #include #include diff --git a/src/input/backend/mousehandler.cpp b/src/input/backend/mousehandler.cpp index 46bd273d6..9c7ff9817 100644 --- a/src/input/backend/mousehandler.cpp +++ b/src/input/backend/mousehandler.cpp @@ -41,7 +41,6 @@ #include #include -#include #include #include diff --git a/src/input/frontend/qabstractphysicaldeviceproxy.cpp b/src/input/frontend/qabstractphysicaldeviceproxy.cpp index a7930ed76..4ed116440 100644 --- a/src/input/frontend/qabstractphysicaldeviceproxy.cpp +++ b/src/input/frontend/qabstractphysicaldeviceproxy.cpp @@ -41,7 +41,6 @@ #include "qabstractphysicaldeviceproxy_p_p.h" #include -#include QT_BEGIN_NAMESPACE diff --git a/src/input/frontend/qaction.cpp b/src/input/frontend/qaction.cpp index c835062a2..512a5aca7 100644 --- a/src/input/frontend/qaction.cpp +++ b/src/input/frontend/qaction.cpp @@ -41,7 +41,6 @@ #include "qaction_p.h" #include -#include #include #include diff --git a/src/input/frontend/qaxis.cpp b/src/input/frontend/qaxis.cpp index b6018c887..7faa6a459 100644 --- a/src/input/frontend/qaxis.cpp +++ b/src/input/frontend/qaxis.cpp @@ -40,7 +40,6 @@ #include "qaxis_p.h" #include -#include #include QT_BEGIN_NAMESPACE diff --git a/src/input/frontend/qaxisaccumulator.cpp b/src/input/frontend/qaxisaccumulator.cpp index 7e9930f66..03f6e3bd1 100644 --- a/src/input/frontend/qaxisaccumulator.cpp +++ b/src/input/frontend/qaxisaccumulator.cpp @@ -42,7 +42,6 @@ #include #include -#include QT_BEGIN_NAMESPACE diff --git a/src/input/frontend/qkeyboarddevice.cpp b/src/input/frontend/qkeyboarddevice.cpp index 257a5be8c..0fe3a1338 100644 --- a/src/input/frontend/qkeyboarddevice.cpp +++ b/src/input/frontend/qkeyboarddevice.cpp @@ -41,7 +41,6 @@ #include "qkeyboarddevice_p.h" #include -#include #include @@ -310,16 +309,6 @@ QKeyboardDevice::QKeyboardDevice(QKeyboardDevicePrivate &dd, QNode *parent) { } -/*! \internal */ -void QKeyboardDevice::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) -{ - Q_D(QKeyboardDevice); - Qt3DCore::QPropertyUpdatedChangePtr e = qSharedPointerCast(change); - if (e->type() == Qt3DCore::PropertyUpdated && e->propertyName() == QByteArrayLiteral("activeInput")) { - Qt3DCore::QNodeId activeInputId = e->value().value(); - setActiveInput(qobject_cast(d->scene()->lookupNode(activeInputId))); - } -} /*! * Set the active input to \a activeInput */ diff --git a/src/input/frontend/qkeyboarddevice.h b/src/input/frontend/qkeyboarddevice.h index c3478ec27..ee4b864f7 100644 --- a/src/input/frontend/qkeyboarddevice.h +++ b/src/input/frontend/qkeyboarddevice.h @@ -71,7 +71,6 @@ public: protected: explicit QKeyboardDevice(QKeyboardDevicePrivate &dd, QNode *parent = nullptr); - void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; Q_SIGNALS: void activeInputChanged(QKeyboardHandler *activeInput); diff --git a/src/input/frontend/qkeyboardhandler.cpp b/src/input/frontend/qkeyboardhandler.cpp index aff136a04..1581f763c 100644 --- a/src/input/frontend/qkeyboardhandler.cpp +++ b/src/input/frontend/qkeyboardhandler.cpp @@ -41,7 +41,6 @@ #include "qkeyboardhandler_p.h" #include -#include QT_BEGIN_NAMESPACE diff --git a/src/input/frontend/qmousehandler.cpp b/src/input/frontend/qmousehandler.cpp index 944ca391a..f3e7a18c8 100644 --- a/src/input/frontend/qmousehandler.cpp +++ b/src/input/frontend/qmousehandler.cpp @@ -42,7 +42,6 @@ #include #include -#include #include QT_BEGIN_NAMESPACE diff --git a/src/render/backend/transform.cpp b/src/render/backend/transform.cpp index 8e98801b7..9e78bc96f 100644 --- a/src/render/backend/transform.cpp +++ b/src/render/backend/transform.cpp @@ -39,7 +39,6 @@ #include "transform_p.h" -#include #include #include #include diff --git a/src/render/frontend/qlevelofdetailswitch.cpp b/src/render/frontend/qlevelofdetailswitch.cpp index 7b888fe98..c0bbdc0f8 100644 --- a/src/render/frontend/qlevelofdetailswitch.cpp +++ b/src/render/frontend/qlevelofdetailswitch.cpp @@ -42,7 +42,6 @@ #include "qlevelofdetail_p.h" #include "qglobal.h" #include -#include QT_BEGIN_NAMESPACE diff --git a/src/render/io/qsceneloader.cpp b/src/render/io/qsceneloader.cpp index cf1e45355..1b6a56e36 100644 --- a/src/render/io/qsceneloader.cpp +++ b/src/render/io/qsceneloader.cpp @@ -41,7 +41,6 @@ #include "qsceneloader_p.h" #include -#include #include #include #include diff --git a/src/render/io/scene.cpp b/src/render/io/scene.cpp index 089091701..bd76b136f 100644 --- a/src/render/io/scene.cpp +++ b/src/render/io/scene.cpp @@ -39,7 +39,6 @@ #include "scene_p.h" #include -#include #include #include #include diff --git a/src/render/picking/qobjectpicker_p.h b/src/render/picking/qobjectpicker_p.h index 69cee529d..61f8a3d94 100644 --- a/src/render/picking/qobjectpicker_p.h +++ b/src/render/picking/qobjectpicker_p.h @@ -50,7 +50,6 @@ #include #include -#include #include #include diff --git a/src/render/picking/raycaster.cpp b/src/render/picking/raycaster.cpp index 3a79204c7..8d3456595 100644 --- a/src/render/picking/raycaster.cpp +++ b/src/render/picking/raycaster.cpp @@ -44,7 +44,6 @@ #include #include #include -#include QT_BEGIN_NAMESPACE diff --git a/tests/auto/animation/animationclip/tst_animationclip.cpp b/tests/auto/animation/animationclip/tst_animationclip.cpp index 35df21a58..d28a8fc58 100644 --- a/tests/auto/animation/animationclip/tst_animationclip.cpp +++ b/tests/auto/animation/animationclip/tst_animationclip.cpp @@ -31,9 +31,7 @@ #include #include #include -#include #include -#include #include #include diff --git a/tests/auto/animation/blendedclipanimator/tst_blendedclipanimator.cpp b/tests/auto/animation/blendedclipanimator/tst_blendedclipanimator.cpp index bb95fe979..fb741050b 100644 --- a/tests/auto/animation/blendedclipanimator/tst_blendedclipanimator.cpp +++ b/tests/auto/animation/blendedclipanimator/tst_blendedclipanimator.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include #include #include @@ -44,7 +43,6 @@ #include #include #include -#include #include "qbackendnodetester.h" class tst_BlendedClipAnimator : public Qt3DCore::QBackendNodeTester diff --git a/tests/auto/animation/qanimationcliploader/tst_qanimationcliploader.cpp b/tests/auto/animation/qanimationcliploader/tst_qanimationcliploader.cpp index 274144d3e..00130add3 100644 --- a/tests/auto/animation/qanimationcliploader/tst_qanimationcliploader.cpp +++ b/tests/auto/animation/qanimationcliploader/tst_qanimationcliploader.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/auto/animation/skeleton/tst_skeleton.cpp b/tests/auto/animation/skeleton/tst_skeleton.cpp index 99acf0b43..d9b209194 100644 --- a/tests/auto/animation/skeleton/tst_skeleton.cpp +++ b/tests/auto/animation/skeleton/tst_skeleton.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/auto/input/abstractaxisinput/tst_abstractaxisinput.cpp b/tests/auto/input/abstractaxisinput/tst_abstractaxisinput.cpp index 48ac4b3fe..94f02bc1e 100644 --- a/tests/auto/input/abstractaxisinput/tst_abstractaxisinput.cpp +++ b/tests/auto/input/abstractaxisinput/tst_abstractaxisinput.cpp @@ -30,11 +30,9 @@ #include #include #include -#include #include #include #include -#include #include "testdevice.h" class DummyAxisInput : public Qt3DInput::QAbstractAxisInput diff --git a/tests/auto/input/action/tst_action.cpp b/tests/auto/input/action/tst_action.cpp index 6b8b11b80..cc40cef2f 100644 --- a/tests/auto/input/action/tst_action.cpp +++ b/tests/auto/input/action/tst_action.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/auto/input/analogaxisinput/tst_analogaxisinput.cpp b/tests/auto/input/analogaxisinput/tst_analogaxisinput.cpp index 0bdaadc46..6f91ce337 100644 --- a/tests/auto/input/analogaxisinput/tst_analogaxisinput.cpp +++ b/tests/auto/input/analogaxisinput/tst_analogaxisinput.cpp @@ -32,11 +32,9 @@ #include #include -#include #include #include #include -#include class tst_AnalogAxisInput: public Qt3DCore::QBackendNodeTester { diff --git a/tests/auto/input/axis/tst_axis.cpp b/tests/auto/input/axis/tst_axis.cpp index de9d5c553..ddd59b395 100644 --- a/tests/auto/input/axis/tst_axis.cpp +++ b/tests/auto/input/axis/tst_axis.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/auto/input/axisaccumulator/tst_axisaccumulator.cpp b/tests/auto/input/axisaccumulator/tst_axisaccumulator.cpp index f7d7d32f1..f8d4adcd2 100644 --- a/tests/auto/input/axisaccumulator/tst_axisaccumulator.cpp +++ b/tests/auto/input/axisaccumulator/tst_axisaccumulator.cpp @@ -28,7 +28,6 @@ #include #include -#include #include #include #include diff --git a/tests/auto/input/buttonaxisinput/tst_buttonaxisinput.cpp b/tests/auto/input/buttonaxisinput/tst_buttonaxisinput.cpp index 5debe4d99..e315ed1dc 100644 --- a/tests/auto/input/buttonaxisinput/tst_buttonaxisinput.cpp +++ b/tests/auto/input/buttonaxisinput/tst_buttonaxisinput.cpp @@ -32,11 +32,9 @@ #include #include -#include #include #include #include -#include class tst_ButtonAxisInput: public Qt3DCore::QBackendNodeTester { diff --git a/tests/auto/input/loadproxydevicejob/tst_loadproxydevicejob.cpp b/tests/auto/input/loadproxydevicejob/tst_loadproxydevicejob.cpp index 985ee1955..c5322eda6 100644 --- a/tests/auto/input/loadproxydevicejob/tst_loadproxydevicejob.cpp +++ b/tests/auto/input/loadproxydevicejob/tst_loadproxydevicejob.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include #include "qbackendnodetester.h" #include "testdeviceproxy.h" diff --git a/tests/auto/input/physicaldeviceproxy/tst_physicaldeviceproxy.cpp b/tests/auto/input/physicaldeviceproxy/tst_physicaldeviceproxy.cpp index aaf46a54b..bd5da8e3f 100644 --- a/tests/auto/input/physicaldeviceproxy/tst_physicaldeviceproxy.cpp +++ b/tests/auto/input/physicaldeviceproxy/tst_physicaldeviceproxy.cpp @@ -32,9 +32,7 @@ #include #include #include -#include #include -#include #include "qbackendnodetester.h" #include "testdeviceproxy.h" #include "testpostmanarbiter.h" diff --git a/tests/auto/input/qabstractphysicaldeviceproxy/tst_qabstractphysicaldeviceproxy.cpp b/tests/auto/input/qabstractphysicaldeviceproxy/tst_qabstractphysicaldeviceproxy.cpp index aef76cc0d..bbe184e0e 100644 --- a/tests/auto/input/qabstractphysicaldeviceproxy/tst_qabstractphysicaldeviceproxy.cpp +++ b/tests/auto/input/qabstractphysicaldeviceproxy/tst_qabstractphysicaldeviceproxy.cpp @@ -29,7 +29,6 @@ #include -#include #include #include #include "testdeviceproxy.h" diff --git a/tests/auto/input/qaction/tst_qaction.cpp b/tests/auto/input/qaction/tst_qaction.cpp index 8d097978f..13c4a2d83 100644 --- a/tests/auto/input/qaction/tst_qaction.cpp +++ b/tests/auto/input/qaction/tst_qaction.cpp @@ -27,7 +27,6 @@ ****************************************************************************/ #include -#include #include #include #include diff --git a/tests/auto/input/qaxis/tst_qaxis.cpp b/tests/auto/input/qaxis/tst_qaxis.cpp index 36d434c6a..9b3068442 100644 --- a/tests/auto/input/qaxis/tst_qaxis.cpp +++ b/tests/auto/input/qaxis/tst_qaxis.cpp @@ -27,7 +27,6 @@ ****************************************************************************/ #include -#include #include #include #include diff --git a/tests/auto/input/qaxisaccumulator/tst_qaxisaccumulator.cpp b/tests/auto/input/qaxisaccumulator/tst_qaxisaccumulator.cpp index e4145ab7a..9f96cd845 100644 --- a/tests/auto/input/qaxisaccumulator/tst_qaxisaccumulator.cpp +++ b/tests/auto/input/qaxisaccumulator/tst_qaxisaccumulator.cpp @@ -27,7 +27,6 @@ ****************************************************************************/ #include -#include #include #include #include diff --git a/tests/auto/render/objectpicker/tst_objectpicker.cpp b/tests/auto/render/objectpicker/tst_objectpicker.cpp index 5fc988d47..24fa2159d 100644 --- a/tests/auto/render/objectpicker/tst_objectpicker.cpp +++ b/tests/auto/render/objectpicker/tst_objectpicker.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include "testpostmanarbiter.h" #include "testrenderer.h" diff --git a/tests/auto/render/raycaster/tst_raycaster.cpp b/tests/auto/render/raycaster/tst_raycaster.cpp index 72ef396d7..57a1bcf47 100644 --- a/tests/auto/render/raycaster/tst_raycaster.cpp +++ b/tests/auto/render/raycaster/tst_raycaster.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include "testpostmanarbiter.h" #include "testrenderer.h" diff --git a/tests/auto/render/transform/tst_transform.cpp b/tests/auto/render/transform/tst_transform.cpp index 476c47393..a3fcdb9c8 100644 --- a/tests/auto/render/transform/tst_transform.cpp +++ b/tests/auto/render/transform/tst_transform.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include "qbackendnodetester.h" #include "testrenderer.h" -- cgit v1.2.3 From 93361f1a59c1edd2e4eb6d2aa7e2da5b73760a18 Mon Sep 17 00:00:00 2001 From: Antti Kokko Date: Mon, 14 Oct 2019 10:28:54 +0300 Subject: Add changes file for Qt 5.13.2 Change-Id: I94eb9efad7e331016b44d309feba62436a5bc4c3 Reviewed-by: Paul Lemire --- dist/changes-5.13.2 | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 dist/changes-5.13.2 diff --git a/dist/changes-5.13.2 b/dist/changes-5.13.2 new file mode 100644 index 000000000..e3bb833f0 --- /dev/null +++ b/dist/changes-5.13.2 @@ -0,0 +1,20 @@ +Qt 5.13.2 is a bug-fix release. It maintains both forward and backward +compatibility (source and binary) with Qt 5.13.0 through 5.13.1. + +For more details, refer to the online documentation included in this +distribution. The documentation is also available online: + +https://doc.qt.io/qt-5/index.html + +The Qt version 5.13 series is binary compatible with the 5.12.x series. +Applications compiled for 5.12 will continue to run with 5.13. + +Some of the changes listed in this file include issue tracking numbers +corresponding to tasks in the Qt Bug Tracker: + +https://bugreports.qt.io/ + +Each of these identifiers can be entered in the bug tracker to obtain more +information about a particular change. + + - This release contains only minor code improvements. -- cgit v1.2.3 From 3281951ccc9b607ffaf41d8425b3e3cce3936fd1 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Sun, 20 Oct 2019 18:46:16 +0100 Subject: Fix Coverity warnings Change-Id: I00c875b48d838170fddf0b92f0ac5592828c6f0f Reviewed-by: Paul Lemire --- src/animation/backend/abstractevaluateclipanimatorjob.cpp | 5 ----- src/animation/backend/animationclip.cpp | 2 ++ src/animation/backend/buildblendtreesjob.cpp | 3 ++- src/animation/backend/channelmapping.cpp | 4 ++-- src/animation/backend/evaluateblendclipanimatorjob.cpp | 1 + src/animation/backend/evaluateclipanimatorjob.cpp | 1 + src/animation/backend/findrunningclipanimatorsjob.cpp | 3 ++- src/animation/backend/loadanimationclipjob.cpp | 1 + src/animation/frontend/qabstractchannelmapping.cpp | 1 + src/animation/frontend/qvertexblendanimation.cpp | 4 ++-- src/core/aspects/qaspectmanager.cpp | 1 + src/core/aspects/qaspectmanager_p.h | 1 - src/core/jobs/task.cpp | 1 + src/core/resources/qframeallocator.cpp | 2 ++ src/core/transforms/qabstractskeleton.cpp | 1 + src/core/transforms/sqt_p.h | 2 ++ src/input/backend/keyboardeventfilter.cpp | 1 + src/input/backend/mouseeventfilter.cpp | 1 + src/logic/manager.cpp | 2 ++ src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp | 3 ++- src/quick3d/imports/scene3d/scene3ditem.cpp | 1 + src/quick3d/imports/scene3d/scene3drenderer.cpp | 1 + src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp | 1 + src/quick3d/quick3dscene2d/items/scene2dsharedobject.cpp | 1 + src/render/geometry/skeleton.cpp | 2 ++ src/render/jobs/abstractpickingjob.cpp | 2 ++ src/render/jobs/filterproximitydistancejob.cpp | 4 +++- src/render/jobs/updatetreeenabledjob.cpp | 1 + src/render/materialsystem/shader.cpp | 1 + src/render/raycasting/qcollisionqueryresult.cpp | 1 + src/render/raycasting/qcollisionqueryresult_p.h | 2 ++ src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp | 6 +++--- src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp | 8 +++++--- src/render/renderers/opengl/renderer/rendercommand.cpp | 1 + src/render/renderers/opengl/renderer/renderview.cpp | 5 ++++- src/render/texture/texture.cpp | 8 ++++---- 36 files changed, 60 insertions(+), 25 deletions(-) diff --git a/src/animation/backend/abstractevaluateclipanimatorjob.cpp b/src/animation/backend/abstractevaluateclipanimatorjob.cpp index 236a96efe..5267d4526 100644 --- a/src/animation/backend/abstractevaluateclipanimatorjob.cpp +++ b/src/animation/backend/abstractevaluateclipanimatorjob.cpp @@ -53,13 +53,8 @@ public: void postFrame(Qt3DCore::QAspectManager *manager) override; - Q_DECLARE_PUBLIC(AbstractEvaluateClipAnimatorJob) - AnimationRecord m_record; QVector m_callbacks; - -private: - AbstractEvaluateClipAnimatorJob *q_ptr; }; AbstractEvaluateClipAnimatorJob::AbstractEvaluateClipAnimatorJob() diff --git a/src/animation/backend/animationclip.cpp b/src/animation/backend/animationclip.cpp index 2dea81b52..2c7e4fffb 100644 --- a/src/animation/backend/animationclip.cpp +++ b/src/animation/backend/animationclip.cpp @@ -68,6 +68,7 @@ AnimationClip::AnimationClip() , m_name() , m_channels() , m_duration(0.0f) + , m_channelComponentCount(0) { } @@ -81,6 +82,7 @@ void AnimationClip::cleanup() m_dataType = Unknown; m_channels.clear(); m_duration = 0.0f; + m_channelComponentCount = 0; clearData(); } diff --git a/src/animation/backend/buildblendtreesjob.cpp b/src/animation/backend/buildblendtreesjob.cpp index 3cfa81446..b4cc04323 100644 --- a/src/animation/backend/buildblendtreesjob.cpp +++ b/src/animation/backend/buildblendtreesjob.cpp @@ -50,8 +50,9 @@ namespace Animation { BuildBlendTreesJob::BuildBlendTreesJob() : Qt3DCore::QAspectJob() + , m_handler(nullptr) { - SET_JOB_RUN_STAT_TYPE(this, JobTypes::BuildBlendTree, 0); + SET_JOB_RUN_STAT_TYPE(this, JobTypes::BuildBlendTree, 0) } void BuildBlendTreesJob::setBlendedClipAnimators(const QVector &blendedClipAnimatorHandles) diff --git a/src/animation/backend/channelmapping.cpp b/src/animation/backend/channelmapping.cpp index 83e7322da..42942fdd3 100644 --- a/src/animation/backend/channelmapping.cpp +++ b/src/animation/backend/channelmapping.cpp @@ -106,9 +106,9 @@ void ChannelMapping::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs const QCallbackMapping *callbackMapping = qobject_cast(frontEnd); if (callbackMapping) { m_mappingType = ChannelMappingType; - m_channelName = channelMapping->channelName(); + m_channelName = callbackMapping->channelName(); - const QCallbackMappingPrivate *d = static_cast(Qt3DCore::QNodePrivate::get(channelMapping)); + const QCallbackMappingPrivate *d = static_cast(Qt3DCore::QNodePrivate::get(callbackMapping)); m_type = d->m_type; m_callback = d->m_callback; m_callbackFlags = d->m_callbackFlags; diff --git a/src/animation/backend/evaluateblendclipanimatorjob.cpp b/src/animation/backend/evaluateblendclipanimatorjob.cpp index 9b6802d3b..765531902 100644 --- a/src/animation/backend/evaluateblendclipanimatorjob.cpp +++ b/src/animation/backend/evaluateblendclipanimatorjob.cpp @@ -54,6 +54,7 @@ namespace Animation { EvaluateBlendClipAnimatorJob::EvaluateBlendClipAnimatorJob() : AbstractEvaluateClipAnimatorJob() + , m_handler(nullptr) { SET_JOB_RUN_STAT_TYPE(this, JobTypes::EvaluateBlendClipAnimator, 0) } diff --git a/src/animation/backend/evaluateclipanimatorjob.cpp b/src/animation/backend/evaluateclipanimatorjob.cpp index 7a568e829..914a38139 100644 --- a/src/animation/backend/evaluateclipanimatorjob.cpp +++ b/src/animation/backend/evaluateclipanimatorjob.cpp @@ -52,6 +52,7 @@ namespace Animation { EvaluateClipAnimatorJob::EvaluateClipAnimatorJob() : AbstractEvaluateClipAnimatorJob() + , m_handler(nullptr) { SET_JOB_RUN_STAT_TYPE(this, JobTypes::EvaluateClipAnimator, 0) } diff --git a/src/animation/backend/findrunningclipanimatorsjob.cpp b/src/animation/backend/findrunningclipanimatorsjob.cpp index fde3f7db8..1005914c7 100644 --- a/src/animation/backend/findrunningclipanimatorsjob.cpp +++ b/src/animation/backend/findrunningclipanimatorsjob.cpp @@ -48,8 +48,9 @@ namespace Animation { FindRunningClipAnimatorsJob::FindRunningClipAnimatorsJob() : Qt3DCore::QAspectJob() + , m_handler(nullptr) { - SET_JOB_RUN_STAT_TYPE(this, JobTypes::FindRunningClipAnimator, 0); + SET_JOB_RUN_STAT_TYPE(this, JobTypes::FindRunningClipAnimator, 0) } void FindRunningClipAnimatorsJob::setDirtyClipAnimators(const QVector &clipAnimatorHandles) diff --git a/src/animation/backend/loadanimationclipjob.cpp b/src/animation/backend/loadanimationclipjob.cpp index 977564c7f..93d4c2d9d 100644 --- a/src/animation/backend/loadanimationclipjob.cpp +++ b/src/animation/backend/loadanimationclipjob.cpp @@ -64,6 +64,7 @@ public: LoadAnimationClipJob::LoadAnimationClipJob() : Qt3DCore::QAspectJob(*new LoadAnimationClipJobPrivate) , m_animationClipHandles() + , m_handler(nullptr) { SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadAnimationClip, 0) } diff --git a/src/animation/frontend/qabstractchannelmapping.cpp b/src/animation/frontend/qabstractchannelmapping.cpp index 3249e6876..599ec6ed7 100644 --- a/src/animation/frontend/qabstractchannelmapping.cpp +++ b/src/animation/frontend/qabstractchannelmapping.cpp @@ -46,6 +46,7 @@ namespace Qt3DAnimation { QAbstractChannelMappingPrivate::QAbstractChannelMappingPrivate() : Qt3DCore::QNodePrivate() + , m_mappingType(QChannelMappingCreatedChangeBase::ChannelMapping) { } diff --git a/src/animation/frontend/qvertexblendanimation.cpp b/src/animation/frontend/qvertexblendanimation.cpp index 25468d4a7..143b9553a 100644 --- a/src/animation/frontend/qvertexblendanimation.cpp +++ b/src/animation/frontend/qvertexblendanimation.cpp @@ -192,8 +192,8 @@ void QVertexBlendAnimationPrivate::updateAnimation(float position) Qt3DRender::QGeometry *geometry = m_target->geometry(); // remove attributes from previous frame - if ((m_currentBase && (base != m_currentBase)) - || (m_currentTarget && (target != m_currentTarget))) { + if (m_currentBase && m_currentTarget && + (base != m_currentBase || target != m_currentTarget)) { const QVector baseAttributes = m_currentBase->attributeList(); const QVector targetAttributes = m_currentTarget->attributeList(); for (int i = 0; i < baseAttributes.size(); ++i) { diff --git a/src/core/aspects/qaspectmanager.cpp b/src/core/aspects/qaspectmanager.cpp index 71e05b34f..027264977 100644 --- a/src/core/aspects/qaspectmanager.cpp +++ b/src/core/aspects/qaspectmanager.cpp @@ -107,6 +107,7 @@ QAspectManager::QAspectManager(QObject *parent) , m_serviceLocator(new QServiceLocator()) , m_simulationLoopRunning(false) , m_driveMode(QAspectEngine::Automatic) + , m_postConstructorInit(nullptr) { qRegisterMetaType("QSurface*"); qCDebug(Aspects) << Q_FUNC_INFO; diff --git a/src/core/aspects/qaspectmanager_p.h b/src/core/aspects/qaspectmanager_p.h index d9a6c41ec..ebc148324 100644 --- a/src/core/aspects/qaspectmanager_p.h +++ b/src/core/aspects/qaspectmanager_p.h @@ -122,7 +122,6 @@ private: QAbstractAspectJobManager *m_jobManager; QChangeArbiter *m_changeArbiter; QScopedPointer m_serviceLocator; - bool m_mainLoopRunning; bool m_simulationLoopRunning; QAspectEngine::RunMode m_driveMode; QVector m_nodeTreeChanges; diff --git a/src/core/jobs/task.cpp b/src/core/jobs/task.cpp index 091aabfd6..7c3ebf6eb 100644 --- a/src/core/jobs/task.cpp +++ b/src/core/jobs/task.cpp @@ -57,6 +57,7 @@ RunnableInterface::~RunnableInterface() AspectTaskRunnable::AspectTaskRunnable() : m_pooler(nullptr) + , m_id(0) , m_reserved(false) { } diff --git a/src/core/resources/qframeallocator.cpp b/src/core/resources/qframeallocator.cpp index 61a82a2b4..e85ae4057 100644 --- a/src/core/resources/qframeallocator.cpp +++ b/src/core/resources/qframeallocator.cpp @@ -57,6 +57,8 @@ QT_BEGIN_NAMESPACE namespace Qt3DCore { QFrameAllocatorPrivate::QFrameAllocatorPrivate() + : m_maxObjectSize(0U) + , m_alignment(0U) { } diff --git a/src/core/transforms/qabstractskeleton.cpp b/src/core/transforms/qabstractskeleton.cpp index 5f3b05eb8..0cc1a28d2 100644 --- a/src/core/transforms/qabstractskeleton.cpp +++ b/src/core/transforms/qabstractskeleton.cpp @@ -47,6 +47,7 @@ namespace Qt3DCore { QAbstractSkeletonPrivate::QAbstractSkeletonPrivate() : Qt3DCore::QNodePrivate() + , m_type(QSkeletonCreatedChangeBase::Skeleton) , m_jointCount(0) { } diff --git a/src/core/transforms/sqt_p.h b/src/core/transforms/sqt_p.h index 5fdefccc8..e602cc71e 100644 --- a/src/core/transforms/sqt_p.h +++ b/src/core/transforms/sqt_p.h @@ -71,7 +71,9 @@ struct Sqt Sqt() : rotation() , scale(1.0f, 1.0f, 1.0f) + , pad1(0.f) , translation() + , pad2(0.f) {} inline QMatrix4x4 toMatrix() const diff --git a/src/input/backend/keyboardeventfilter.cpp b/src/input/backend/keyboardeventfilter.cpp index bd3bac5a7..e4f47f08e 100644 --- a/src/input/backend/keyboardeventfilter.cpp +++ b/src/input/backend/keyboardeventfilter.cpp @@ -53,6 +53,7 @@ namespace Input { KeyboardEventFilter::KeyboardEventFilter(QObject *parent) : QObject(parent) + , m_inputHandler(nullptr) { } diff --git a/src/input/backend/mouseeventfilter.cpp b/src/input/backend/mouseeventfilter.cpp index 618a64b15..48b30725a 100644 --- a/src/input/backend/mouseeventfilter.cpp +++ b/src/input/backend/mouseeventfilter.cpp @@ -53,6 +53,7 @@ namespace Input { MouseEventFilter::MouseEventFilter(QObject *parent) : QObject(parent) + , m_inputHandler(nullptr) { } diff --git a/src/logic/manager.cpp b/src/logic/manager.cpp index 3d096a342..db90e6ad9 100644 --- a/src/logic/manager.cpp +++ b/src/logic/manager.cpp @@ -56,6 +56,8 @@ namespace Logic { Manager::Manager() : m_logicHandlerManager(new HandlerManager) + , m_logicAspect(nullptr) + , m_executor(nullptr) , m_dt(0.0f) { } diff --git a/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp b/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp index ddb950f86..ab783102d 100644 --- a/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp +++ b/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp @@ -139,7 +139,8 @@ GLTFGeometryLoader::BufferData::BufferData(const QJsonObject &json) } GLTFGeometryLoader::AccessorData::AccessorData() - : type(QAttribute::Float) + : bufferViewIndex(0) + , type(QAttribute::Float) , dataSize(0) , count(0) , offset(0) diff --git a/src/quick3d/imports/scene3d/scene3ditem.cpp b/src/quick3d/imports/scene3d/scene3ditem.cpp index f3f7acd71..835485385 100644 --- a/src/quick3d/imports/scene3d/scene3ditem.cpp +++ b/src/quick3d/imports/scene3d/scene3ditem.cpp @@ -154,6 +154,7 @@ Scene3DItem::Scene3DItem(QQuickItem *parent) , m_disableClearWindow(false) , m_cameraAspectRatioMode(AutomaticAspectRatio) , m_compositingMode(FBO) + , m_dummySurface(nullptr) { setFlag(QQuickItem::ItemHasContents, true); setAcceptedMouseButtons(Qt::MouseButtonMask); diff --git a/src/quick3d/imports/scene3d/scene3drenderer.cpp b/src/quick3d/imports/scene3d/scene3drenderer.cpp index 1e375ccbb..7ef068c3e 100644 --- a/src/quick3d/imports/scene3d/scene3drenderer.cpp +++ b/src/quick3d/imports/scene3d/scene3drenderer.cpp @@ -162,6 +162,7 @@ Scene3DRenderer::Scene3DRenderer(Scene3DItem *item, Qt3DCore::QAspectEngine *asp , m_shouldRender(false) , m_dirtyViews(false) , m_allowRendering(0) + , m_compositingMode(Scene3DItem::FBO) { Q_CHECK_PTR(m_item); Q_CHECK_PTR(m_item->window()); diff --git a/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp b/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp index 55538ad1f..cfe39e8c7 100644 --- a/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp +++ b/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp @@ -76,6 +76,7 @@ Scene3DSGMaterialShader::Scene3DSGMaterialShader() : QSGMaterialShader() , m_matrixId(-1) , m_opacityId(-1) + , m_visibleId(-1) { } diff --git a/src/quick3d/quick3dscene2d/items/scene2dsharedobject.cpp b/src/quick3d/quick3dscene2d/items/scene2dsharedobject.cpp index cb9973f0a..aed624501 100644 --- a/src/quick3d/quick3dscene2d/items/scene2dsharedobject.cpp +++ b/src/quick3d/quick3dscene2d/items/scene2dsharedobject.cpp @@ -59,6 +59,7 @@ Scene2DSharedObject::Scene2DSharedObject(Scene2DManager *manager) , m_quickWindow(nullptr) , m_renderManager(manager) , m_surface(nullptr) + , m_renderThread(nullptr) , m_renderObject(nullptr) , m_disallowed(false) , m_quit(false) diff --git a/src/render/geometry/skeleton.cpp b/src/render/geometry/skeleton.cpp index 839a1a056..0452c020b 100644 --- a/src/render/geometry/skeleton.cpp +++ b/src/render/geometry/skeleton.cpp @@ -60,6 +60,8 @@ namespace Render { Skeleton::Skeleton() : BackendNode(Qt3DCore::QBackendNode::ReadWrite) , m_status(Qt3DCore::QSkeletonLoader::NotReady) + , m_createJoints(false) + , m_dataType(Unknown) , m_skeletonManager(nullptr) , m_jointManager(nullptr) { diff --git a/src/render/jobs/abstractpickingjob.cpp b/src/render/jobs/abstractpickingjob.cpp index 35e658535..092ab7d3b 100644 --- a/src/render/jobs/abstractpickingjob.cpp +++ b/src/render/jobs/abstractpickingjob.cpp @@ -63,6 +63,7 @@ AbstractPickingJob::AbstractPickingJob() , m_node(nullptr) , m_frameGraphRoot(nullptr) , m_renderSettings(nullptr) + , m_oneEnabledAtLeast(false) { } @@ -72,6 +73,7 @@ AbstractPickingJob::AbstractPickingJob(Qt3DCore::QAspectJobPrivate &dd) , m_node(nullptr) , m_frameGraphRoot(nullptr) , m_renderSettings(nullptr) + , m_oneEnabledAtLeast(false) { } diff --git a/src/render/jobs/filterproximitydistancejob.cpp b/src/render/jobs/filterproximitydistancejob.cpp index a25e88508..80a9e4777 100644 --- a/src/render/jobs/filterproximitydistancejob.cpp +++ b/src/render/jobs/filterproximitydistancejob.cpp @@ -43,8 +43,10 @@ namespace Render { FilterProximityDistanceJob::FilterProximityDistanceJob() : m_manager(nullptr) + , m_targetEntity(nullptr) + , m_distanceThresholdSquared(0.) { - SET_JOB_RUN_STAT_TYPE(this, JobTypes::ProximityFiltering, 0); + SET_JOB_RUN_STAT_TYPE(this, JobTypes::ProximityFiltering, 0) } void FilterProximityDistanceJob::run() diff --git a/src/render/jobs/updatetreeenabledjob.cpp b/src/render/jobs/updatetreeenabledjob.cpp index e97fc6414..5c6f2b378 100644 --- a/src/render/jobs/updatetreeenabledjob.cpp +++ b/src/render/jobs/updatetreeenabledjob.cpp @@ -71,6 +71,7 @@ void updateTreeEnabled(NodeManagers *manager, Entity *node, bool parentEnabled) UpdateTreeEnabledJob::UpdateTreeEnabledJob() : Qt3DCore::QAspectJob() , m_node(nullptr) + , m_manager(nullptr) { SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateTreeEnabled, 0); } diff --git a/src/render/materialsystem/shader.cpp b/src/render/materialsystem/shader.cpp index 58709b37e..017deabac 100644 --- a/src/render/materialsystem/shader.cpp +++ b/src/render/materialsystem/shader.cpp @@ -62,6 +62,7 @@ Shader::Shader() : BackendNode(ReadWrite) , m_isLoaded(false) , m_dna(0) + , m_oldDna(0) , m_graphicsContext(nullptr) , m_status(QShaderProgram::NotReady) , m_requiresFrontendSync(false) diff --git a/src/render/raycasting/qcollisionqueryresult.cpp b/src/render/raycasting/qcollisionqueryresult.cpp index 9d1e484b6..d2a443691 100644 --- a/src/render/raycasting/qcollisionqueryresult.cpp +++ b/src/render/raycasting/qcollisionqueryresult.cpp @@ -46,6 +46,7 @@ namespace RayCasting { QCollisionQueryResultPrivate::QCollisionQueryResultPrivate() : QSharedData() + , m_handle(0) { } diff --git a/src/render/raycasting/qcollisionqueryresult_p.h b/src/render/raycasting/qcollisionqueryresult_p.h index 67f6a34d0..d8e2056eb 100644 --- a/src/render/raycasting/qcollisionqueryresult_p.h +++ b/src/render/raycasting/qcollisionqueryresult_p.h @@ -86,8 +86,10 @@ public: Hit(Qt3DCore::QNodeId entity, const Vector3D &intersection, float distance, const Vector3D &uvw) : m_entityId(entity) + , m_type(Entity) , m_intersection(intersection) , m_distance(distance) + , m_primitiveIndex(0U) , m_uvw(uvw) { } diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp index 4b4199820..4d42b6291 100644 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp +++ b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp @@ -538,9 +538,9 @@ GLuint SubmissionContext::updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeI // ### TODO QTBUG-64757 this check is insufficient since the // texture may have changed to another one with the same size. That // case is not handled atm. - needsResize |= (rTex != nullptr && rTex->size() != s); - if (isActiveRenderTarget) { - if (attachment.m_point == QRenderTargetOutput::Color0) + if (rTex) { + needsResize |= rTex->size() != s; + if (isActiveRenderTarget && attachment.m_point == QRenderTargetOutput::Color0) m_renderTargetFormat = rTex->properties().format; } } diff --git a/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp b/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp index fa6218d6f..42f00d9f2 100644 --- a/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp +++ b/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp @@ -53,10 +53,12 @@ int renderViewInstanceCounter = 0; } // anonymous RenderViewBuilderJob::RenderViewBuilderJob() - : Qt3DCore::QAspectJob(), - m_renderView(nullptr) + : Qt3DCore::QAspectJob() + , m_renderView(nullptr) + , m_renderer(nullptr) + , m_index(0) { - SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderViewBuilder, renderViewInstanceCounter++); + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderViewBuilder, renderViewInstanceCounter++) } void RenderViewBuilderJob::run() diff --git a/src/render/renderers/opengl/renderer/rendercommand.cpp b/src/render/renderers/opengl/renderer/rendercommand.cpp index e60b17668..ee0bf0aec 100644 --- a/src/render/renderers/opengl/renderer/rendercommand.cpp +++ b/src/render/renderers/opengl/renderer/rendercommand.cpp @@ -48,6 +48,7 @@ RenderCommand::RenderCommand() : m_stateSet(nullptr) , m_depth(0.0f) , m_changeCost(0) + , m_shaderDna(0) , m_type(RenderCommand::Draw) , m_primitiveCount(0) , m_primitiveType(QGeometryRenderer::Triangles) diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp index aa9f4d1a5..48f622c07 100644 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ b/src/render/renderers/opengl/renderer/renderview.cpp @@ -238,11 +238,14 @@ RenderView::RenderView() : m_isDownloadBuffersEnable(false) , m_hasBlitFramebufferInfo(false) , m_renderer(nullptr) + , m_manager(nullptr) , m_devicePixelRatio(1.) - , m_viewport(QRectF(0.0f, 0.0f, 1.0f, 1.0f)) + , m_viewport(QRectF(0., 0., 1., 1.)) , m_gamma(2.2f) , m_surface(nullptr) , m_clearBuffer(QClearBuffers::None) + , m_clearDepthValue(1.f) + , m_clearStencilValue(0) , m_stateSet(nullptr) , m_noDraw(false) , m_compute(false) diff --git a/src/render/texture/texture.cpp b/src/render/texture/texture.cpp index d120c2b39..5ebde56b0 100644 --- a/src/render/texture/texture.cpp +++ b/src/render/texture/texture.cpp @@ -163,11 +163,11 @@ void Texture::syncFromFrontEnd(const QNode *frontEnd, bool firstTime) m_textureImageIds = ids; addDirtyFlag(DirtyImageGenerators); } - } - if (dnode->m_sharedTextureId != m_sharedTextureId) { - m_sharedTextureId = dnode->m_sharedTextureId; - addDirtyFlag(DirtySharedTextureId); + if (dnode->m_sharedTextureId != m_sharedTextureId) { + m_sharedTextureId = dnode->m_sharedTextureId; + addDirtyFlag(DirtySharedTextureId); + } } } -- cgit v1.2.3 From 7d8fd90a1d5e59b21b29da3e7fd0e593e3d94620 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Fri, 18 Oct 2019 17:33:09 +0200 Subject: Reduce number of allocations Grow one big vector rather than concatenating lots of small ones. Change-Id: I7c6ea653367c3703372606f23885e78b2bd0121e Reviewed-by: Paul Lemire --- src/render/jobs/updateworldtransformjob.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/render/jobs/updateworldtransformjob.cpp b/src/render/jobs/updateworldtransformjob.cpp index 13e14442f..fc661a7ce 100644 --- a/src/render/jobs/updateworldtransformjob.cpp +++ b/src/render/jobs/updateworldtransformjob.cpp @@ -65,11 +65,10 @@ struct TransformUpdate QMatrix4x4 worldTransformMatrix; }; -QVector updateWorldTransformAndBounds(NodeManagers *manager, Entity *node, const Matrix4x4 &parentTransform) +void updateWorldTransformAndBounds(NodeManagers *manager, Entity *node, const Matrix4x4 &parentTransform, QVector &updatedTransforms) { Matrix4x4 worldTransform(parentTransform); Transform *nodeTransform = node->renderComponent(); - QVector updatedTransforms; const bool hasTransformComponent = nodeTransform != nullptr && nodeTransform->isEnabled(); if (hasTransformComponent) @@ -85,9 +84,8 @@ QVector updateWorldTransformAndBounds(NodeManagers *manager, En for (const HEntity &handle : childrenHandles) { Entity *child = manager->renderNodesManager()->data(handle); if (child) - updatedTransforms += updateWorldTransformAndBounds(manager, child, worldTransform); + updateWorldTransformAndBounds(manager, child, worldTransform, updatedTransforms); } - return updatedTransforms; } } @@ -137,7 +135,7 @@ void UpdateWorldTransformJob::run() Entity *parent = m_node->parent(); if (parent != nullptr) parentTransform = *(parent->worldTransform()); - d->m_updatedTransforms = updateWorldTransformAndBounds(m_manager, m_node, parentTransform); + updateWorldTransformAndBounds(m_manager, m_node, parentTransform, d->m_updatedTransforms); qCDebug(Jobs) << "Exiting" << Q_FUNC_INFO << QThread::currentThread(); } -- cgit v1.2.3 From 7eb01e9532f080bef539808c0eb5e7c65cf34048 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Fri, 27 Sep 2019 14:31:21 +0200 Subject: Split RenderCommand generation and uniform update In most cases, we can generate the RenderCommands once and reuse them in subsequent frames only updating the uniforms. We still have to copy the RenderCommands as the renderer renders while we start preparing the next frame. This is still faster than regenerating them entirely. Regenerating the entire commands will happen only when FrameGraph or Scene structure changes. That should rarely be happening on a per frame basis. Next step could be to look at how to only update commands for Entity with Parameters that have changed. Change-Id: I202870850a46fcd3946f81bffddb7027d192f374 Reviewed-by: Paul Lemire --- src/render/backend/commandexecuter.cpp | 14 +- src/render/jobs/job_common_p.h | 10 +- src/render/renderers/opengl/jobs/jobs.pri | 6 +- .../renderers/opengl/jobs/renderviewbuilderjob.cpp | 107 ----- .../renderers/opengl/jobs/renderviewbuilderjob_p.h | 96 ---- .../opengl/jobs/renderviewcommandbuilderjob.cpp | 78 +++ .../opengl/jobs/renderviewcommandbuilderjob_p.h | 89 ++++ .../opengl/jobs/renderviewcommandupdaterjob.cpp | 85 ++++ .../opengl/jobs/renderviewcommandupdaterjob_p.h | 95 ++++ .../renderers/opengl/renderer/rendercommand.cpp | 14 + .../renderers/opengl/renderer/rendercommand_p.h | 17 +- src/render/renderers/opengl/renderer/renderer.cpp | 103 ++-- src/render/renderers/opengl/renderer/renderer_p.h | 4 +- .../renderers/opengl/renderer/renderercache_p.h | 2 + .../renderers/opengl/renderer/renderview.cpp | 526 +++++++++++---------- .../renderers/opengl/renderer/renderview_p.h | 20 +- .../opengl/renderer/renderviewbuilder.cpp | 427 +++++++++++------ .../opengl/renderer/renderviewbuilder_p.h | 31 +- tests/auto/render/renderer/tst_renderer.cpp | 73 ++- .../renderviewbuilder/tst_renderviewbuilder.cpp | 114 ++--- tests/auto/render/renderviews/tst_renderviews.cpp | 126 +++-- 21 files changed, 1194 insertions(+), 843 deletions(-) delete mode 100644 src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp delete mode 100644 src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h create mode 100644 src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp create mode 100644 src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h create mode 100644 src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp create mode 100644 src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h diff --git a/src/render/backend/commandexecuter.cpp b/src/render/backend/commandexecuter.cpp index 8bccb1437..3aea56ad0 100644 --- a/src/render/backend/commandexecuter.cpp +++ b/src/render/backend/commandexecuter.cpp @@ -346,15 +346,15 @@ void CommandExecuter::performAsynchronousCommandExecution(const QVectorclearStencilValue()); QJsonArray renderCommandsArray; - for (Render::RenderCommand *c : v->commands()) { + for (const Render::RenderCommand &c : v->commands()) { QJsonObject commandObj; Render::NodeManagers *nodeManagers = m_renderer->nodeManagers(); - commandObj.insert(QLatin1String("shader"), backendNodeToJSon(c->m_shader, nodeManagers->shaderManager())); - commandObj.insert(QLatin1String("vao"), double(c->m_vao.handle())); - commandObj.insert(QLatin1String("instanceCount"), c->m_instanceCount); - commandObj.insert(QLatin1String("geometry"), backendNodeToJSon(c->m_geometry, nodeManagers->geometryManager())); - commandObj.insert(QLatin1String("geometryRenderer"), backendNodeToJSon(c->m_geometryRenderer, nodeManagers->geometryRendererManager())); - commandObj.insert(QLatin1String("shaderParameterPack"), parameterPackToJson(c->m_parameterPack)); + commandObj.insert(QLatin1String("shader"), backendNodeToJSon(c.m_shader, nodeManagers->shaderManager())); + commandObj.insert(QLatin1String("vao"), double(c.m_vao.handle())); + commandObj.insert(QLatin1String("instanceCount"), c.m_instanceCount); + commandObj.insert(QLatin1String("geometry"), backendNodeToJSon(c.m_geometry, nodeManagers->geometryManager())); + commandObj.insert(QLatin1String("geometryRenderer"), backendNodeToJSon(c.m_geometryRenderer, nodeManagers->geometryRendererManager())); + commandObj.insert(QLatin1String("shaderParameterPack"), parameterPackToJson(c.m_parameterPack)); renderCommandsArray.push_back(commandObj); } diff --git a/src/render/jobs/job_common_p.h b/src/render/jobs/job_common_p.h index 7aa6f64ba..c3b581277 100644 --- a/src/render/jobs/job_common_p.h +++ b/src/render/jobs/job_common_p.h @@ -80,7 +80,7 @@ namespace JobTypes { LayerFiltering, EntityComponentTypeFiltering, MaterialParameterGathering, - RenderViewBuilder, + RenderCommandUpdater, GenericLambda, FrustumCulling, LightGathering, @@ -92,9 +92,9 @@ namespace JobTypes { DirtyShaderGathering, SendRenderCapture, SendBufferCapture, - SyncRenderViewCommandBuilding, + SyncRenderViewPreCommandUpdate, SyncRenderViewInitialization, - SyncRenderViewCommandBuilder, + SyncRenderViewPostCommandUpdate, SyncFrustumCulling, ClearBufferDrawIndex, UpdateMeshTriangleList, @@ -109,7 +109,9 @@ namespace JobTypes { UpdateLayerEntity, SendTextureChangesToFrontend, SendSetFenceHandlesToFrontend, - SendDisablesToFrontend + SendDisablesToFrontend, + RenderViewCommandBuilder, + SyncRenderViewPreCommandBuilding }; } // JobTypes diff --git a/src/render/renderers/opengl/jobs/jobs.pri b/src/render/renderers/opengl/jobs/jobs.pri index 021cd3242..d80b8bfd9 100644 --- a/src/render/renderers/opengl/jobs/jobs.pri +++ b/src/render/renderers/opengl/jobs/jobs.pri @@ -3,13 +3,15 @@ INCLUDEPATH += $$PWD SOURCES += \ $$PWD/filtercompatibletechniquejob.cpp \ $$PWD/materialparametergathererjob.cpp \ - $$PWD/renderviewbuilderjob.cpp \ + $$PWD/renderviewcommandbuilderjob.cpp \ + $$PWD/renderviewcommandupdaterjob.cpp \ $$PWD/renderviewinitializerjob.cpp \ $$PWD/renderviewjobutils.cpp HEADERS += \ $$PWD/filtercompatibletechniquejob_p.h \ $$PWD/materialparametergathererjob_p.h \ - $$PWD/renderviewbuilderjob_p.h \ + $$PWD/renderviewcommandbuilderjob_p.h \ + $$PWD/renderviewcommandupdaterjob_p.h \ $$PWD/renderviewinitializerjob_p.h \ $$PWD/renderviewjobutils_p.h diff --git a/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp b/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp deleted file mode 100644 index 42f00d9f2..000000000 --- a/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderviewbuilderjob_p.h" -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -namespace { -int renderViewInstanceCounter = 0; -} // anonymous - -RenderViewBuilderJob::RenderViewBuilderJob() - : Qt3DCore::QAspectJob() - , m_renderView(nullptr) - , m_renderer(nullptr) - , m_index(0) -{ - SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderViewBuilder, renderViewInstanceCounter++) -} - -void RenderViewBuilderJob::run() -{ - // Build RenderCommand should perform the culling as we have no way to determine - // if a child has a mesh in the view frustum while its parent isn't contained in it. - if (!m_renderView->noDraw()) { -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - gatherLightsTime = timer.nsecsElapsed(); - timer.restart(); -#endif - if (!m_renderView->isCompute()) - m_commands = m_renderView->buildDrawRenderCommands(m_renderables); - else - m_commands = m_renderView->buildComputeRenderCommands(m_renderables); -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - buildCommandsTime = timer.nsecsElapsed(); - timer.restart(); -#endif - } - -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - qint64 creationTime = timer.nsecsElapsed(); - timer.restart(); -#endif - -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - qint64 sortTime = timer.nsecsElapsed(); -#endif - -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - qDebug() << m_index - << "state:" << gatherStateTime / 1.0e6 - << "lights:" << gatherLightsTime / 1.0e6 - << "build commands:" << buildCommandsTime / 1.0e6 - << "sort:" << sortTime / 1.0e6; -#endif - - -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h b/src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h deleted file mode 100644 index c38f788b0..000000000 --- a/src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERVIEWBUILDERJOB_P_H -#define QT3DRENDER_RENDER_RENDERVIEWBUILDERJOB_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class RenderView; -class Renderer; -class RenderCommand; - -class Q_AUTOTEST_EXPORT RenderViewBuilderJob : public Qt3DCore::QAspectJob -{ -public: - RenderViewBuilderJob(); - - inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } - inline void setRenderer(Renderer *renderer) Q_DECL_NOTHROW { m_renderer = renderer; } - inline void setIndex(int index) Q_DECL_NOTHROW { m_index = index; } - inline void setRenderables(const QVector &renderables) Q_DECL_NOTHROW { m_renderables = renderables; } - QVector &commands() Q_DECL_NOTHROW { return m_commands; } - - void run() final; - -private: - RenderView *m_renderView; - Renderer *m_renderer; - int m_index; - QVector m_renderables; - QVector m_commands; -}; - -typedef QSharedPointer RenderViewBuilderJobPtr; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERVIEWBUILDERJOB_P_H diff --git a/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp b/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp new file mode 100644 index 000000000..658458568 --- /dev/null +++ b/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewcommandbuilderjob_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { +int renderViewInstanceCounter = 0; +} // anonymous + +RenderViewCommandBuilderJob::RenderViewCommandBuilderJob() + : Qt3DCore::QAspectJob() + , m_renderView(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderViewCommandBuilder, renderViewInstanceCounter++); +} + +void RenderViewCommandBuilderJob::run() +{ + if (!m_renderView->noDraw()) { + const bool isDraw = !m_renderView->isCompute(); + if (isDraw) + m_commandData = std::move(m_renderView->buildDrawRenderCommands( + m_entities)); + else + m_commandData = std::move(m_renderView->buildComputeRenderCommands( + m_entities)); + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h b/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h new file mode 100644 index 000000000..725f83b62 --- /dev/null +++ b/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h @@ -0,0 +1,89 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob +{ +public: + RenderViewCommandBuilderJob(); + + inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } + inline void setEntities(const QVector &entities) { m_entities = entities; } + inline QVector &commandData() { return m_commandData; } + + void run() final; + +private: + RenderView *m_renderView; + QVector m_entities; + QVector m_commandData; +}; + +typedef QSharedPointer RenderViewCommandBuilderJobPtr; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H diff --git a/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp b/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp new file mode 100644 index 000000000..d58b288e6 --- /dev/null +++ b/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewcommandupdaterjob_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { +int renderViewInstanceCounter = 0; +} // anonymous + +RenderViewCommandUpdaterJob::RenderViewCommandUpdaterJob() + : Qt3DCore::QAspectJob() + , m_renderView(nullptr) + , m_renderer(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderCommandUpdater, renderViewInstanceCounter++); +} + +void RenderViewCommandUpdaterJob::run() +{ + // Build RenderCommand should perform the culling as we have no way to determine + // if a child has a mesh in the view frustum while its parent isn't contained in it. + if (!m_renderView->noDraw()) { + // Update Render Commands (Uniform Change, Depth Change) + m_renderView->updateRenderCommand(m_renderables); + + // Copy commands out of cached -> ensures we can submit them for rendering + // while cache is rebuilt or modified for next frame + QVector commands; + commands.reserve(m_renderables.size()); + for (const EntityRenderCommandData *data : m_renderables) + commands.push_back(data->command); + m_commands = commands; + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h b/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h new file mode 100644 index 000000000..3fff5f1a0 --- /dev/null +++ b/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H +#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class RenderView; +class Renderer; + +class Q_AUTOTEST_EXPORT RenderViewCommandUpdaterJob : public Qt3DCore::QAspectJob +{ +public: + RenderViewCommandUpdaterJob(); + + inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } + inline void setRenderer(Renderer *renderer) Q_DECL_NOTHROW { m_renderer = renderer; } + inline void setRenderables(const QVector &renderables) Q_DECL_NOTHROW { m_renderables = renderables; } + + QVector &commands() Q_DECL_NOTHROW { return m_commands; } + + void run() final; + +private: + RenderView *m_renderView; + Renderer *m_renderer; + QVector m_renderables; + QVector m_commands; +}; + +typedef QSharedPointer RenderViewCommandUpdaterJobPtr; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H diff --git a/src/render/renderers/opengl/renderer/rendercommand.cpp b/src/render/renderers/opengl/renderer/rendercommand.cpp index ee0bf0aec..072127391 100644 --- a/src/render/renderers/opengl/renderer/rendercommand.cpp +++ b/src/render/renderers/opengl/renderer/rendercommand.cpp @@ -71,6 +71,20 @@ RenderCommand::RenderCommand() m_workGroups[2] = 0; } +bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept +{ + return (a.m_vao == b.m_vao && a.m_shader == b.m_shader && a.m_material == b.m_material && + a.m_stateSet == b.m_stateSet && a.m_geometry == b.m_geometry && a.m_geometryRenderer == b.m_geometryRenderer && + a.m_indirectDrawBuffer == b.m_indirectDrawBuffer && a.m_activeAttributes == b.m_activeAttributes && + a.m_depth == b.m_depth && a.m_changeCost == b.m_changeCost && a.m_shaderDna == b.m_shaderDna && + a.m_workGroups[0] == b.m_workGroups[0] && a.m_workGroups[1] == b.m_workGroups[1] && a.m_workGroups[2] == b.m_workGroups[2] && + a.m_primitiveCount == b.m_primitiveCount && a.m_primitiveType == b.m_primitiveType && a.m_restartIndexValue == b.m_restartIndexValue && + a.m_firstInstance == b.m_firstInstance && a.m_firstVertex == b.m_firstVertex && a.m_verticesPerPatch == b.m_verticesPerPatch && + a.m_instanceCount == b.m_instanceCount && a.m_indexOffset == b.m_indexOffset && a.m_indexAttributeByteOffset == b.m_indexAttributeByteOffset && + a.m_drawIndexed == b.m_drawIndexed && a.m_drawIndirect == b.m_drawIndirect && a.m_primitiveRestartEnabled == b.m_primitiveRestartEnabled && + a.m_isValid == b.m_isValid && a.m_computeCommand == b.m_computeCommand); +} + } // namespace Render } // namespace Qt3DRender diff --git a/src/render/renderers/opengl/renderer/rendercommand_p.h b/src/render/renderers/opengl/renderer/rendercommand_p.h index 61cc6d17d..58ab0cadd 100644 --- a/src/render/renderers/opengl/renderer/rendercommand_p.h +++ b/src/render/renderers/opengl/renderer/rendercommand_p.h @@ -55,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -69,6 +70,7 @@ namespace Qt3DRender { namespace Render { class RenderStateSet; +using RenderStateSetPtr = QSharedPointer; class Q_AUTOTEST_EXPORT RenderCommand { @@ -80,12 +82,13 @@ public: HMaterial m_material; // Purely used to ease sorting (minimize stage changes, binding changes ....) ShaderParameterPack m_parameterPack; // Might need to be reworked so as to be able to destroy the // Texture while submission is happening. - RenderStateSet *m_stateSet; + RenderStateSetPtr m_stateSet; HGeometry m_geometry; HGeometryRenderer m_geometryRenderer; HBuffer m_indirectDrawBuffer; // Reference to indirect draw buffer (valid only m_drawIndirect == true) + HComputeCommand m_computeCommand; // A QAttribute pack might be interesting // This is a temporary fix in the meantime, to remove the hacked methods in Technique @@ -121,6 +124,18 @@ public: bool m_isValid; }; +Q_AUTOTEST_EXPORT bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept; + +inline bool operator!=(const RenderCommand &lhs, const RenderCommand &rhs) noexcept +{ return !operator==(lhs, rhs); } + +struct EntityRenderCommandData +{ + Entity *entity; + RenderCommand command; + RenderPassParameterData passData; +}; + } // namespace Render } // namespace Qt3DRender diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index 121a6aa8f..f17e66108 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -432,6 +432,9 @@ void Renderer::initialize() m_waitForInitializationToBeCompleted.release(1); // Allow the aspect manager to proceed m_vsyncFrameAdvanceService->proceedToNextFrame(); + + // Force initial refresh + markDirty(AllDirty, nullptr); } /*! @@ -860,13 +863,13 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView QHash updatedTable; for (RenderView *rv: renderViews) { - const QVector commands = rv->commands(); - for (RenderCommand *command : commands) { + QVector &commands = rv->commands(); + for (RenderCommand &command : commands) { // Update/Create VAO - if (command->m_type == RenderCommand::Draw) { - Geometry *rGeometry = m_nodesManager->data(command->m_geometry); - GeometryRenderer *rGeometryRenderer = m_nodesManager->data(command->m_geometryRenderer); - Shader *shader = m_nodesManager->data(command->m_shader); + if (command.m_type == RenderCommand::Draw) { + Geometry *rGeometry = m_nodesManager->data(command.m_geometry); + GeometryRenderer *rGeometryRenderer = m_nodesManager->data(command.m_geometryRenderer); + Shader *shader = m_nodesManager->data(command.m_shader); // We should never have inserted a command for which these are null // in the first place @@ -879,15 +882,15 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView // Create VAO or return already created instance associated with command shader/geometry // (VAO is emulated if not supported) - createOrUpdateVAO(command, &vaoHandle, &vao); - command->m_vao = vaoHandle; + createOrUpdateVAO(&command, &vaoHandle, &vao); + command.m_vao = vaoHandle; // Avoids redoing the same thing for the same VAO if (!updatedTable.contains(vaoHandle)) { updatedTable.insert(vaoHandle, true); // Do we have any attributes that are dirty ? - const bool requiresPartialVAOUpdate = requiresVAOAttributeUpdate(rGeometry, command); + const bool requiresPartialVAOUpdate = requiresVAOAttributeUpdate(rGeometry, &command); // If true, we need to reupload all attributes to set the VAO // Otherwise only dirty attributes will be updates @@ -898,7 +901,7 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView if (rGeometry->isDirty()) m_dirtyGeometry.push_back(rGeometry); - if (!command->m_activeAttributes.isEmpty() && (requiresFullVAOUpdate || requiresPartialVAOUpdate)) { + if (!command.m_activeAttributes.isEmpty() && (requiresFullVAOUpdate || requiresPartialVAOUpdate)) { Profiling::GLTimeRecorder recorder(Profiling::VAOUpload); // Activate shader m_submissionContext->activateShader(shader->dna()); @@ -906,7 +909,7 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView vao->bind(); // Update or set Attributes and Buffers for the given rGeometry and Command // Note: this fills m_dirtyAttributes as well - if (updateVAOWithAttributes(rGeometry, command, shader, requiresFullVAOUpdate)) + if (updateVAOWithAttributes(rGeometry, &command, shader, requiresFullVAOUpdate)) vao->setSpecified(true); } } @@ -918,11 +921,11 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView rGeometryRenderer->unsetDirty(); // Prepare the ShaderParameterPack based on the active uniforms of the shader - shader->prepareUniforms(command->m_parameterPack); + shader->prepareUniforms(command.m_parameterPack); { // Scoped to show extent - command->m_isValid = !command->m_activeAttributes.empty(); - if (!command->m_isValid) + command.m_isValid = !command.m_activeAttributes.empty(); + if (!command.m_isValid) continue; // Update the draw command with what's going to be needed for the drawing @@ -942,7 +945,7 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView indirectAttribute = attribute; break; case QAttribute::VertexAttribute: { - if (command->m_activeAttributes.contains(attribute->nameId())) + if (command.m_activeAttributes.contains(attribute->nameId())) estimatedCount = qMax(attribute->count(), estimatedCount); break; } @@ -952,20 +955,20 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView } } - command->m_drawIndexed = (indexAttribute != nullptr); - command->m_drawIndirect = (indirectAttribute != nullptr); + command.m_drawIndexed = (indexAttribute != nullptr); + command.m_drawIndirect = (indirectAttribute != nullptr); // Update the draw command with all the information required for the drawing - if (command->m_drawIndexed) { - command->m_indexAttributeDataType = GraphicsContext::glDataTypeFromAttributeDataType(indexAttribute->vertexBaseType()); - command->m_indexAttributeByteOffset = indexAttribute->byteOffset() + rGeometryRenderer->indexBufferByteOffset(); + if (command.m_drawIndexed) { + command.m_indexAttributeDataType = GraphicsContext::glDataTypeFromAttributeDataType(indexAttribute->vertexBaseType()); + command.m_indexAttributeByteOffset = indexAttribute->byteOffset() + rGeometryRenderer->indexBufferByteOffset(); } // Note: we only care about the primitiveCount when using direct draw calls // For indirect draw calls it is assumed the buffer was properly set already - if (command->m_drawIndirect) { - command->m_indirectAttributeByteOffset = indirectAttribute->byteOffset(); - command->m_indirectDrawBuffer = m_nodesManager->bufferManager()->lookupHandle(indirectAttribute->bufferId()); + if (command.m_drawIndirect) { + command.m_indirectAttributeByteOffset = indirectAttribute->byteOffset(); + command.m_indirectDrawBuffer = m_nodesManager->bufferManager()->lookupHandle(indirectAttribute->bufferId()); } else { // Use the count specified by the GeometryRender // If not specify use the indexAttribute count if present @@ -978,22 +981,22 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView } } - command->m_primitiveCount = primitiveCount; - command->m_primitiveType = rGeometryRenderer->primitiveType(); - command->m_primitiveRestartEnabled = rGeometryRenderer->primitiveRestartEnabled(); - command->m_restartIndexValue = rGeometryRenderer->restartIndexValue(); - command->m_firstInstance = rGeometryRenderer->firstInstance(); - command->m_instanceCount = rGeometryRenderer->instanceCount(); - command->m_firstVertex = rGeometryRenderer->firstVertex(); - command->m_indexOffset = rGeometryRenderer->indexOffset(); - command->m_verticesPerPatch = rGeometryRenderer->verticesPerPatch(); + command.m_primitiveCount = primitiveCount; + command.m_primitiveType = rGeometryRenderer->primitiveType(); + command.m_primitiveRestartEnabled = rGeometryRenderer->primitiveRestartEnabled(); + command.m_restartIndexValue = rGeometryRenderer->restartIndexValue(); + command.m_firstInstance = rGeometryRenderer->firstInstance(); + command.m_instanceCount = rGeometryRenderer->instanceCount(); + command.m_firstVertex = rGeometryRenderer->firstVertex(); + command.m_indexOffset = rGeometryRenderer->indexOffset(); + command.m_verticesPerPatch = rGeometryRenderer->verticesPerPatch(); } // scope - } else if (command->m_type == RenderCommand::Compute) { - Shader *shader = m_nodesManager->data(command->m_shader); + } else if (command.m_type == RenderCommand::Compute) { + Shader *shader = m_nodesManager->data(command.m_shader); Q_ASSERT(shader); // Prepare the ShaderParameterPack based on the active uniforms of the shader - shader->prepareUniforms(command->m_parameterPack); + shader->prepareUniforms(command.m_parameterPack); } } } @@ -1834,6 +1837,7 @@ QVector Renderer::renderBinJobs() const bool computeableDirty = dirtyBitsForFrame & AbstractRenderer::ComputeDirty; const bool renderableDirty = dirtyBitsForFrame & AbstractRenderer::GeometryDirty; const bool materialCacheNeedsToBeRebuilt = shadersDirty || materialDirty || frameGraphDirty; + const bool renderCommandsDirty = materialCacheNeedsToBeRebuilt || renderableDirty || computeableDirty; // Rebuild Entity Layers list if layers are dirty if (layersDirty) @@ -1873,6 +1877,7 @@ QVector Renderer::renderBinJobs() builder.setLightGathererCacheNeedsToBeRebuilt(lightsDirty); builder.setMaterialGathererCacheNeedsToBeRebuilt(materialCacheNeedsToBeRebuilt); builder.setLightGathererCacheNeedsToBeRebuilt(lightsDirty); + builder.setRenderCommandCacheNeedsToBeRebuilt(renderCommandsDirty); builder.prepareJobs(); renderBinJobs.append(builder.buildJobHierachy()); @@ -2075,7 +2080,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) bool allCommandsIssued = true; // Render drawing commands - const QVector commands = rv->commands(); + QVector commands = rv->commands(); // Use the graphicscontext to submit the commands to the underlying // graphics API (OpenGL) @@ -2084,18 +2089,18 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) RenderStateSet *globalState = m_submissionContext->currentStateSet(); OpenGLVertexArrayObject *vao = nullptr; - for (RenderCommand *command : qAsConst(commands)) { + for (RenderCommand &command : commands) { - if (command->m_type == RenderCommand::Compute) { // Compute Call - performCompute(rv, command); + if (command.m_type == RenderCommand::Compute) { // Compute Call + performCompute(rv, &command); } else { // Draw Command // Check if we have a valid command that can be drawn - if (!command->m_isValid) { + if (!command.m_isValid) { allCommandsIssued = false; continue; } - vao = m_nodesManager->vaoManager()->data(command->m_vao); + vao = m_nodesManager->vaoManager()->data(command.m_vao); // something may have went wrong when initializing the VAO if (!vao->isSpecified()) { @@ -2106,7 +2111,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) { Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate); //// We activate the shader here - if (!m_submissionContext->activateShader(command->m_shaderDna)) { + if (!m_submissionContext->activateShader(command.m_shaderDna)) { allCommandsIssued = false; continue; } @@ -2121,7 +2126,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) { Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate); //// Update program uniforms - if (!m_submissionContext->setParameters(command->m_parameterPack)) { + if (!m_submissionContext->setParameters(command.m_parameterPack)) { allCommandsIssued = false; // If we have failed to set uniform (e.g unable to bind a texture) // we won't perform the draw call which could show invalid content @@ -2132,7 +2137,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) //// OpenGL State // TO DO: Make states not dependendent on their backend node for this step // Set state - RenderStateSet *localState = command->m_stateSet; + RenderStateSet *localState = command.m_stateSet.data(); { @@ -2140,8 +2145,8 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) // Merge the RenderCommand state with the globalState of the RenderView // Or restore the globalState if no stateSet for the RenderCommand if (localState != nullptr) { - command->m_stateSet->merge(globalState); - m_submissionContext->setCurrentStateSet(command->m_stateSet); + command.m_stateSet->merge(globalState); + m_submissionContext->setCurrentStateSet(localState); } else { m_submissionContext->setCurrentStateSet(globalState); } @@ -2151,7 +2156,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) // at that point //// Draw Calls - performDraw(command); + performDraw(&command); } } // end of RenderCommands loop @@ -2167,7 +2172,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) } bool Renderer::updateVAOWithAttributes(Geometry *geometry, - RenderCommand *command, + const RenderCommand *command, Shader *shader, bool forceUpdate) { @@ -2227,7 +2232,7 @@ bool Renderer::updateVAOWithAttributes(Geometry *geometry, } bool Renderer::requiresVAOAttributeUpdate(Geometry *geometry, - RenderCommand *command) const + const RenderCommand *command) const { const auto attributeIds = geometry->attributes(); diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index b1cd4aac5..db63f31d0 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -254,12 +254,12 @@ public: void prepareCommandsSubmission(const QVector &renderViews); bool executeCommandsSubmission(const RenderView *rv); bool updateVAOWithAttributes(Geometry *geometry, - RenderCommand *command, + const RenderCommand *command, Shader *shader, bool forceUpdate); bool requiresVAOAttributeUpdate(Geometry *geometry, - RenderCommand *command) const; + const RenderCommand *command) const; void setOpenGLContext(QOpenGLContext *context) override; const GraphicsApiFilterData *contextInfo() const; diff --git a/src/render/renderers/opengl/renderer/renderercache_p.h b/src/render/renderers/opengl/renderer/renderercache_p.h index 0e9c5d3cd..a1298f491 100644 --- a/src/render/renderers/opengl/renderer/renderercache_p.h +++ b/src/render/renderers/opengl/renderer/renderercache_p.h @@ -56,6 +56,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -73,6 +74,7 @@ struct RendererCache QVector renderableEntities; QVector computeEntities; EnvironmentLight* environmentLight; + QVector renderCommandData; }; QHash leafNodeCache; diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp index 48f622c07..c38ffae80 100644 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ b/src/render/renderers/opengl/renderer/renderview.cpp @@ -282,11 +282,6 @@ RenderView::RenderView() RenderView::~RenderView() { - delete m_stateSet; - for (RenderCommand *command : qAsConst(m_commands)) { - delete command->m_stateSet; - delete command; - } } namespace { @@ -294,7 +289,7 @@ namespace { template struct AdjacentSubRangeFinder { - static bool adjacentSubRange(RenderCommand *, RenderCommand *) + static bool adjacentSubRange(const RenderCommand &, const RenderCommand &) { Q_UNREACHABLE(); return false; @@ -304,47 +299,47 @@ struct AdjacentSubRangeFinder template<> struct AdjacentSubRangeFinder { - static bool adjacentSubRange(RenderCommand *a, RenderCommand *b) + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) { - return a->m_changeCost == b->m_changeCost; + return a.m_changeCost == b.m_changeCost; } }; template<> struct AdjacentSubRangeFinder { - static bool adjacentSubRange(RenderCommand *a, RenderCommand *b) + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) { - return a->m_depth == b->m_depth; + return a.m_depth == b.m_depth; } }; template<> struct AdjacentSubRangeFinder { - static bool adjacentSubRange(RenderCommand *a, RenderCommand *b) + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) { - return a->m_shaderDna == b->m_shaderDna; + return a.m_shaderDna == b.m_shaderDna; } }; template<> struct AdjacentSubRangeFinder { - static bool adjacentSubRange(RenderCommand *a, RenderCommand *b) + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) { - return a->m_depth == b->m_depth; + return a.m_depth == b.m_depth; } }; template<> struct AdjacentSubRangeFinder { - static bool adjacentSubRange(RenderCommand *a, RenderCommand *b) + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) { // Two renderCommands are adjacent if one contains all the other command's textures - QVector texturesA = a->m_parameterPack.textures(); - QVector texturesB = b->m_parameterPack.textures(); + QVector texturesA = a.m_parameterPack.textures(); + QVector texturesB = b.m_parameterPack.textures(); if (texturesB.size() > texturesA.size()) qSwap(texturesA, texturesB); @@ -359,7 +354,7 @@ struct AdjacentSubRangeFinder }; template -int advanceUntilNonAdjacent(const QVector &commands, +int advanceUntilNonAdjacent(const QVector &commands, const int beg, const int end, Predicate pred) { int i = beg + 1; @@ -372,7 +367,7 @@ int advanceUntilNonAdjacent(const QVector &commands, } -using CommandIt = QVector::iterator; +using CommandIt = QVector::iterator; template struct SubRangeSorter @@ -390,8 +385,8 @@ struct SubRangeSorter { static void sortSubRange(CommandIt begin, const CommandIt end) { - std::stable_sort(begin, end, [] (RenderCommand *a, RenderCommand *b) { - return a->m_changeCost > b->m_changeCost; + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_changeCost > b.m_changeCost; }); } }; @@ -401,8 +396,8 @@ struct SubRangeSorter { static void sortSubRange(CommandIt begin, const CommandIt end) { - std::stable_sort(begin, end, [] (RenderCommand *a, RenderCommand *b) { - return a->m_depth > b->m_depth; + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_depth > b.m_depth; }); } }; @@ -413,8 +408,8 @@ struct SubRangeSorter static void sortSubRange(CommandIt begin, const CommandIt end) { // First we sort by shaderDNA - std::stable_sort(begin, end, [] (RenderCommand *a, RenderCommand *b) { - return a->m_shaderDna > b->m_shaderDna; + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_shaderDna > b.m_shaderDna; }); } }; @@ -424,8 +419,8 @@ struct SubRangeSorter { static void sortSubRange(CommandIt begin, const CommandIt end) { - std::stable_sort(begin, end, [] (RenderCommand *a, RenderCommand *b) { - return a->m_depth < b->m_depth; + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_depth < b.m_depth; }); } }; @@ -435,9 +430,9 @@ struct SubRangeSorter { static void sortSubRange(CommandIt begin, const CommandIt end) { - std::stable_sort(begin, end, [] (RenderCommand *a, RenderCommand *b) { - QVector texturesA = a->m_parameterPack.textures(); - QVector texturesB = b->m_parameterPack.textures(); + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + QVector texturesA = a.m_parameterPack.textures(); + QVector texturesB = b.m_parameterPack.textures(); const int originalTextureASize = texturesA.size(); @@ -456,7 +451,7 @@ struct SubRangeSorter } }; -int findSubRange(const QVector &commands, +int findSubRange(const QVector &commands, const int begin, const int end, const QSortPolicy::SortType sortType) { @@ -477,14 +472,14 @@ int findSubRange(const QVector &commands, } } -void sortByMaterial(QVector &commands, int begin, const int end) +void sortByMaterial(QVector &commands, int begin, const int end) { // We try to arrange elements so that their rendering cost is minimized for a given shader int rangeEnd = advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); while (begin != end) { if (begin + 1 < rangeEnd) { - std::stable_sort(commands.begin() + begin + 1, commands.begin() + rangeEnd, [] (RenderCommand *a, RenderCommand *b){ - return a->m_material.handle() < b->m_material.handle(); + std::stable_sort(commands.begin() + begin + 1, commands.begin() + rangeEnd, [] (const RenderCommand &a, const RenderCommand &b){ + return a.m_material.handle() < b.m_material.handle(); }); } begin = rangeEnd; @@ -492,7 +487,7 @@ void sortByMaterial(QVector &commands, int begin, const int end } } -void sortCommandRange(QVector &commands, int begin, const int end, const int level, +void sortCommandRange(QVector &commands, int begin, const int end, const int level, const QVector &sortingTypes) { if (level >= sortingTypes.size()) @@ -542,20 +537,21 @@ void RenderView::sort() // Minimize uniform changes int i = 0; - while (i < m_commands.size()) { + const int commandSize = m_commands.size(); + while (i < commandSize) { int j = i; // Advance while commands share the same shader - while (i < m_commands.size() && m_commands[j]->m_shaderDna == m_commands[i]->m_shaderDna) + while (i < commandSize && m_commands[j].m_shaderDna == m_commands[i].m_shaderDna) ++i; if (i - j > 0) { // Several commands have the same shader, so we minimize uniform changes - PackUniformHash cachedUniforms = m_commands[j++]->m_parameterPack.uniforms(); + PackUniformHash cachedUniforms = m_commands[j++].m_parameterPack.uniforms(); while (j < i) { // We need the reference here as we are modifying the original container // not the copy - PackUniformHash &uniforms = m_commands.at(j)->m_parameterPack.m_uniforms; + PackUniformHash &uniforms = m_commands[j].m_parameterPack.m_uniforms; PackUniformHash::iterator it = uniforms.begin(); const PackUniformHash::iterator end = uniforms.end(); @@ -571,6 +567,9 @@ void RenderView::sort() if (it.value() == refValue) { it = uniforms.erase(it); } else { + // Record updated value so that subsequent comparison + // for the next command will be made againts latest + // uniform value cachedUniforms.insert(it.key(), it.value()); ++it; } @@ -622,19 +621,12 @@ void RenderView::addClearBuffers(const ClearBuffers *cb) { } // If we are there, we know that entity had a GeometryRenderer + Material -QVector RenderView::buildDrawRenderCommands(const QVector &entities) const +QVector RenderView::buildDrawRenderCommands(const QVector &entities) const { - // Note: since many threads can be building render commands - // we need to ensure that the UniformBlockValueBuilder they are using - // is only accessed from the same thread - UniformBlockValueBuilder *builder = new UniformBlockValueBuilder(); - builder->shaderDataManager = m_manager->shaderDataManager(); - builder->textureManager = m_manager->textureManager(); - m_localData.setLocalData(builder); - - QVector commands; + QVector commands; commands.reserve(entities.size()); + for (Entity *entity : entities) { GeometryRenderer *geometryRenderer = nullptr; HGeometryRenderer geometryRendererHandle = entity->componentHandle(); @@ -651,84 +643,47 @@ QVector RenderView::buildDrawRenderCommands(const QVectorm_geometryRenderer = geometryRendererHandle; - command->m_geometry = m_manager->geometryManager()->lookupHandle(geometryRenderer->geometryId()); - - // Project the camera-to-object-center vector onto the camera - // view vector. This gives a depth value suitable as the key - // for BackToFront sorting. - command->m_depth = Vector3D::dotProduct(entity->worldBoundingVolume()->center() - m_data.m_eyePos, m_data.m_eyeViewDir); - command->m_material = materialHandle; + RenderCommand command = {}; + command.m_geometryRenderer = geometryRendererHandle; + command.m_geometry = m_manager->geometryManager()->lookupHandle(geometryRenderer->geometryId()); + + command.m_material = materialHandle; // For RenderPass based states we use the globally set RenderState // if no renderstates are defined as part of the pass. That means: // RenderPass { renderStates: [] } will use the states defined by // StateSet in the FrameGraph RenderPass *pass = passData.pass; if (pass->hasRenderStates()) { - command->m_stateSet = new RenderStateSet(); - addStatesToRenderStateSet(command->m_stateSet, pass->renderStates(), m_manager->renderStateManager()); + command.m_stateSet = RenderStateSetPtr::create(); + addStatesToRenderStateSet(command.m_stateSet.data(), pass->renderStates(), m_manager->renderStateManager()); if (m_stateSet != nullptr) - command->m_stateSet->merge(m_stateSet); - command->m_changeCost = m_renderer->defaultRenderState()->changeCost(command->m_stateSet); + command.m_stateSet->merge(m_stateSet); + command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); } + command.m_shader = m_manager->lookupHandle(pass->shaderProgram()); - // Pick which lights to take in to account. - // For now decide based on the distance by taking the MAX_LIGHTS closest lights. - // Replace with more sophisticated mechanisms later. - // Copy vector so that we can sort it concurrently and we only want to sort the one for the current command - QVector lightSources = m_lightSources; - if (lightSources.size() > 1) { - const Vector3D entityCenter = entity->worldBoundingVolume()->center(); - std::sort(lightSources.begin(), lightSources.end(), - [&] (const LightSource &a, const LightSource &b) { - const float distA = entityCenter.distanceToPoint(a.entity->worldBoundingVolume()->center()); - const float distB = entityCenter.distanceToPoint(b.entity->worldBoundingVolume()->center()); - return distA < distB; - }); - } - - ParameterInfoList globalParameters = passData.parameterInfo; - // setShaderAndUniforms can initialize a localData - // make sure this is cleared before we leave this function - setShaderAndUniforms(command, - pass, - globalParameters, - entity, - lightSources.mid(0, std::max(lightSources.size(), MAX_LIGHTS)), - m_environmentLight); - - commands.append(command); + const EntityRenderCommandData commandData = { entity, command, passData }; + commands.append(commandData); } } } - // We reset the local data once we are done with it - m_localData.setLocalData(nullptr); - return commands; } -QVector RenderView::buildComputeRenderCommands(const QVector &entities) const +QVector RenderView::buildComputeRenderCommands(const QVector &entities) const { - // Note: since many threads can be building render commands - // we need to ensure that the UniformBlockValueBuilder they are using - // is only accessed from the same thread - UniformBlockValueBuilder *builder = new UniformBlockValueBuilder(); - builder->shaderDataManager = m_manager->shaderDataManager(); - builder->textureManager = m_manager->textureManager(); - m_localData.setLocalData(builder); - // If the RenderView contains only a ComputeDispatch then it cares about // A ComputeDispatch is also implicitely a NoDraw operation // enabled flag // layer component // material/effect/technique/parameters/filters/ - QVector commands; + QVector commands; commands.reserve(entities.size()); for (Entity *entity : entities) { ComputeCommand *computeJob = nullptr; - if ((computeJob = entity->renderComponent()) != nullptr + HComputeCommand computeCommandHandle = entity->componentHandle(); + if ((computeJob = nodeManagers()->computeJobManager()->data(computeCommandHandle)) != nullptr && computeJob->isEnabled()) { // Note: if frameCount has reached 0 in the previous frame, isEnabled @@ -742,41 +697,96 @@ QVector RenderView::buildComputeRenderCommands(const QVectorhasRenderStates()) { - command->m_stateSet = new RenderStateSet(); - addStatesToRenderStateSet(command->m_stateSet, pass->renderStates(), m_manager->renderStateManager()); + command.m_stateSet = RenderStateSetPtr::create(); + addStatesToRenderStateSet(command.m_stateSet.data(), pass->renderStates(), m_manager->renderStateManager()); // Merge per pass stateset with global stateset // so that the local stateset only overrides if (m_stateSet != nullptr) - command->m_stateSet->merge(m_stateSet); - command->m_changeCost = m_renderer->defaultRenderState()->changeCost(command->m_stateSet); + command.m_stateSet->merge(m_stateSet); + command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); } + command.m_shader = m_manager->lookupHandle(pass->shaderProgram()); + command.m_computeCommand = computeCommandHandle; + command.m_type = RenderCommand::Compute; + command.m_workGroups[0] = std::max(m_workGroups[0], computeJob->x()); + command.m_workGroups[1] = std::max(m_workGroups[1], computeJob->y()); + command.m_workGroups[2] = std::max(m_workGroups[2], computeJob->z()); + + const EntityRenderCommandData commandData = { entity, command, passData }; + commands.append(commandData); + } + } + } - command->m_type = RenderCommand::Compute; - command->m_workGroups[0] = std::max(m_workGroups[0], computeJob->x()); - command->m_workGroups[1] = std::max(m_workGroups[1], computeJob->y()); - command->m_workGroups[2] = std::max(m_workGroups[2], computeJob->z()); - - ParameterInfoList globalParameters = passData.parameterInfo; - setShaderAndUniforms(command, - pass, - globalParameters, - entity, - QVector(), - nullptr); - commands.append(command); + return commands; +} + +void RenderView::updateRenderCommand(QVector &renderCommandData) +{ + // Note: since many threads can be building render commands + // we need to ensure that the UniformBlockValueBuilder they are using + // is only accessed from the same thread + UniformBlockValueBuilder *builder = new UniformBlockValueBuilder(); + builder->shaderDataManager = m_manager->shaderDataManager(); + builder->textureManager = m_manager->textureManager(); + m_localData.setLocalData(builder); + + for (EntityRenderCommandData *commandData : renderCommandData) { + Entity *entity = commandData->entity; + RenderPassParameterData passData = commandData->passData; + RenderCommand &command = commandData->command; + + // Pick which lights to take in to account. + // For now decide based on the distance by taking the MAX_LIGHTS closest lights. + // Replace with more sophisticated mechanisms later. + // Copy vector so that we can sort it concurrently and we only want to sort the one for the current command + QVector lightSources; + EnvironmentLight *environmentLight = nullptr; + + if (command.m_type == RenderCommand::Draw) { + // Project the camera-to-object-center vector onto the camera + // view vector. This gives a depth value suitable as the key + // for BackToFront sorting. + command.m_depth = Vector3D::dotProduct(entity->worldBoundingVolume()->center() - m_data.m_eyePos, m_data.m_eyeViewDir); + + environmentLight = m_environmentLight; + lightSources = m_lightSources; + + if (lightSources.size() > 1) { + const Vector3D entityCenter = entity->worldBoundingVolume()->center(); + std::sort(lightSources.begin(), lightSources.end(), + [&] (const LightSource &a, const LightSource &b) { + const float distA = entityCenter.distanceToPoint(a.entity->worldBoundingVolume()->center()); + const float distB = entityCenter.distanceToPoint(b.entity->worldBoundingVolume()->center()); + return distA < distB; + }); } + lightSources = lightSources.mid(0, std::max(lightSources.size(), MAX_LIGHTS)); + } else { // Compute + // Note: if frameCount has reached 0 in the previous frame, isEnabled + // would be false + ComputeCommand *computeJob = m_manager->computeJobManager()->data(command.m_computeCommand); + if (computeJob->runType() == QComputeCommand::Manual) + computeJob->updateFrameCount(); } + + ParameterInfoList globalParameters = passData.parameterInfo; + // setShaderAndUniforms can initialize a localData + // make sure this is cleared before we leave this function + setShaderAndUniforms(&command, + globalParameters, + entity, + lightSources, + environmentLight); } // We reset the local data once we are done with it m_localData.setLocalData(nullptr); - - return commands; } void RenderView::updateMatrices() @@ -911,7 +921,6 @@ void RenderView::setDefaultUniformBlockShaderDataValue(ShaderParameterPack &unif } void RenderView::setShaderAndUniforms(RenderCommand *command, - RenderPass *rPass, ParameterInfoList ¶meters, Entity *entity, const QVector &activeLightSources, @@ -927,163 +936,158 @@ void RenderView::setShaderAndUniforms(RenderCommand *command, // For each ParameterBinder in the RenderPass -> create a QUniformPack // Once that works, improve that to try and minimize QUniformPack updates - if (rPass != nullptr) { - // Index Shader by Shader UUID - command->m_shader = m_manager->lookupHandle(rPass->shaderProgram()); - Shader *shader = m_manager->data(command->m_shader); - if (shader != nullptr && shader->isLoaded()) { - command->m_shaderDna = shader->dna(); - - // Builds the QUniformPack, sets shader standard uniforms and store attributes name / glname bindings - // If a parameter is defined and not found in the bindings it is assumed to be a binding of Uniform type with the glsl name - // equals to the parameter name - const QVector uniformNamesIds = shader->uniformsNamesIds(); - const QVector uniformBlockNamesIds = shader->uniformBlockNamesIds(); - const QVector shaderStorageBlockNamesIds = shader->storageBlockNamesIds(); - const QVector attributeNamesIds = shader->attributeNamesIds(); - - // Set fragData Name and index - // Later on we might want to relink the shader if attachments have changed - // But for now we set them once and for all + // Index Shader by Shader UUID + Shader *shader = m_manager->data(command->m_shader); + if (shader != nullptr && shader->isLoaded()) { + command->m_shaderDna = shader->dna(); + + // Builds the QUniformPack, sets shader standard uniforms and store attributes name / glname bindings + // If a parameter is defined and not found in the bindings it is assumed to be a binding of Uniform type with the glsl name + // equals to the parameter name + const QVector uniformNamesIds = shader->uniformsNamesIds(); + const QVector uniformBlockNamesIds = shader->uniformBlockNamesIds(); + const QVector shaderStorageBlockNamesIds = shader->storageBlockNamesIds(); + const QVector attributeNamesIds = shader->attributeNamesIds(); + + // Set fragData Name and index + // Later on we might want to relink the shader if attachments have changed + // But for now we set them once and for all + if (!m_renderTarget.isNull() && !shader->isLoaded()) { QHash fragOutputs; - if (!m_renderTarget.isNull() && !shader->isLoaded()) { - const auto atts = m_attachmentPack.attachments(); - for (const Attachment &att : atts) { - if (att.m_point <= QRenderTargetOutput::Color15) - fragOutputs.insert(att.m_name, att.m_point); - } + const auto atts = m_attachmentPack.attachments(); + for (const Attachment &att : atts) { + if (att.m_point <= QRenderTargetOutput::Color15) + fragOutputs.insert(att.m_name, att.m_point); } + // Set frag outputs in the shaders if hash not empty + if (!fragOutputs.isEmpty()) + shader->setFragOutputs(fragOutputs); + } - if (!uniformNamesIds.isEmpty() || !attributeNamesIds.isEmpty() || - !shaderStorageBlockNamesIds.isEmpty() || !attributeNamesIds.isEmpty()) { + if (!uniformNamesIds.isEmpty() || !attributeNamesIds.isEmpty() || + !shaderStorageBlockNamesIds.isEmpty() || !attributeNamesIds.isEmpty()) { - // Set default standard uniforms without bindings - const Matrix4x4 worldTransform = *(entity->worldTransform()); - for (const int uniformNameId : uniformNamesIds) { - if (ms_standardUniformSetters.contains(uniformNameId)) - setStandardUniformValue(command->m_parameterPack, uniformNameId, uniformNameId, entity, worldTransform); - } + // Set default standard uniforms without bindings + const Matrix4x4 worldTransform = *(entity->worldTransform()); - // Set default attributes - for (const int attributeNameId : attributeNamesIds) - command->m_activeAttributes.push_back(attributeNameId); - - // Parameters remaining could be - // -> uniform scalar / vector - // -> uniform struct / arrays - // -> uniform block / array (4.3) - // -> ssbo block / array (4.3) - - ParameterInfoList::const_iterator it = parameters.cbegin(); - const ParameterInfoList::const_iterator parametersEnd = parameters.cend(); - - while (it != parametersEnd) { - Parameter *param = m_manager->data(it->handle); - const UniformValue &uniformValue = param->uniformValue(); - if (uniformNamesIds.contains(it->nameId)) { // Parameter is a regular uniform - setUniformValue(command->m_parameterPack, it->nameId, uniformValue); - } else if (uniformBlockNamesIds.indexOf(it->nameId) != -1) { // Parameter is a uniform block - setUniformBlockValue(command->m_parameterPack, shader, shader->uniformBlockForBlockNameId(it->nameId), uniformValue); - } else if (shaderStorageBlockNamesIds.indexOf(it->nameId) != -1) { // Parameters is a SSBO - setShaderStorageValue(command->m_parameterPack, shader, shader->storageBlockForBlockNameId(it->nameId), uniformValue); - } else { // Parameter is a struct - ShaderData *shaderData = nullptr; - if (uniformValue.valueType() == UniformValue::NodeId && - (shaderData = m_manager->shaderDataManager()->lookupResource(*uniformValue.constData())) != nullptr) { - // Try to check if we have a struct or array matching a QShaderData parameter - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, StringToInt::lookupString(it->nameId)); - } - // Otherwise: param unused by current shader + for (const int uniformNameId : uniformNamesIds) { + if (ms_standardUniformSetters.contains(uniformNameId)) + setStandardUniformValue(command->m_parameterPack, uniformNameId, uniformNameId, entity, worldTransform); + } + + // Set default attributes + command->m_activeAttributes = attributeNamesIds; + + // Parameters remaining could be + // -> uniform scalar / vector + // -> uniform struct / arrays + // -> uniform block / array (4.3) + // -> ssbo block / array (4.3) + + ParameterInfoList::const_iterator it = parameters.cbegin(); + const ParameterInfoList::const_iterator parametersEnd = parameters.cend(); + + while (it != parametersEnd) { + Parameter *param = m_manager->data(it->handle); + const UniformValue &uniformValue = param->uniformValue(); + if (uniformNamesIds.contains(it->nameId)) { // Parameter is a regular uniform + setUniformValue(command->m_parameterPack, it->nameId, uniformValue); + } else if (uniformBlockNamesIds.indexOf(it->nameId) != -1) { // Parameter is a uniform block + setUniformBlockValue(command->m_parameterPack, shader, shader->uniformBlockForBlockNameId(it->nameId), uniformValue); + } else if (shaderStorageBlockNamesIds.indexOf(it->nameId) != -1) { // Parameters is a SSBO + setShaderStorageValue(command->m_parameterPack, shader, shader->storageBlockForBlockNameId(it->nameId), uniformValue); + } else { // Parameter is a struct + ShaderData *shaderData = nullptr; + if (uniformValue.valueType() == UniformValue::NodeId && + (shaderData = m_manager->shaderDataManager()->lookupResource(*uniformValue.constData())) != nullptr) { + // Try to check if we have a struct or array matching a QShaderData parameter + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, StringToInt::lookupString(it->nameId)); } - ++it; + // Otherwise: param unused by current shader } + ++it; + } + + // Lights + + int lightIdx = 0; + for (const LightSource &lightSource : activeLightSources) { + if (lightIdx == MAX_LIGHTS) + break; + Entity *lightEntity = lightSource.entity; + const Vector3D worldPos = lightEntity->worldBoundingVolume()->center(); + for (Light *light : lightSource.lights) { + if (!light->isEnabled()) + continue; - // Lights + ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(light->shaderData()); + if (!shaderData) + continue; - int lightIdx = 0; - for (const LightSource &lightSource : activeLightSources) { if (lightIdx == MAX_LIGHTS) break; - Entity *lightEntity = lightSource.entity; - const Vector3D worldPos = lightEntity->worldBoundingVolume()->center(); - for (Light *light : lightSource.lights) { - if (!light->isEnabled()) - continue; - - ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(light->shaderData()); - if (!shaderData) - continue; - - if (lightIdx == MAX_LIGHTS) - break; - - // Note: implicit conversion of values to UniformValue - setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[lightIdx], worldPos); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[lightIdx], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[lightIdx], 0.5f); - - setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[lightIdx], worldPos); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[lightIdx], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[lightIdx], 0.5f); - - // There is no risk in doing that even if multithreaded - // since we are sure that a shaderData is unique for a given light - // and won't ever be referenced as a Component either - Matrix4x4 *worldTransform = lightEntity->worldTransform(); - if (worldTransform) - shaderData->updateWorldTransform(*worldTransform); - - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_NAMES[lightIdx]); - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_UNROLL_NAMES[lightIdx]); - ++lightIdx; - } - } - if (uniformNamesIds.contains(LIGHT_COUNT_NAME_ID)) - setUniformValue(command->m_parameterPack, LIGHT_COUNT_NAME_ID, UniformValue(qMax((environmentLight ? 0 : 1), lightIdx))); - - // If no active light sources and no environment light, add a default light - if (activeLightSources.isEmpty() && !environmentLight) { // Note: implicit conversion of values to UniformValue - setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[0], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[0], 0.5f); - - setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[0], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[0], 0.5f); + setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[lightIdx], worldPos); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[lightIdx], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[lightIdx], 0.5f); + + setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[lightIdx], worldPos); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[lightIdx], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[lightIdx], 0.5f); + + + // There is no risk in doing that even if multithreaded + // since we are sure that a shaderData is unique for a given light + // and won't ever be referenced as a Component either + Matrix4x4 *worldTransform = lightEntity->worldTransform(); + if (worldTransform) + shaderData->updateWorldTransform(*worldTransform); + + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_NAMES[lightIdx]); + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_UNROLL_NAMES[lightIdx]); + ++lightIdx; } + } - // Environment Light - int envLightCount = 0; - if (environmentLight && environmentLight->isEnabled()) { - ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(environmentLight->shaderData()); - if (shaderData) { - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, QStringLiteral("envLight")); - envLightCount = 1; - } - } else { - // with some drivers, samplers (like the envbox sampler) need to be bound even though - // they may not be actually used, otherwise draw calls can fail - static const int irradianceId = StringToInt::lookupId(QLatin1String("envLight.irradiance")); - static const int specularId = StringToInt::lookupId(QLatin1String("envLight.specular")); - setUniformValue(command->m_parameterPack, irradianceId, m_renderer->submissionContext()->maxTextureUnitsCount()); - setUniformValue(command->m_parameterPack, specularId, m_renderer->submissionContext()->maxTextureUnitsCount()); + if (uniformNamesIds.contains(LIGHT_COUNT_NAME_ID)) + setUniformValue(command->m_parameterPack, LIGHT_COUNT_NAME_ID, UniformValue(qMax((environmentLight ? 0 : 1), lightIdx))); + + // If no active light sources and no environment light, add a default light + if (activeLightSources.isEmpty() && !environmentLight) { + // Note: implicit conversion of values to UniformValue + setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[0], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[0], 0.5f); + + setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[0], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[0], 0.5f); + } + + // Environment Light + int envLightCount = 0; + if (environmentLight && environmentLight->isEnabled()) { + ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(environmentLight->shaderData()); + if (shaderData) { + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, QStringLiteral("envLight")); + envLightCount = 1; } - setUniformValue(command->m_parameterPack, StringToInt::lookupId(QStringLiteral("envLightCount")), envLightCount); + } else { + // with some drivers, samplers (like the envbox sampler) need to be bound even though + // they may not be actually used, otherwise draw calls can fail + static const int irradianceId = StringToInt::lookupId(QLatin1String("envLight.irradiance")); + static const int specularId = StringToInt::lookupId(QLatin1String("envLight.specular")); + setUniformValue(command->m_parameterPack, irradianceId, m_renderer->submissionContext()->maxTextureUnitsCount()); + setUniformValue(command->m_parameterPack, specularId, m_renderer->submissionContext()->maxTextureUnitsCount()); } - // Set frag outputs in the shaders if hash not empty - if (!fragOutputs.isEmpty()) - shader->setFragOutputs(fragOutputs); + setUniformValue(command->m_parameterPack, StringToInt::lookupId(QStringLiteral("envLightCount")), envLightCount); } } - else { - qCWarning(Render::Backend) << Q_FUNC_INFO << "Using default effect as none was provided"; - } } bool RenderView::hasBlitFramebufferInfo() const diff --git a/src/render/renderers/opengl/renderer/renderview_p.h b/src/render/renderers/opengl/renderer/renderview_p.h index 7ebcdb6bd..7d148118d 100644 --- a/src/render/renderers/opengl/renderer/renderview_p.h +++ b/src/render/renderers/opengl/renderer/renderview_p.h @@ -227,10 +227,16 @@ public: RenderPassList passesAndParameters(ParameterInfoList *parameter, Entity *node, bool useDefaultMaterials = true); - QVector buildDrawRenderCommands(const QVector &entities) const; - QVector buildComputeRenderCommands(const QVector &entities) const; - void setCommands(QVector &commands) Q_DECL_NOTHROW { m_commands = commands; } - QVector commands() const Q_DECL_NOTHROW { return m_commands; } + QVector buildDrawRenderCommands(const QVector &entities) const; + QVector buildComputeRenderCommands(const QVector &entities) const; + + + void updateRenderCommand(QVector &renderCommandData); + + + void setCommands(const QVector &commands) Q_DECL_NOTHROW { m_commands = commands; } + QVector &commands() { return m_commands; } + QVector commands() const { return m_commands; } void setAttachmentPack(const AttachmentPack &pack) { m_attachmentPack = pack; } const AttachmentPack &attachmentPack() const { return m_attachmentPack; } @@ -291,7 +297,6 @@ public: private: void setShaderAndUniforms(RenderCommand *command, - RenderPass *pass, ParameterInfoList ¶meters, Entity *entity, const QVector &activeLightSources, @@ -331,10 +336,7 @@ private: QVector m_insertFenceIds; QVector m_waitFences; - // We do not use pointers to RenderNodes or Drawable's here so that the - // render aspect is free to change the drawables on the next frame whilst - // the render thread is submitting these commands. - QVector m_commands; + QVector m_commands; mutable QVector m_lightSources; EnvironmentLight *m_environmentLight; diff --git a/src/render/renderers/opengl/renderer/renderviewbuilder.cpp b/src/render/renderers/opengl/renderer/renderviewbuilder.cpp index 83fab301a..3c6521263 100644 --- a/src/render/renderers/opengl/renderer/renderviewbuilder.cpp +++ b/src/render/renderers/opengl/renderer/renderviewbuilder.cpp @@ -54,14 +54,60 @@ const int RenderViewBuilder::m_optimalParallelJobCount = std::max(std::min(4, QT namespace { -class SyncRenderViewCommandBuilders +class SyncPreCommandBuilding { public: - explicit SyncRenderViewCommandBuilders(const RenderViewInitializerJobPtr &renderViewJob, - const QVector &renderViewBuilderJobs, - Renderer *renderer) + explicit SyncPreCommandBuilding(RenderViewInitializerJobPtr renderViewInitializerJob, + const QVector &renderViewCommandBuilderJobs, + Renderer *renderer, + FrameGraphNode *leafNode) + : m_renderViewInitializer(renderViewInitializerJob) + , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) + , m_renderer(renderer) + , m_leafNode(leafNode) + { + } + + void operator()() + { + // Split commands to build among jobs + QMutexLocker lock(m_renderer->cache()->mutex()); + // Rebuild RenderCommands for all entities in RV (ignoring filtering) + const RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; + RenderView *rv = m_renderViewInitializer->renderView(); + const auto entities = !rv->isCompute() ? dataCacheForLeaf.renderableEntities : dataCacheForLeaf.computeEntities; + + rv->setMaterialParameterTable(dataCacheForLeaf.materialParameterGatherer); + + lock.unlock(); + + // Split among the number of command builders + int i = 0; + const int m = RenderViewBuilder::optimalJobCount() - 1; + const int packetSize = entities.size() / RenderViewBuilder::optimalJobCount(); + while (i < m) { + const RenderViewCommandBuilderJobPtr renderViewCommandBuilder = m_renderViewCommandBuilderJobs.at(i); + renderViewCommandBuilder->setEntities(entities.mid(i * packetSize, packetSize)); + ++i; + } + m_renderViewCommandBuilderJobs.at(i)->setEntities(entities.mid(i * packetSize, packetSize + entities.size() % (m + 1))); + } + +private: + RenderViewInitializerJobPtr m_renderViewInitializer; + QVector m_renderViewCommandBuilderJobs; + Renderer *m_renderer; + FrameGraphNode *m_leafNode; +}; + +class SyncRenderViewPostCommandUpdate +{ +public: + explicit SyncRenderViewPostCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob, + const QVector &renderViewCommandUpdateJobs, + Renderer *renderer) : m_renderViewJob(renderViewJob) - , m_renderViewBuilderJobs(renderViewBuilderJobs) + , m_renderViewCommandUpdaterJobs(renderViewCommandUpdateJobs) , m_renderer(renderer) {} @@ -71,17 +117,19 @@ public: RenderView *rv = m_renderViewJob->renderView(); int totalCommandCount = 0; - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs)) + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandUpdaterJobs)) totalCommandCount += renderViewCommandBuilder->commands().size(); - QVector commands; + QVector commands; commands.reserve(totalCommandCount); // Reduction - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs)) + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandUpdaterJobs)) commands += std::move(renderViewCommandBuilder->commands()); + rv->setCommands(commands); + // TO DO: Find way to store commands once or at least only when required // Sort the commands rv->sort(); @@ -91,15 +139,15 @@ public: private: RenderViewInitializerJobPtr m_renderViewJob; - QVector m_renderViewBuilderJobs; + QVector m_renderViewCommandUpdaterJobs; Renderer *m_renderer; }; -class SyncFrustumCulling +class SyncPreFrustumCulling { public: - explicit SyncFrustumCulling(const RenderViewInitializerJobPtr &renderViewJob, - const FrustumCullingJobPtr &frustumCulling) + explicit SyncPreFrustumCulling(const RenderViewInitializerJobPtr &renderViewJob, + const FrustumCullingJobPtr &frustumCulling) : m_renderViewJob(renderViewJob) , m_frustumCullingJob(frustumCulling) {} @@ -120,21 +168,23 @@ private: FrustumCullingJobPtr m_frustumCullingJob; }; -class SyncRenderViewInitialization +class SyncRenderViewPostInitialization { public: - explicit SyncRenderViewInitialization(const RenderViewInitializerJobPtr &renderViewJob, - const FrustumCullingJobPtr &frustumCullingJob, - const FilterLayerEntityJobPtr &filterEntityByLayerJob, - const FilterProximityDistanceJobPtr &filterProximityJob, - const QVector &materialGathererJobs, - const QVector &renderViewBuilderJobs) + explicit SyncRenderViewPostInitialization(const RenderViewInitializerJobPtr &renderViewJob, + const FrustumCullingJobPtr &frustumCullingJob, + const FilterLayerEntityJobPtr &filterEntityByLayerJob, + const FilterProximityDistanceJobPtr &filterProximityJob, + const QVector &materialGathererJobs, + const QVector &renderViewCommandUpdaterJobs, + const QVector &renderViewCommandBuilderJobs) : m_renderViewJob(renderViewJob) , m_frustumCullingJob(frustumCullingJob) , m_filterEntityByLayerJob(filterEntityByLayerJob) , m_filterProximityJob(filterProximityJob) , m_materialGathererJobs(materialGathererJobs) - , m_renderViewBuilderJobs(renderViewBuilderJobs) + , m_renderViewCommandUpdaterJobs(renderViewCommandUpdaterJobs) + , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) {} void operator()() @@ -154,8 +204,10 @@ public: materialGatherer->setTechniqueFilter(const_cast(rv->techniqueFilter())); } - // Command builders - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs)) + // Command builders and updates + for (const auto &renderViewCommandUpdater : qAsConst(m_renderViewCommandUpdaterJobs)) + renderViewCommandUpdater->setRenderView(rv); + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) renderViewCommandBuilder->setRenderView(rv); // Set whether frustum culling is enabled or not @@ -168,26 +220,31 @@ private: FilterLayerEntityJobPtr m_filterEntityByLayerJob; FilterProximityDistanceJobPtr m_filterProximityJob; QVector m_materialGathererJobs; - QVector m_renderViewBuilderJobs; + QVector m_renderViewCommandUpdaterJobs; + QVector m_renderViewCommandBuilderJobs; }; -class SyncRenderCommandBuilding +class SyncRenderViewPreCommandUpdate { public: - explicit SyncRenderCommandBuilding(const RenderViewInitializerJobPtr &renderViewJob, - const FrustumCullingJobPtr &frustumCullingJob, - const FilterProximityDistanceJobPtr &filterProximityJob, - const QVector &materialGathererJobs, - const QVector &renderViewBuilderJobs, - Renderer *renderer, - FrameGraphNode *leafNode) + explicit SyncRenderViewPreCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob, + const FrustumCullingJobPtr &frustumCullingJob, + const FilterProximityDistanceJobPtr &filterProximityJob, + const QVector &materialGathererJobs, + const QVector &renderViewCommandUpdaterJobs, + const QVector &renderViewCommandBuilderJobs, + Renderer *renderer, + FrameGraphNode *leafNode, + bool fullCommandRebuild) : m_renderViewJob(renderViewJob) , m_frustumCullingJob(frustumCullingJob) , m_filterProximityJob(filterProximityJob) , m_materialGathererJobs(materialGathererJobs) - , m_renderViewBuilderJobs(renderViewBuilderJobs) + , m_renderViewCommandUpdaterJobs(renderViewCommandUpdaterJobs) + , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) , m_renderer(renderer) , m_leafNode(leafNode) + , m_fullRebuild(fullCommandRebuild) {} void operator()() @@ -197,21 +254,45 @@ public: RenderView *rv = m_renderViewJob->renderView(); if (!rv->noDraw()) { - QVector renderableEntities; - const bool isDraw = !rv->isCompute(); + ///////// CACHE LOCKED //////////// + // Retrieve Data from Cache QMutexLocker lock(m_renderer->cache()->mutex()); - const auto& cacheData = m_renderer->cache()->leafNodeCache.value(m_leafNode); + Q_ASSERT(m_renderer->cache()->leafNodeCache.contains(m_leafNode)); - if (isDraw) - renderableEntities = cacheData.renderableEntities; - else - renderableEntities = cacheData.computeEntities; + const bool isDraw = !rv->isCompute(); + const RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; + + // Rebuild RenderCommands if required + // This should happen fairly infrequently (FrameGraph Change, Geometry/Material change) + // and allow to skip that step most of the time + if (m_fullRebuild) { + // Clear previous cache + RendererCache::LeafNodeData &writableCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; + writableCacheForLeaf.renderCommandData.clear(); + + QVector commandData; + // Reduction + { + int totalCommandCount = 0; + for (const RenderViewCommandBuilderJobPtr &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) + totalCommandCount += renderViewCommandBuilder->commandData().size(); + commandData.reserve(totalCommandCount); + for (const RenderViewCommandBuilderJobPtr &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) + commandData += std::move(renderViewCommandBuilder->commandData()); + } + // Store in cache + writableCacheForLeaf.renderCommandData = std::move(commandData); + } + const QVector commandData = dataCacheForLeaf.renderCommandData; - const QVector filteredEntities = cacheData.filterEntitiesByLayer; - QVector lightSources = cacheData.gatheredLights; - rv->setEnvironmentLight(cacheData.environmentLight); + QVector renderableEntities = isDraw ? dataCacheForLeaf.renderableEntities : dataCacheForLeaf.computeEntities; + const QVector filteredEntities = dataCacheForLeaf.filterEntitiesByLayer; + QVector lightSources = dataCacheForLeaf.gatheredLights; + rv->setMaterialParameterTable(dataCacheForLeaf.materialParameterGatherer); + rv->setEnvironmentLight(dataCacheForLeaf.environmentLight); lock.unlock(); + ///////// END OF CACHE LOCKED //////////// // Filter out entities that weren't selected by the layer filters // Remove all entities from the compute and renderable vectors that aren't in the filtered layer vector @@ -232,20 +313,43 @@ public: renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_filterProximityJob->filteredEntities()); } + // Filter out Render commands for which the Entity wasn't selected because + // of frustum, proximity or layer filtering + QVector filteredCommandData; + filteredCommandData.reserve(renderableEntities.size()); + // Because dataCacheForLeaf.renderableEntities or computeEntities are sorted + // What we get out of EntityRenderCommandData is also sorted by Entity + auto eIt = std::cbegin(renderableEntities); + auto cIt = std::cbegin(commandData); + const auto eEnd = std::cend(renderableEntities); + const auto cEnd = std::cend(commandData); + + while (eIt != eEnd) { + const Entity *targetEntity = *eIt; + // Advance until we have commands whose Entity has a lower address + // than the selected filtered entity + while (cIt->entity < targetEntity && cIt != cEnd) + ++cIt; + + // Push pointers to command data for all commands that match the + // entity + while (cIt->entity == targetEntity && cIt != cEnd) { + filteredCommandData.push_back(const_cast(&(*cIt))); + ++cIt; + } + ++eIt; + } + // Split among the number of command builders int i = 0; const int m = RenderViewBuilder::optimalJobCount() - 1; - const int packetSize = renderableEntities.size() / RenderViewBuilder::optimalJobCount(); + const int packetSize = filteredCommandData.size() / RenderViewBuilder::optimalJobCount(); while (i < m) { - const RenderViewBuilderJobPtr renderViewCommandBuilder = m_renderViewBuilderJobs.at(i); - renderViewCommandBuilder->setRenderables(renderableEntities.mid(i * packetSize, packetSize)); + const RenderViewCommandUpdaterJobPtr renderViewCommandBuilder = m_renderViewCommandUpdaterJobs.at(i); + renderViewCommandBuilder->setRenderables(filteredCommandData.mid(i * packetSize, packetSize)); ++i; } - m_renderViewBuilderJobs.at(i)->setRenderables(renderableEntities.mid(i * packetSize, packetSize + renderableEntities.size() % (m + 1))); - { - QMutexLocker rendererCacheLock(m_renderer->cache()->mutex()); - rv->setMaterialParameterTable(m_renderer->cache()->leafNodeCache.value(m_leafNode).materialParameterGatherer); - } + m_renderViewCommandUpdaterJobs.at(i)->setRenderables(filteredCommandData.mid(i * packetSize, packetSize + filteredCommandData.size() % (m + 1))); } } @@ -254,9 +358,11 @@ private: FrustumCullingJobPtr m_frustumCullingJob; FilterProximityDistanceJobPtr m_filterProximityJob; QVector m_materialGathererJobs; - QVector m_renderViewBuilderJobs; + QVector m_renderViewCommandUpdaterJobs; + QVector m_renderViewCommandBuilderJobs; Renderer *m_renderer; FrameGraphNode *m_leafNode; + bool m_fullRebuild; }; class SetClearDrawBufferIndex @@ -365,8 +471,8 @@ class SyncRenderableEntities { public: explicit SyncRenderableEntities(RenderableEntityFilterPtr gatherJob, - Renderer *renderer, - FrameGraphNode *leafNode) + Renderer *renderer, + FrameGraphNode *leafNode) : m_gatherJob(gatherJob) , m_renderer(renderer) , m_leafNode(leafNode) @@ -375,10 +481,12 @@ public: void operator()() { + QVector selectedEntities = m_gatherJob->filteredEntities(); + std::sort(selectedEntities.begin(), selectedEntities.end()); + QMutexLocker lock(m_renderer->cache()->mutex()); RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; - dataCacheForLeaf.renderableEntities = m_gatherJob->filteredEntities(); - std::sort(dataCacheForLeaf.renderableEntities.begin(), dataCacheForLeaf.renderableEntities.end()); + dataCacheForLeaf.renderableEntities = selectedEntities; } private: @@ -391,8 +499,8 @@ class SyncComputableEntities { public: explicit SyncComputableEntities(ComputableEntityFilterPtr gatherJob, - Renderer *renderer, - FrameGraphNode *leafNode) + Renderer *renderer, + FrameGraphNode *leafNode) : m_gatherJob(gatherJob) , m_renderer(renderer) , m_leafNode(leafNode) @@ -401,10 +509,12 @@ public: void operator()() { + QVector selectedEntities = m_gatherJob->filteredEntities(); + std::sort(selectedEntities.begin(), selectedEntities.end()); + QMutexLocker lock(m_renderer->cache()->mutex()); RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; - dataCacheForLeaf.computeEntities = m_gatherJob->filteredEntities(); - std::sort(dataCacheForLeaf.computeEntities.begin(), dataCacheForLeaf.computeEntities.end()); + dataCacheForLeaf.computeEntities = selectedEntities; } private: @@ -424,10 +534,11 @@ RenderViewBuilder::RenderViewBuilder(Render::FrameGraphNode *leafNode, int rende , m_lightsCacheNeedsToBeRebuilt(false) , m_renderableCacheNeedsToBeRebuilt(false) , m_computableCacheNeedsToBeRebuilt(false) + , m_renderCommandCacheNeedsToBeRebuilt(false) , m_renderViewJob(RenderViewInitializerJobPtr::create()) , m_filterEntityByLayerJob() , m_frustumCullingJob(new Render::FrustumCullingJob()) - , m_syncFrustumCullingJob(SynchronizerJobPtr::create(SyncFrustumCulling(m_renderViewJob, m_frustumCullingJob), JobTypes::SyncFrustumCulling)) + , m_syncPreFrustumCullingJob(SynchronizerJobPtr::create(SyncPreFrustumCulling(m_renderViewJob, m_frustumCullingJob), JobTypes::SyncFrustumCulling)) , m_setClearDrawBufferIndexJob(SynchronizerJobPtr::create(SetClearDrawBufferIndex(m_renderViewJob), JobTypes::ClearBufferDrawIndex)) , m_syncFilterEntityByLayerJob() , m_filterProximityJob(Render::FilterProximityDistanceJobPtr::create()) @@ -464,9 +575,14 @@ FrustumCullingJobPtr RenderViewBuilder::frustumCullingJob() const return m_frustumCullingJob; } -QVector RenderViewBuilder::renderViewBuilderJobs() const +QVector RenderViewBuilder::renderViewCommandUpdaterJobs() const +{ + return m_renderViewCommandUpdaterJobs; +} + +QVector RenderViewBuilder::renderViewCommandBuilderJobs() const { - return m_renderViewBuilderJobs; + return m_renderViewCommandBuilderJobs; } QVector RenderViewBuilder::materialGathererJobs() const @@ -474,24 +590,29 @@ QVector RenderViewBuilder::materialGathererJobs return m_materialGathererJobs; } -SynchronizerJobPtr RenderViewBuilder::syncRenderViewInitializationJob() const +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostInitializationJob() const +{ + return m_syncRenderViewPostInitializationJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncPreFrustumCullingJob() const { - return m_syncRenderViewInitializationJob; + return m_syncPreFrustumCullingJob; } -SynchronizerJobPtr RenderViewBuilder::syncFrustumCullingJob() const +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandBuildingJob() const { - return m_syncFrustumCullingJob; + return m_syncRenderViewPreCommandBuildingJob; } -SynchronizerJobPtr RenderViewBuilder::syncRenderCommandBuildingJob() const +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandUpdateJob() const { - return m_syncRenderCommandBuildingJob; + return m_syncRenderViewPreCommandUpdateJob; } -SynchronizerJobPtr RenderViewBuilder::syncRenderViewCommandBuildersJob() const +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostCommandUpdateJob() const { - return m_syncRenderViewCommandBuildersJob; + return m_syncRenderViewPostCommandUpdateJob; } SynchronizerJobPtr RenderViewBuilder::setClearDrawBufferIndexJob() const @@ -526,7 +647,7 @@ void RenderViewBuilder::prepareJobs() m_lightGathererJob->setManager(entityManager); m_cacheLightsJob = SynchronizerJobPtr::create(SyncLightsGatherer(m_lightGathererJob, m_renderer, m_leafNode), - JobTypes::EntityComponentTypeFiltering); + JobTypes::EntityComponentTypeFiltering); m_cacheLightsJob->addDependency(m_lightGathererJob); } @@ -535,8 +656,8 @@ void RenderViewBuilder::prepareJobs() m_renderableEntityFilterJob->setManager(entityManager); m_cacheRenderableEntitiesJob = SynchronizerJobPtr::create( - SyncRenderableEntities(m_renderableEntityFilterJob, m_renderer, m_leafNode), - JobTypes::EntityComponentTypeFiltering); + SyncRenderableEntities(m_renderableEntityFilterJob, m_renderer, m_leafNode), + JobTypes::EntityComponentTypeFiltering); m_cacheRenderableEntitiesJob->addDependency(m_renderableEntityFilterJob); } @@ -545,23 +666,36 @@ void RenderViewBuilder::prepareJobs() m_computableEntityFilterJob->setManager(entityManager); m_cacheComputableEntitiesJob = SynchronizerJobPtr::create( - SyncComputableEntities(m_computableEntityFilterJob, m_renderer, m_leafNode), - JobTypes::EntityComponentTypeFiltering); + SyncComputableEntities(m_computableEntityFilterJob, m_renderer, m_leafNode), + JobTypes::EntityComponentTypeFiltering); m_cacheComputableEntitiesJob->addDependency(m_computableEntityFilterJob); } + if (m_renderCommandCacheNeedsToBeRebuilt) { + + m_renderViewCommandBuilderJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); + for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { + auto renderViewCommandBuilder = Render::RenderViewCommandBuilderJobPtr::create(); + m_renderViewCommandBuilderJobs.push_back(renderViewCommandBuilder); + } + m_syncRenderViewPreCommandBuildingJob = SynchronizerJobPtr::create(SyncPreCommandBuilding(m_renderViewJob, + m_renderViewCommandBuilderJobs, + m_renderer, + m_leafNode), + JobTypes::SyncRenderViewPreCommandBuilding); + } + m_renderViewJob->setRenderer(m_renderer); m_renderViewJob->setFrameGraphLeafNode(m_leafNode); m_renderViewJob->setSubmitOrderIndex(m_renderViewIndex); // RenderCommand building is the most consuming task -> split it // Estimate the number of jobs to create based on the number of entities - m_renderViewBuilderJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); + m_renderViewCommandUpdaterJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto renderViewCommandBuilder = Render::RenderViewBuilderJobPtr::create(); - renderViewCommandBuilder->setIndex(m_renderViewIndex); - renderViewCommandBuilder->setRenderer(m_renderer); - m_renderViewBuilderJobs.push_back(renderViewCommandBuilder); + auto renderViewCommandUpdater = Render::RenderViewCommandUpdaterJobPtr::create(); + renderViewCommandUpdater->setRenderer(m_renderer); + m_renderViewCommandUpdaterJobs.push_back(renderViewCommandUpdater); } if (m_materialGathererCacheNeedsToBeRebuilt) { @@ -582,7 +716,7 @@ void RenderViewBuilder::prepareJobs() m_syncMaterialGathererJob = SynchronizerJobPtr::create(SyncMaterialParameterGatherer(m_materialGathererJobs, m_renderer, m_leafNode), - JobTypes::SyncMaterialGatherer); + JobTypes::SyncMaterialGatherer); } if (m_layerCacheNeedsToBeRebuilt) { @@ -594,34 +728,37 @@ void RenderViewBuilder::prepareJobs() JobTypes::SyncFilterEntityByLayer); } - m_syncRenderCommandBuildingJob = SynchronizerJobPtr::create(SyncRenderCommandBuilding(m_renderViewJob, - m_frustumCullingJob, - m_filterProximityJob, - m_materialGathererJobs, - m_renderViewBuilderJobs, - m_renderer, - m_leafNode), - JobTypes::SyncRenderViewCommandBuilding); - - m_syncRenderViewCommandBuildersJob = SynchronizerJobPtr::create(SyncRenderViewCommandBuilders(m_renderViewJob, - m_renderViewBuilderJobs, - m_renderer), - JobTypes::SyncRenderViewCommandBuilder); - - m_syncRenderViewInitializationJob = SynchronizerJobPtr::create(SyncRenderViewInitialization(m_renderViewJob, - m_frustumCullingJob, - m_filterEntityByLayerJob, - m_filterProximityJob, - m_materialGathererJobs, - m_renderViewBuilderJobs), - JobTypes::SyncRenderViewInitialization); + m_syncRenderViewPreCommandUpdateJob = SynchronizerJobPtr::create(SyncRenderViewPreCommandUpdate(m_renderViewJob, + m_frustumCullingJob, + m_filterProximityJob, + m_materialGathererJobs, + m_renderViewCommandUpdaterJobs, + m_renderViewCommandBuilderJobs, + m_renderer, + m_leafNode, + m_renderCommandCacheNeedsToBeRebuilt), + JobTypes::SyncRenderViewPreCommandUpdate); + + m_syncRenderViewPostCommandUpdateJob = SynchronizerJobPtr::create(SyncRenderViewPostCommandUpdate(m_renderViewJob, + m_renderViewCommandUpdaterJobs, + m_renderer), + JobTypes::SyncRenderViewPostCommandUpdate); + + m_syncRenderViewPostInitializationJob = SynchronizerJobPtr::create(SyncRenderViewPostInitialization(m_renderViewJob, + m_frustumCullingJob, + m_filterEntityByLayerJob, + m_filterProximityJob, + m_materialGathererJobs, + m_renderViewCommandUpdaterJobs, + m_renderViewCommandBuilderJobs), + JobTypes::SyncRenderViewInitialization); } QVector RenderViewBuilder::buildJobHierachy() const { QVector jobs; - jobs.reserve(m_materialGathererJobs.size() + m_renderViewBuilderJobs.size() + 11); + jobs.reserve(m_materialGathererJobs.size() + m_renderViewCommandUpdaterJobs.size() + 11); // Set dependencies @@ -629,36 +766,36 @@ QVector RenderViewBuilder::buildJobHierachy() const // TODO: Maybe only update skinning palettes for non-culled entities m_renderViewJob->addDependency(m_renderer->updateSkinningPaletteJob()); - m_syncFrustumCullingJob->addDependency(m_renderer->updateWorldTransformJob()); - m_syncFrustumCullingJob->addDependency(m_renderer->updateShaderDataTransformJob()); - m_syncFrustumCullingJob->addDependency(m_syncRenderViewInitializationJob); + m_syncPreFrustumCullingJob->addDependency(m_renderer->updateWorldTransformJob()); + m_syncPreFrustumCullingJob->addDependency(m_renderer->updateShaderDataTransformJob()); + m_syncPreFrustumCullingJob->addDependency(m_syncRenderViewPostInitializationJob); m_frustumCullingJob->addDependency(m_renderer->expandBoundingVolumeJob()); - m_frustumCullingJob->addDependency(m_syncFrustumCullingJob); + m_frustumCullingJob->addDependency(m_syncPreFrustumCullingJob); - m_setClearDrawBufferIndexJob->addDependency(m_syncRenderViewInitializationJob); + m_setClearDrawBufferIndexJob->addDependency(m_syncRenderViewPostInitializationJob); - m_syncRenderViewInitializationJob->addDependency(m_renderViewJob); + m_syncRenderViewPostInitializationJob->addDependency(m_renderViewJob); m_filterProximityJob->addDependency(m_renderer->expandBoundingVolumeJob()); - m_filterProximityJob->addDependency(m_syncRenderViewInitializationJob); + m_filterProximityJob->addDependency(m_syncRenderViewPostInitializationJob); - m_syncRenderCommandBuildingJob->addDependency(m_syncRenderViewInitializationJob); - m_syncRenderCommandBuildingJob->addDependency(m_filterProximityJob); - m_syncRenderCommandBuildingJob->addDependency(m_frustumCullingJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncRenderViewPostInitializationJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_filterProximityJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_frustumCullingJob); // Ensure the RenderThread won't be able to process dirtyResources // before they have been completely gathered - m_syncRenderCommandBuildingJob->addDependency(m_renderer->introspectShadersJob()); - m_syncRenderCommandBuildingJob->addDependency(m_renderer->bufferGathererJob()); - m_syncRenderCommandBuildingJob->addDependency(m_renderer->textureGathererJob()); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->introspectShadersJob()); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->bufferGathererJob()); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->textureGathererJob()); - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs)) { - renderViewCommandBuilder->addDependency(m_syncRenderCommandBuildingJob); - m_syncRenderViewCommandBuildersJob->addDependency(renderViewCommandBuilder); + for (const auto &renderViewCommandUpdater : qAsConst(m_renderViewCommandUpdaterJobs)) { + renderViewCommandUpdater->addDependency(m_syncRenderViewPreCommandUpdateJob); + m_syncRenderViewPostCommandUpdateJob->addDependency(renderViewCommandUpdater); } - m_renderer->frameCleanupJob()->addDependency(m_syncRenderViewCommandBuildersJob); + m_renderer->frameCleanupJob()->addDependency(m_syncRenderViewPostCommandUpdateJob); m_renderer->frameCleanupJob()->addDependency(m_setClearDrawBufferIndexJob); // Add jobs @@ -667,59 +804,75 @@ QVector RenderViewBuilder::buildJobHierachy() const if (m_lightsCacheNeedsToBeRebuilt) { jobs.push_back(m_lightGathererJob); // Step 1 jobs.push_back(m_cacheLightsJob); - m_syncRenderCommandBuildingJob->addDependency(m_cacheLightsJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_cacheLightsJob); } if (m_renderableCacheNeedsToBeRebuilt) { jobs.push_back(m_renderableEntityFilterJob); // Step 1 jobs.push_back(m_cacheRenderableEntitiesJob); - m_syncRenderCommandBuildingJob->addDependency(m_cacheRenderableEntitiesJob); } if (m_computableCacheNeedsToBeRebuilt) { // Note: do it only if OpenGL 4.3+ available jobs.push_back(m_computableEntityFilterJob); // Step 1 jobs.push_back(m_cacheComputableEntitiesJob); - m_syncRenderCommandBuildingJob->addDependency(m_cacheComputableEntitiesJob); } - jobs.push_back(m_syncRenderViewInitializationJob); // Step 2 + jobs.push_back(m_syncRenderViewPostInitializationJob); // Step 2 + + if (m_renderCommandCacheNeedsToBeRebuilt) { // Step 3 + m_syncRenderViewPreCommandBuildingJob->addDependency(m_cacheComputableEntitiesJob); + m_syncRenderViewPreCommandBuildingJob->addDependency(m_cacheRenderableEntitiesJob); + m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncRenderViewPostInitializationJob); + + if (m_materialGathererCacheNeedsToBeRebuilt) + m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncMaterialGathererJob); + + jobs.push_back(m_syncRenderViewPreCommandBuildingJob); + + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) { + renderViewCommandBuilder->addDependency(m_syncRenderViewPreCommandBuildingJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(renderViewCommandBuilder); + jobs.push_back(renderViewCommandBuilder); + } + } if (m_layerCacheNeedsToBeRebuilt) { m_filterEntityByLayerJob->addDependency(m_renderer->updateEntityLayersJob()); - m_filterEntityByLayerJob->addDependency(m_syncRenderViewInitializationJob); + m_filterEntityByLayerJob->addDependency(m_syncRenderViewPostInitializationJob); m_filterEntityByLayerJob->addDependency(m_renderer->updateTreeEnabledJob()); m_syncFilterEntityByLayerJob->addDependency(m_filterEntityByLayerJob); - m_syncRenderCommandBuildingJob->addDependency(m_syncFilterEntityByLayerJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncFilterEntityByLayerJob); jobs.push_back(m_filterEntityByLayerJob); // Step 3 jobs.push_back(m_syncFilterEntityByLayerJob); // Step 4 } - jobs.push_back(m_syncFrustumCullingJob); // Step 3 + jobs.push_back(m_syncPreFrustumCullingJob); // Step 3 jobs.push_back(m_filterProximityJob); // Step 3 jobs.push_back(m_setClearDrawBufferIndexJob); // Step 3 if (m_materialGathererCacheNeedsToBeRebuilt) { for (const auto &materialGatherer : qAsConst(m_materialGathererJobs)) { - materialGatherer->addDependency(m_syncRenderViewInitializationJob); + materialGatherer->addDependency(m_syncRenderViewPostInitializationJob); materialGatherer->addDependency(m_renderer->introspectShadersJob()); materialGatherer->addDependency(m_renderer->filterCompatibleTechniqueJob()); jobs.push_back(materialGatherer); // Step3 m_syncMaterialGathererJob->addDependency(materialGatherer); } - m_syncRenderCommandBuildingJob->addDependency(m_syncMaterialGathererJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncMaterialGathererJob); jobs.push_back(m_syncMaterialGathererJob); // Step 3 } jobs.push_back(m_frustumCullingJob); // Step 4 - jobs.push_back(m_syncRenderCommandBuildingJob); // Step 5 + jobs.push_back(m_syncRenderViewPreCommandUpdateJob); // Step 5 - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs)) // Step 6 + // Build RenderCommands or Update RenderCommand Uniforms + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandUpdaterJobs)) // Step 6 jobs.push_back(renderViewCommandBuilder); - jobs.push_back(m_syncRenderViewCommandBuildersJob); // Step 7 + jobs.push_back(m_syncRenderViewPostCommandUpdateJob); // Step 7 return jobs; } @@ -784,6 +937,16 @@ bool RenderViewBuilder::lightGathererCacheNeedsToBeRebuilt() const return m_lightsCacheNeedsToBeRebuilt; } +void RenderViewBuilder::setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt) +{ + m_renderCommandCacheNeedsToBeRebuilt = needsToBeRebuilt; +} + +bool RenderViewBuilder::renderCommandCacheNeedsToBeRebuilt() const +{ + return m_renderCommandCacheNeedsToBeRebuilt; +} + int RenderViewBuilder::optimalJobCount() { return RenderViewBuilder::m_optimalParallelJobCount; diff --git a/src/render/renderers/opengl/renderer/renderviewbuilder_p.h b/src/render/renderers/opengl/renderer/renderviewbuilder_p.h index e223a5f1e..66344da11 100644 --- a/src/render/renderers/opengl/renderer/renderviewbuilder_p.h +++ b/src/render/renderers/opengl/renderer/renderviewbuilder_p.h @@ -58,7 +58,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -87,12 +88,14 @@ public: RenderableEntityFilterPtr renderableEntityFilterJob() const; ComputableEntityFilterPtr computableEntityFilterJob() const; FrustumCullingJobPtr frustumCullingJob() const; - QVector renderViewBuilderJobs() const; + QVector renderViewCommandBuilderJobs() const; + QVector renderViewCommandUpdaterJobs() const; QVector materialGathererJobs() const; - SynchronizerJobPtr syncRenderViewInitializationJob() const; - SynchronizerJobPtr syncFrustumCullingJob() const; - SynchronizerJobPtr syncRenderCommandBuildingJob() const; - SynchronizerJobPtr syncRenderViewCommandBuildersJob() const; + SynchronizerJobPtr syncRenderViewPostInitializationJob() const; + SynchronizerJobPtr syncPreFrustumCullingJob() const; + SynchronizerJobPtr syncRenderViewPreCommandBuildingJob() const; + SynchronizerJobPtr syncRenderViewPreCommandUpdateJob() const; + SynchronizerJobPtr syncRenderViewPostCommandUpdateJob() const; SynchronizerJobPtr setClearDrawBufferIndexJob() const; SynchronizerJobPtr syncFilterEntityByLayerJob() const; FilterProximityDistanceJobPtr filterProximityJob() const; @@ -118,6 +121,9 @@ public: void setLightGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt); bool lightGathererCacheNeedsToBeRebuilt() const; + void setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt); + bool renderCommandCacheNeedsToBeRebuilt() const; + static int optimalJobCount(); static QVector entitiesInSubset(const QVector &entities, const QVector &subset); @@ -130,6 +136,7 @@ private: bool m_lightsCacheNeedsToBeRebuilt; bool m_renderableCacheNeedsToBeRebuilt; bool m_computableCacheNeedsToBeRebuilt; + bool m_renderCommandCacheNeedsToBeRebuilt; RenderViewInitializerJobPtr m_renderViewJob; FilterLayerEntityJobPtr m_filterEntityByLayerJob; @@ -137,13 +144,15 @@ private: RenderableEntityFilterPtr m_renderableEntityFilterJob; ComputableEntityFilterPtr m_computableEntityFilterJob; FrustumCullingJobPtr m_frustumCullingJob; - QVector m_renderViewBuilderJobs; + QVector m_renderViewCommandBuilderJobs; + QVector m_renderViewCommandUpdaterJobs; QVector m_materialGathererJobs; - SynchronizerJobPtr m_syncRenderViewInitializationJob; - SynchronizerJobPtr m_syncFrustumCullingJob; - SynchronizerJobPtr m_syncRenderCommandBuildingJob; - SynchronizerJobPtr m_syncRenderViewCommandBuildersJob; + SynchronizerJobPtr m_syncRenderViewPostInitializationJob; + SynchronizerJobPtr m_syncPreFrustumCullingJob; + SynchronizerJobPtr m_syncRenderViewPreCommandBuildingJob; + SynchronizerJobPtr m_syncRenderViewPreCommandUpdateJob; + SynchronizerJobPtr m_syncRenderViewPostCommandUpdateJob; SynchronizerJobPtr m_setClearDrawBufferIndexJob; SynchronizerJobPtr m_syncFilterEntityByLayerJob; SynchronizerJobPtr m_syncMaterialGathererJob; diff --git a/tests/auto/render/renderer/tst_renderer.cpp b/tests/auto/render/renderer/tst_renderer.cpp index e1bf8dfd9..65309707c 100644 --- a/tests/auto/render/renderer/tst_renderer.cpp +++ b/tests/auto/render/renderer/tst_renderer.cpp @@ -160,6 +160,9 @@ private Q_SLOTS: const int layerCacheJobCount = 2; // filterEntityByLayerJob, // syncFilterEntityByLayerJob + + const int singleRenderViewCommandRebuildJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + const int singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); // RenderViewBuilder renderViewJob, // syncRenderViewInitializationJob, @@ -167,20 +170,42 @@ private Q_SLOTS: // filterProximityJob, // setClearDrawBufferIndexJob, // frustumCullingJob, - // syncRenderCommandBuldingJob, - // syncRenderViewCommandBuilderJob + // syncRenderCommandUpdateJob, + // syncRenderViewCommandPostUpdateJob // n * (RenderViewCommandBuildJobs) // WHEN QVector jobs = renderer.renderBinJobs(); - // THEN + // THEN -> AllDirty + // (Renderer is not initialized so FilterCompatibleTechniqueJob + // and ShaderGathererJob are not added here) QCOMPARE(jobs.size(), + 1 + // EntityEnabledDirty + 1 + // WorldTransformJob + 1 + // UpdateWorldBoundingVolume + 1 + // UpdateShaderDataTransform + 1 + // ExpandBoundingVolumeJob + 1 + // CalculateBoundingVolumeJob + 1 + // UpdateMeshTriangleListJob + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs 1 + // updateLevelOfDetailJob 1 + // cleanupJob 1 + // VAOGatherer - 1 + // updateSkinningPaletteJob - 1); // SyncLoadingJobs + 1 + // BufferGathererJob + 1 + // TexturesGathererJob + 1 + // UpdateEntityLayersJob + 1 + // LightGathererJob + 1 + // CacheLightJob + 1 + // RenderableEntityFilterJob + 1 + // CacheRenderableEntitiesJob + 1 + // ComputableEntityFilterJob + 1 + // CacheComputableEntitiesJob + singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + + layerCacheJobCount + + renderViewBuilderMaterialCacheJobCount); renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); renderQueue->reset(); @@ -197,6 +222,7 @@ private Q_SLOTS: 1 + // updateSkinningPaletteJob 1 + // SyncLoadingJobs singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + renderViewBuilderMaterialCacheJobCount + layerCacheJobCount); @@ -253,6 +279,7 @@ private Q_SLOTS: 1 + // updateSkinningPaletteJob 1 + // SyncLoadingJobs singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + renderViewBuilderMaterialCacheJobCount); renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); @@ -274,6 +301,7 @@ private Q_SLOTS: 1 + // ExpandBoundingVolumeJob 1 + // RenderableEntityFilterPtr 1 + // SyncRenderableEntities + singleRenderViewCommandRebuildJobCount + singleRenderViewJobCount); renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); @@ -315,41 +343,6 @@ private Q_SLOTS: renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); renderQueue->reset(); - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::AllDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (Renderer is not initialized so FilterCompatibleTechniqueJob - // and ShaderGathererJob are not added here) - QCOMPARE(jobs.size(), - 1 + // EntityEnabledDirty - 1 + // WorldTransformJob - 1 + // UpdateWorldBoundingVolume - 1 + // UpdateShaderDataTransform - 1 + // ExpandBoundingVolumeJob - 1 + // CalculateBoundingVolumeJob - 1 + // UpdateMeshTriangleListJob - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // BufferGathererJob - 1 + // TexturesGathererJob - 1 + // UpdateEntityLayersJob - 1 + // LightGathererJob - 1 + // CacheLightJob - 1 + // RenderableEntityFilterJob - 1 + // CacheRenderableEntitiesJob - 1 + // ComputableEntityFilterJob - 1 + // CacheComputableEntitiesJob - singleRenderViewJobCount + - layerCacheJobCount + - renderViewBuilderMaterialCacheJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - // Properly shutdown command thread renderer.shutdown(); } diff --git a/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp b/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp index 96d51a3a9..0fb1f5e24 100644 --- a/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp +++ b/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp @@ -224,29 +224,29 @@ private Q_SLOTS: QCOMPARE(renderViewBuilder.materialGathererCacheNeedsToBeRebuilt(), false); QVERIFY(!renderViewBuilder.renderViewJob().isNull()); QVERIFY(!renderViewBuilder.frustumCullingJob().isNull()); - QVERIFY(!renderViewBuilder.syncFrustumCullingJob().isNull()); + QVERIFY(!renderViewBuilder.syncPreFrustumCullingJob().isNull()); QVERIFY(!renderViewBuilder.setClearDrawBufferIndexJob().isNull()); QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob().isNull()); - QVERIFY(renderViewBuilder.syncRenderViewCommandBuildersJob().isNull()); - QVERIFY(renderViewBuilder.syncRenderViewInitializationJob().isNull()); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob().isNull()); + QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob().isNull()); + QVERIFY(renderViewBuilder.syncRenderViewPostInitializationJob().isNull()); - QCOMPARE(renderViewBuilder.renderViewBuilderJobs().size(), 0); + QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), 0); QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); // WHEN renderViewBuilder.prepareJobs(); // THEN - QVERIFY(!renderViewBuilder.syncRenderCommandBuildingJob().isNull()); - QVERIFY(!renderViewBuilder.syncRenderViewCommandBuildersJob().isNull()); - QVERIFY(!renderViewBuilder.syncRenderViewInitializationJob().isNull()); + QVERIFY(!renderViewBuilder.syncRenderViewPreCommandUpdateJob().isNull()); + QVERIFY(!renderViewBuilder.syncRenderViewPostCommandUpdateJob().isNull()); + QVERIFY(!renderViewBuilder.syncRenderViewPostInitializationJob().isNull()); QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - QCOMPARE(renderViewBuilder.renderViewBuilderJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); } @@ -338,8 +338,8 @@ private Q_SLOTS: // Step 2 - QCOMPARE(renderViewBuilder.syncRenderViewInitializationJob()->dependencies().size(), 1); - QCOMPARE(renderViewBuilder.syncRenderViewInitializationJob()->dependencies().constFirst().toStrongRef().data(), + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().size(), 1); + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().constFirst().toStrongRef().data(), renderViewBuilder.renderViewJob().data()); // Step 3 @@ -347,43 +347,43 @@ private Q_SLOTS: QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); QCOMPARE(renderViewBuilder.filterProximityJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); + QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().size(), 1); QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderViewInitializationJob().data()); + renderViewBuilder.syncRenderViewPostInitializationJob().data()); - QCOMPARE(renderViewBuilder.syncFrustumCullingJob()->dependencies().size(), 3); - QVERIFY(renderViewBuilder.syncFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); - QVERIFY(renderViewBuilder.syncFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); - QVERIFY(renderViewBuilder.syncFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); + QCOMPARE(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().size(), 3); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); // Step 4 QCOMPARE(renderViewBuilder.frustumCullingJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncFrustumCullingJob())); + QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncPreFrustumCullingJob())); QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); - QCOMPARE(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().size(), renderViewBuilder.materialGathererJobs().size() + 6); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); + QCOMPARE(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().size(), renderViewBuilder.materialGathererJobs().size() + 6); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); // Step 5 - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewBuilderJobs()) { + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { QCOMPARE(renderViewBuilderJob->dependencies().size(), 1); QCOMPARE(renderViewBuilderJob->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderCommandBuildingJob().data()); + renderViewBuilder.syncRenderViewPreCommandUpdateJob().data()); } // Step 6 - QCOMPARE(renderViewBuilder.syncRenderViewCommandBuildersJob()->dependencies().size(), renderViewBuilder.renderViewBuilderJobs().size()); - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewBuilderJobs()) { - QVERIFY(renderViewBuilder.syncRenderViewCommandBuildersJob()->dependencies().contains(renderViewBuilderJob)); + QCOMPARE(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().size(), renderViewBuilder.renderViewCommandUpdaterJobs().size()); + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { + QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().contains(renderViewBuilderJob)); } } { @@ -399,63 +399,63 @@ private Q_SLOTS: QCOMPARE(renderViewBuilder.renderViewJob()->dependencies().size(), 1); // Depends upon skinning palette update // Step 2 - QCOMPARE(renderViewBuilder.syncRenderViewInitializationJob()->dependencies().size(), 1); - QCOMPARE(renderViewBuilder.syncRenderViewInitializationJob()->dependencies().constFirst().toStrongRef().data(), + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().size(), 1); + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().constFirst().toStrongRef().data(), renderViewBuilder.renderViewJob().data()); // Step 3 QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->dependencies().size(), 3); QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(testAspect.renderer()->updateEntityLayersJob())); - QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); + QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(testAspect.renderer()->updateTreeEnabledJob())); QCOMPARE(renderViewBuilder.syncFilterEntityByLayerJob()->dependencies().size(), 1); QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob()->dependencies().contains(renderViewBuilder.filterEntityByLayerJob())); QCOMPARE(renderViewBuilder.filterProximityJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); + QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().size(), 1); QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderViewInitializationJob().data()); + renderViewBuilder.syncRenderViewPostInitializationJob().data()); - QCOMPARE(renderViewBuilder.syncFrustumCullingJob()->dependencies().size(), 3); - QVERIFY(renderViewBuilder.syncFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); - QVERIFY(renderViewBuilder.syncFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); - QVERIFY(renderViewBuilder.syncFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); + QCOMPARE(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().size(), 3); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { QCOMPARE(materialGatherer->dependencies().size(), 3); - QVERIFY(materialGatherer->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); + QVERIFY(materialGatherer->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); QVERIFY(materialGatherer->dependencies().contains(testAspect.renderer()->introspectShadersJob())); QVERIFY(materialGatherer->dependencies().contains(testAspect.renderer()->filterCompatibleTechniqueJob())); } // Step 4 QCOMPARE(renderViewBuilder.frustumCullingJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncFrustumCullingJob())); + QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncPreFrustumCullingJob())); QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.syncRenderViewInitializationJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.syncFilterEntityByLayerJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); - QVERIFY(renderViewBuilder.syncRenderCommandBuildingJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncFilterEntityByLayerJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); // Step 5 - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewBuilderJobs()) { + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { QCOMPARE(renderViewBuilderJob->dependencies().size(), 1); QCOMPARE(renderViewBuilderJob->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderCommandBuildingJob().data()); + renderViewBuilder.syncRenderViewPreCommandUpdateJob().data()); } // Step 6 - QCOMPARE(renderViewBuilder.syncRenderViewCommandBuildersJob()->dependencies().size(), renderViewBuilder.renderViewBuilderJobs().size()); - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewBuilderJobs()) { - QVERIFY(renderViewBuilder.syncRenderViewCommandBuildersJob()->dependencies().contains(renderViewBuilderJob)); + QCOMPARE(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().size(), renderViewBuilder.renderViewCommandUpdaterJobs().size()); + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { + QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().contains(renderViewBuilderJob)); } } } @@ -581,7 +581,7 @@ private Q_SLOTS: // WHEN renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncRenderViewInitializationJob()->run(); + renderViewBuilder.syncRenderViewPostInitializationJob()->run(); // THEN QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true); @@ -608,7 +608,7 @@ private Q_SLOTS: // WHEN renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncRenderViewInitializationJob()->run(); + renderViewBuilder.syncRenderViewPostInitializationJob()->run(); // THEN QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true); @@ -647,7 +647,7 @@ private Q_SLOTS: // WHEN renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncFrustumCullingJob()->run(); + renderViewBuilder.syncPreFrustumCullingJob()->run(); // THEN QCOMPARE(convertToQMatrix4x4(renderViewBuilder.frustumCullingJob()->viewProjection()), camera->projectionMatrix() * camera->viewMatrix()); @@ -676,7 +676,7 @@ private Q_SLOTS: renderViewBuilder.renderViewJob()->run(); renderViewBuilder.renderableEntityFilterJob()->run(); - renderViewBuilder.syncRenderViewInitializationJob()->run(); + renderViewBuilder.syncRenderViewPostInitializationJob()->run(); renderViewBuilder.filterEntityByLayerJob()->run(); QVector renderableEntity = renderViewBuilder.renderableEntityFilterJob()->filteredEntities(); diff --git a/tests/auto/render/renderviews/tst_renderviews.cpp b/tests/auto/render/renderviews/tst_renderviews.cpp index f38915bf8..17995659b 100644 --- a/tests/auto/render/renderviews/tst_renderviews.cpp +++ b/tests/auto/render/renderviews/tst_renderviews.cpp @@ -138,14 +138,14 @@ private Q_SLOTS: { // GIVEN RenderView renderView; - QVector rawCommands; + QVector rawCommands; QVector sortTypes; sortTypes.push_back(QSortPolicy::BackToFront); for (int i = 0; i < 200; ++i) { - RenderCommand *c = new RenderCommand(); - c->m_depth = float(i); + RenderCommand c; + c.m_depth = float(i); rawCommands.push_back(c); } @@ -155,10 +155,10 @@ private Q_SLOTS: renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); for (int j = 1; j < sortedCommands.size(); ++j) - QVERIFY(sortedCommands.at(j - 1)->m_depth > sortedCommands.at(j)->m_depth); + QVERIFY(sortedCommands.at(j - 1).m_depth > sortedCommands.at(j).m_depth); // RenderCommands are deleted by RenderView dtor } @@ -167,7 +167,7 @@ private Q_SLOTS: { // GIVEN RenderView renderView; - QVector rawCommands; + QVector rawCommands; QVector sortTypes; sortTypes.push_back(QSortPolicy::Material); @@ -181,8 +181,8 @@ private Q_SLOTS: }; for (int i = 0; i < 20; ++i) { - RenderCommand *c = new RenderCommand(); - c->m_shaderDna = dnas[i % 5]; + RenderCommand c; + c.m_shaderDna = dnas[i % 5]; rawCommands.push_back(c); } @@ -192,18 +192,18 @@ private Q_SLOTS: renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); ProgramDNA targetDNA; for (int j = 0; j < sortedCommands.size(); ++j) { if (j % 4 == 0) { - targetDNA = sortedCommands.at(j)->m_shaderDna; + targetDNA = sortedCommands.at(j).m_shaderDna; if (j > 0) - QVERIFY(targetDNA != sortedCommands.at(j - 1)->m_shaderDna); + QVERIFY(targetDNA != sortedCommands.at(j - 1).m_shaderDna); } - QCOMPARE(targetDNA, sortedCommands.at(j)->m_shaderDna); + QCOMPARE(targetDNA, sortedCommands.at(j).m_shaderDna); } // RenderCommands are deleted by RenderView dtor @@ -247,12 +247,12 @@ private Q_SLOTS: QFETCH(QVector, expectedMinimizedParameters); RenderView renderView; - QVector rawCommands; + QVector rawCommands; for (int i = 0, m = programDNAs.size(); i < m; ++i) { - RenderCommand *c = new RenderCommand(); - c->m_shaderDna = programDNAs.at(i); - c->m_parameterPack = rawParameters.at(i); + RenderCommand c; + c.m_shaderDna = programDNAs.at(i); + c.m_parameterPack = rawParameters.at(i); rawCommands.push_back(c); } @@ -261,13 +261,13 @@ private Q_SLOTS: renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands, sortedCommands); for (int i = 0, m = programDNAs.size(); i < m; ++i) { - const RenderCommand *c = sortedCommands.at(i); - QCOMPARE(c->m_shaderDna, programDNAs.at(i)); - compareShaderParameterPacks(c->m_parameterPack, expectedMinimizedParameters.at(i)); + const RenderCommand c = sortedCommands.at(i); + QCOMPARE(c.m_shaderDna, programDNAs.at(i)); + compareShaderParameterPacks(c.m_parameterPack, expectedMinimizedParameters.at(i)); } } @@ -276,14 +276,14 @@ private Q_SLOTS: { // GIVEN RenderView renderView; - QVector rawCommands; + QVector rawCommands; QVector sortTypes; sortTypes.push_back(QSortPolicy::FrontToBack); for (int i = 0; i < 200; ++i) { - RenderCommand *c = new RenderCommand(); - c->m_depth = float(i); + RenderCommand c; + c.m_depth = float(i); rawCommands.push_back(c); } @@ -293,10 +293,10 @@ private Q_SLOTS: renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); for (int j = 1; j < sortedCommands.size(); ++j) - QVERIFY(sortedCommands.at(j - 1)->m_depth < sortedCommands.at(j)->m_depth); + QVERIFY(sortedCommands.at(j - 1).m_depth < sortedCommands.at(j).m_depth); // RenderCommands are deleted by RenderView dtor } @@ -305,14 +305,14 @@ private Q_SLOTS: { // GIVEN RenderView renderView; - QVector rawCommands; + QVector rawCommands; QVector sortTypes; sortTypes.push_back(QSortPolicy::StateChangeCost); for (int i = 0; i < 200; ++i) { - RenderCommand *c = new RenderCommand(); - c->m_changeCost = i; + RenderCommand c; + c.m_changeCost = i; rawCommands.push_back(c); } @@ -322,10 +322,10 @@ private Q_SLOTS: renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); for (int j = 1; j < sortedCommands.size(); ++j) - QVERIFY(sortedCommands.at(j - 1)->m_changeCost > sortedCommands.at(j)->m_changeCost); + QVERIFY(sortedCommands.at(j - 1).m_changeCost > sortedCommands.at(j).m_changeCost); // RenderCommands are deleted by RenderView dtor } @@ -334,7 +334,7 @@ private Q_SLOTS: { // GIVEN RenderView renderView; - QVector rawCommands; + QVector rawCommands; QVector sortTypes; sortTypes.push_back(QSortPolicy::StateChangeCost); @@ -360,24 +360,24 @@ private Q_SLOTS: }; auto buildRC = [] (ProgramDNA dna, float depth, int changeCost) { - RenderCommand *c = new RenderCommand(); - c->m_shaderDna = dna; - c->m_depth = depth; - c->m_changeCost = changeCost; + RenderCommand c; + c.m_shaderDna = dna; + c.m_depth = depth; + c.m_changeCost = changeCost; return c; }; - RenderCommand *c5 = buildRC(dna[3], depth[1], stateChangeCost[1]); - RenderCommand *c3 = buildRC(dna[3], depth[0], stateChangeCost[1]); - RenderCommand *c4 = buildRC(dna[2], depth[1], stateChangeCost[1]); - RenderCommand *c8 = buildRC(dna[1], depth[1], stateChangeCost[1]); - RenderCommand *c0 = buildRC(dna[0], depth[2], stateChangeCost[1]); + RenderCommand c5 = buildRC(dna[3], depth[1], stateChangeCost[1]); + RenderCommand c3 = buildRC(dna[3], depth[0], stateChangeCost[1]); + RenderCommand c4 = buildRC(dna[2], depth[1], stateChangeCost[1]); + RenderCommand c8 = buildRC(dna[1], depth[1], stateChangeCost[1]); + RenderCommand c0 = buildRC(dna[0], depth[2], stateChangeCost[1]); - RenderCommand *c2 = buildRC(dna[2], depth[2], stateChangeCost[0]); - RenderCommand *c9 = buildRC(dna[2], depth[0], stateChangeCost[0]); - RenderCommand *c1 = buildRC(dna[1], depth[0], stateChangeCost[0]); - RenderCommand *c7 = buildRC(dna[0], depth[2], stateChangeCost[0]); - RenderCommand *c6 = buildRC(dna[0], depth[1], stateChangeCost[0]); + RenderCommand c2 = buildRC(dna[2], depth[2], stateChangeCost[0]); + RenderCommand c9 = buildRC(dna[2], depth[0], stateChangeCost[0]); + RenderCommand c1 = buildRC(dna[1], depth[0], stateChangeCost[0]); + RenderCommand c7 = buildRC(dna[0], depth[2], stateChangeCost[0]); + RenderCommand c6 = buildRC(dna[0], depth[1], stateChangeCost[0]); rawCommands << c0 << c1 << c2 << c3 << c4 << c5 << c6 << c7 << c8 << c9; @@ -387,12 +387,9 @@ private Q_SLOTS: renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); - for (RenderCommand *rc : sortedCommands) - qDebug() << rc->m_changeCost << rc->m_shaderDna << rc->m_depth; - // Ordered by higher state, higher shaderDNA and higher depth QCOMPARE(c0, sortedCommands.at(4)); QCOMPARE(c3, sortedCommands.at(1)); @@ -423,61 +420,60 @@ private Q_SLOTS: Qt3DCore::QNodeId tex3 = Qt3DCore::QNodeId::createId(); Qt3DCore::QNodeId tex4 = Qt3DCore::QNodeId::createId(); - RenderCommand *a = new RenderCommand(); + RenderCommand a; { ShaderParameterPack pack; pack.setTexture(0, 0, tex1); pack.setTexture(1, 0, tex3); pack.setTexture(2, 0, tex4); pack.setTexture(3, 0, tex2); - a->m_parameterPack = pack; + a.m_parameterPack = pack; } - RenderCommand *b = new RenderCommand(); - RenderCommand *c = new RenderCommand(); + RenderCommand b; + RenderCommand c; { ShaderParameterPack pack; pack.setTexture(0, 0, tex1); pack.setTexture(3, 0, tex2); - c->m_parameterPack = pack; + c.m_parameterPack = pack; } - RenderCommand *d = new RenderCommand(); + RenderCommand d; { ShaderParameterPack pack; pack.setTexture(1, 0, tex3); pack.setTexture(2, 0, tex4); - d->m_parameterPack = pack; + d.m_parameterPack = pack; } - RenderCommand *e = new RenderCommand(); + RenderCommand e; { ShaderParameterPack pack; pack.setTexture(3, 0, tex2); - e->m_parameterPack = pack; + e.m_parameterPack = pack; } - RenderCommand *f = new RenderCommand(); + RenderCommand f; { ShaderParameterPack pack; pack.setTexture(3, 0, tex2); - f->m_parameterPack = pack; + f.m_parameterPack = pack; } - RenderCommand *g = new RenderCommand(); + RenderCommand g; { ShaderParameterPack pack; pack.setTexture(0, 0, tex1); pack.setTexture(1, 0, tex3); pack.setTexture(2, 0, tex4); pack.setTexture(3, 0, tex2); - g->m_parameterPack = pack; + g.m_parameterPack = pack; } // WHEN - QVector rawCommands = {a, b, c, d, e, f, g}; + QVector rawCommands = {a, b, c, d, e, f, g}; renderView.addSortType(sortTypes); renderView.setCommands(rawCommands); renderView.sort(); // THEN - const QVector sortedCommands = renderView.commands(); - qDebug() << rawCommands << sortedCommands; + const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); QCOMPARE(sortedCommands.at(0), a); QCOMPARE(sortedCommands.at(1), g); -- cgit v1.2.3 From af354bc1df172be2c255e6b540ce62afa218951f Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Wed, 16 Oct 2019 07:49:07 +0200 Subject: Convert LoadBufferJob to use direct sync Change-Id: I44334264fba285494624a8a4ee6ff3b85755402c Reviewed-by: Mike Krus --- src/render/geometry/buffer.cpp | 9 --------- src/render/geometry/qbuffer.cpp | 18 +++++++++++------- src/render/geometry/qbuffer_p.h | 2 ++ src/render/jobs/loadbufferjob.cpp | 30 +++++++++++++++++++++++++++++- src/render/jobs/loadbufferjob_p.h | 4 ++++ tests/auto/render/buffer/tst_buffer.cpp | 5 +---- 6 files changed, 47 insertions(+), 21 deletions(-) diff --git a/src/render/geometry/buffer.cpp b/src/render/geometry/buffer.cpp index 0ce81efc1..df270ba3e 100644 --- a/src/render/geometry/buffer.cpp +++ b/src/render/geometry/buffer.cpp @@ -88,15 +88,6 @@ void Buffer::executeFunctor() m_data = (*m_functor)(); // Request data to be loaded forceDataUpload(); - - if (m_syncData) { - // Send data back to the frontend - auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(peerId()); - e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll); - e->setPropertyName("data"); - e->setValue(QVariant::fromValue(m_data)); - notifyObservers(e); - } } //Called from th sendBufferJob diff --git a/src/render/geometry/qbuffer.cpp b/src/render/geometry/qbuffer.cpp index d27da25c7..1cccb7a1f 100644 --- a/src/render/geometry/qbuffer.cpp +++ b/src/render/geometry/qbuffer.cpp @@ -58,6 +58,15 @@ QBufferPrivate::QBufferPrivate() { } +void QBufferPrivate::setData(const QByteArray &data) +{ + Q_Q(QBuffer); + const bool blocked = q->blockNotifications(true); + m_data = data; + emit q->dataChanged(data); + q->blockNotifications(blocked); +} + /*! * \qmltype Buffer * \instantiates Qt3DRender::QBuffer @@ -308,11 +317,7 @@ void QBuffer::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) if (change->type() == PropertyUpdated) { QPropertyUpdatedChangePtr e = qSharedPointerCast(change); const QByteArray propertyName = e->propertyName(); - if (propertyName == QByteArrayLiteral("data")) { - const bool blocked = blockNotifications(true); - setData(e->value().toByteArray()); - blockNotifications(blocked); - } else if (propertyName == QByteArrayLiteral("downloadedData")) { + if (propertyName == QByteArrayLiteral("downloadedData")) { const bool blocked = blockNotifications(true); setData(e->value().toByteArray()); blockNotifications(blocked); @@ -328,9 +333,8 @@ void QBuffer::setData(const QByteArray &bytes) { Q_D(QBuffer); if (bytes != d->m_data) { - d->m_data = bytes; + d->setData(bytes); d->update(); - emit dataChanged(bytes); } } diff --git a/src/render/geometry/qbuffer_p.h b/src/render/geometry/qbuffer_p.h index 7a0ffdfb9..6da28e88b 100644 --- a/src/render/geometry/qbuffer_p.h +++ b/src/render/geometry/qbuffer_p.h @@ -75,6 +75,8 @@ public: QBufferDataGeneratorPtr m_functor; bool m_syncData; QBuffer::AccessType m_access; + + void setData(const QByteArray &data); }; struct QBufferData diff --git a/src/render/jobs/loadbufferjob.cpp b/src/render/jobs/loadbufferjob.cpp index 49f271df5..c9cbb623d 100644 --- a/src/render/jobs/loadbufferjob.cpp +++ b/src/render/jobs/loadbufferjob.cpp @@ -39,9 +39,11 @@ #include "loadbufferjob_p.h" #include +#include #include #include #include +#include QT_BEGIN_NAMESPACE @@ -49,9 +51,20 @@ namespace Qt3DRender { namespace Render { +class LoadBufferJobPrivate : public Qt3DCore::QAspectJobPrivate +{ +public: + LoadBufferJobPrivate() {} + ~LoadBufferJobPrivate() {} + + void postFrame(Qt3DCore::QAspectManager *aspectManager) override; + + Buffer *m_bufferToUpdate = nullptr; +}; + LoadBufferJob::LoadBufferJob(const HBuffer &handle) - : QAspectJob() + : QAspectJob(*new LoadBufferJobPrivate) , m_handle(handle) , m_nodeManagers(nullptr) { @@ -64,10 +77,25 @@ LoadBufferJob::~LoadBufferJob() void LoadBufferJob::run() { + Q_D(LoadBufferJob); // Let's leave it for the moment until this has been properly tested qCDebug(Jobs) << Q_FUNC_INFO; Buffer *buffer = m_nodeManagers->data(m_handle); buffer->executeFunctor(); + if (buffer->isSyncData()) + d->m_bufferToUpdate = buffer; +} + +void LoadBufferJobPrivate::postFrame(Qt3DCore::QAspectManager *aspectManager) +{ + if (m_bufferToUpdate == nullptr) + return; + QBuffer *frontendBuffer = static_cast(aspectManager->lookupNode(m_bufferToUpdate->peerId())); + QBufferPrivate *dFrontend = static_cast(Qt3DCore::QNodePrivate::get(frontendBuffer)); + // Calling frontendBuffer->setData would result in forcing a sync against the backend + // which isn't necessary + dFrontend->setData(m_bufferToUpdate->data()); + m_bufferToUpdate = nullptr; } } // namespace Render diff --git a/src/render/jobs/loadbufferjob_p.h b/src/render/jobs/loadbufferjob_p.h index 6a221c7e0..e86e4f835 100644 --- a/src/render/jobs/loadbufferjob_p.h +++ b/src/render/jobs/loadbufferjob_p.h @@ -63,6 +63,7 @@ namespace Qt3DRender { namespace Render { class NodeManagers; +class LoadBufferJobPrivate; class Q_AUTOTEST_EXPORT LoadBufferJob : public Qt3DCore::QAspectJob { @@ -76,6 +77,9 @@ public: protected: HBuffer m_handle; NodeManagers *m_nodeManagers; + +private: + Q_DECLARE_PRIVATE(LoadBufferJob) }; typedef QSharedPointer LoadBufferJobPtr; diff --git a/tests/auto/render/buffer/tst_buffer.cpp b/tests/auto/render/buffer/tst_buffer.cpp index 48215bea5..1b53efd33 100644 --- a/tests/auto/render/buffer/tst_buffer.cpp +++ b/tests/auto/render/buffer/tst_buffer.cpp @@ -237,10 +237,7 @@ private Q_SLOTS: backendBuffer.executeFunctor(); // THEN - QCOMPARE(arbiter.events.count(), 1); - Qt3DCore::QPropertyUpdatedChangePtr change = arbiter.events.first().staticCast(); - QCOMPARE(change->propertyName(), "data"); - QCOMPARE(change->value().toByteArray(), QByteArrayLiteral("454")); + QCOMPARE(arbiter.events.count(), 0); QCOMPARE(backendBuffer.pendingBufferUpdates().size(), 1); QCOMPARE(backendBuffer.pendingBufferUpdates().first().offset, -1); -- cgit v1.2.3 From ae88eeee627664b06935004cc0d2868b65905d62 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Wed, 16 Oct 2019 09:19:11 +0200 Subject: Convent SendBufferCaptureJob to direct sync Change-Id: I8d5bc69cb75d73e628f08d70b2e40d665c39802b Reviewed-by: Mike Krus --- src/render/geometry/buffer.cpp | 6 --- src/render/geometry/qbuffer.cpp | 17 ------ src/render/geometry/qbuffer.h | 3 -- src/render/jobs/sendbuffercapturejob.cpp | 66 ++++++++++++++++++----- src/render/jobs/sendbuffercapturejob_p.h | 10 ++-- src/render/renderers/opengl/renderer/renderer.cpp | 25 ++++++--- src/render/renderers/opengl/renderer/renderer_p.h | 2 +- tests/auto/render/renderer/tst_renderer.cpp | 2 +- 8 files changed, 79 insertions(+), 52 deletions(-) diff --git a/src/render/geometry/buffer.cpp b/src/render/geometry/buffer.cpp index df270ba3e..0d634c911 100644 --- a/src/render/geometry/buffer.cpp +++ b/src/render/geometry/buffer.cpp @@ -96,12 +96,6 @@ void Buffer::updateDataFromGPUToCPU(QByteArray data) // Note: when this is called, data is what's currently in GPU memory // so m_data shouldn't be reuploaded m_data = data; - // Send data back to the frontend - auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(peerId()); - e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll); - e->setPropertyName("downloadedData"); - e->setValue(QVariant::fromValue(m_data)); - notifyObservers(e); } void Buffer::forceDataUpload() diff --git a/src/render/geometry/qbuffer.cpp b/src/render/geometry/qbuffer.cpp index 1cccb7a1f..bbe08fdf7 100644 --- a/src/render/geometry/qbuffer.cpp +++ b/src/render/geometry/qbuffer.cpp @@ -309,23 +309,6 @@ QBuffer::~QBuffer() { } -/*! - * \internal - */ -void QBuffer::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) -{ - if (change->type() == PropertyUpdated) { - QPropertyUpdatedChangePtr e = qSharedPointerCast(change); - const QByteArray propertyName = e->propertyName(); - if (propertyName == QByteArrayLiteral("downloadedData")) { - const bool blocked = blockNotifications(true); - setData(e->value().toByteArray()); - blockNotifications(blocked); - Q_EMIT dataAvailable(); - } - } -} - /*! * Sets \a bytes as data. */ diff --git a/src/render/geometry/qbuffer.h b/src/render/geometry/qbuffer.h index 1bd1aa8fd..4d5f6c86e 100644 --- a/src/render/geometry/qbuffer.h +++ b/src/render/geometry/qbuffer.h @@ -118,9 +118,6 @@ public Q_SLOTS: void setSyncData(bool syncData); void setAccessType(AccessType access); -protected: - void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; - Q_SIGNALS: void dataChanged(const QByteArray &bytes); void typeChanged(BufferType type); diff --git a/src/render/jobs/sendbuffercapturejob.cpp b/src/render/jobs/sendbuffercapturejob.cpp index 8683ea9f2..3fa185684 100644 --- a/src/render/jobs/sendbuffercapturejob.cpp +++ b/src/render/jobs/sendbuffercapturejob.cpp @@ -39,11 +39,12 @@ #include "sendbuffercapturejob_p.h" - -#include "Qt3DRender/private/renderer_p.h" -#include "Qt3DRender/private/nodemanagers_p.h" +#include #include #include +#include +#include +#include QT_BEGIN_NAMESPACE @@ -51,8 +52,22 @@ namespace Qt3DRender { namespace Render { +class SendBufferCaptureJobPrivate : public Qt3DCore::QAspectJobPrivate +{ +public: + SendBufferCaptureJobPrivate() {} + ~SendBufferCaptureJobPrivate() {} + + void postFrame(Qt3DCore::QAspectManager *aspectManager) override; + + mutable QMutex m_mutex; + QVector> m_buffersToCapture; + QVector> m_buffersToNotify; +}; + SendBufferCaptureJob::SendBufferCaptureJob() - : Qt3DCore::QAspectJob() + : Qt3DCore::QAspectJob(*new SendBufferCaptureJobPrivate) + , m_nodeManagers(nullptr) { SET_JOB_RUN_STAT_TYPE(this, JobTypes::SendBufferCapture, 0); } @@ -61,26 +76,51 @@ SendBufferCaptureJob::~SendBufferCaptureJob() { } -void SendBufferCaptureJob::addRequest(QPair request) +// Called from SubmitRenderView while rendering +void SendBufferCaptureJob::addRequest(QPair request) { - QMutexLocker locker(&m_mutex); - m_pendingSendBufferCaptures.push_back(request); + Q_D(SendBufferCaptureJob); + QMutexLocker locker(&d->m_mutex); + d->m_buffersToCapture.push_back(request); } -// Called by aspect thread jobs to execute (no concurrency at that point) +// Called by aspect thread jobs to execute (we may still be rendering at this point) bool SendBufferCaptureJob::hasRequests() const { - return m_pendingSendBufferCaptures.size() > 0; + Q_D(const SendBufferCaptureJob); + QMutexLocker locker(&d->m_mutex); + return d->m_buffersToCapture.size() > 0; } void SendBufferCaptureJob::run() { - QMutexLocker locker(&m_mutex); - for (const QPair &pendingCapture : qAsConst(m_pendingSendBufferCaptures)) { - pendingCapture.first->updateDataFromGPUToCPU(pendingCapture.second); + Q_ASSERT(m_nodeManagers); + Q_D(SendBufferCaptureJob); + QMutexLocker locker(&d->m_mutex); + for (const QPair &pendingCapture : qAsConst(d->m_buffersToCapture)) { + Buffer *buffer = m_nodeManagers->bufferManager()->lookupResource(pendingCapture.first); + // Buffer might have been destroyed between the time addRequest is made and this job gets run + // If it exists however, it cannot be destroyed before this job is done running + if (buffer != nullptr) + buffer->updateDataFromGPUToCPU(pendingCapture.second); } + d->m_buffersToNotify = std::move(d->m_buffersToCapture); +} - m_pendingSendBufferCaptures.clear(); +void SendBufferCaptureJobPrivate::postFrame(Qt3DCore::QAspectManager *aspectManager) +{ + QMutexLocker locker(&m_mutex); + const QVector> pendingSendBufferCaptures = std::move(m_buffersToNotify); + for (const auto &bufferDataPair : pendingSendBufferCaptures) { + QBuffer *frontendBuffer = static_cast(aspectManager->lookupNode(bufferDataPair.first)); + if (!frontendBuffer) + continue; + QBufferPrivate *dFrontend = static_cast(Qt3DCore::QNodePrivate::get(frontendBuffer)); + // Calling frontendBuffer->setData would result in forcing a sync against the backend + // which isn't necessary + dFrontend->setData(bufferDataPair.second); + Q_EMIT frontendBuffer->dataAvailable(); + } } } // Render diff --git a/src/render/jobs/sendbuffercapturejob_p.h b/src/render/jobs/sendbuffercapturejob_p.h index f47c556df..3b9f5d12b 100644 --- a/src/render/jobs/sendbuffercapturejob_p.h +++ b/src/render/jobs/sendbuffercapturejob_p.h @@ -52,6 +52,7 @@ // #include +#include #include #include #include @@ -67,6 +68,7 @@ class NodeManagers; class Entity; class Renderer; class Buffer; +class SendBufferCaptureJobPrivate; class Q_3DRENDERSHARED_PRIVATE_EXPORT SendBufferCaptureJob : public Qt3DCore::QAspectJob { @@ -74,15 +76,15 @@ public: explicit SendBufferCaptureJob(); ~SendBufferCaptureJob(); - void addRequest(QPair request); + void setManagers(NodeManagers *nodeManagers) { m_nodeManagers = nodeManagers; } + void addRequest(QPair request); bool hasRequests() const; void run() final; private: - QMutex m_mutex; - - QVector > m_pendingSendBufferCaptures; + Q_DECLARE_PRIVATE(SendBufferCaptureJob) + NodeManagers *m_nodeManagers; }; typedef QSharedPointer SendBufferCaptureJobPtr; diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index f17e66108..35c4d553f 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -306,6 +306,7 @@ void Renderer::setNodeManagers(NodeManagers *managers) m_filterCompatibleTechniqueJob->setManager(m_nodesManager->techniqueManager()); m_updateEntityLayersJob->setManager(m_nodesManager); m_updateTreeEnabledJob->setManagers(m_nodesManager); + m_sendBufferCaptureJob->setManagers(m_nodesManager); } void Renderer::setServices(QServiceLocator *services) @@ -1045,6 +1046,7 @@ void Renderer::lookForDirtyBuffers() } } +// Called in prepareSubmission void Renderer::lookForDownloadableBuffers() { m_downloadableBuffers.clear(); @@ -1052,7 +1054,7 @@ void Renderer::lookForDownloadableBuffers() for (const HBuffer &handle : activeBufferHandles) { Buffer *buffer = m_nodesManager->bufferManager()->data(handle); if (buffer->access() & QBuffer::Read) - m_downloadableBuffers.push_back(handle); + m_downloadableBuffers.push_back(buffer->peerId()); } } @@ -1358,6 +1360,9 @@ void Renderer::updateGLResources() // Record ids of texture to cleanup while we are still blocking the aspect thread m_textureIdsToCleanup += m_nodesManager->textureManager()->takeTexturesIdsToCleanup(); } + + // Record list of buffer that might need uploading + lookForDownloadableBuffers(); } // Render Thread @@ -1440,12 +1445,18 @@ void Renderer::cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId) // Called by SubmitRenderView void Renderer::downloadGLBuffers() { - lookForDownloadableBuffers(); - const QVector downloadableHandles = std::move(m_downloadableBuffers); - for (const HBuffer &handle : downloadableHandles) { - Buffer *buffer = m_nodesManager->bufferManager()->data(handle); - QByteArray content = m_submissionContext->downloadBufferContent(buffer); - m_sendBufferCaptureJob->addRequest(QPair(buffer, content)); + const QVector downloadableHandles = std::move(m_downloadableBuffers); + for (const Qt3DCore::QNodeId &bufferId : downloadableHandles) { + BufferManager *bufferManager = m_nodesManager->bufferManager(); + BufferManager::ReadLocker locker(const_cast(bufferManager)); + Buffer *buffer = bufferManager->lookupResource(bufferId); + // Buffer could have been destroyed at this point + if (!buffer) + continue; + // locker is protecting us from the buffer being destroy while we're looking + // up its content + const QByteArray content = m_submissionContext->downloadBufferContent(buffer); + m_sendBufferCaptureJob->addRequest(QPair(bufferId, content)); } } diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index db63f31d0..7b1349503 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -401,7 +401,7 @@ private: QVector m_abandonedVaos; QVector m_dirtyBuffers; - QVector m_downloadableBuffers; + QVector m_downloadableBuffers; QVector m_dirtyShaders; QVector m_dirtyTextures; QVector> m_updatedTextureProperties; diff --git a/tests/auto/render/renderer/tst_renderer.cpp b/tests/auto/render/renderer/tst_renderer.cpp index 65309707c..f8125bce4 100644 --- a/tests/auto/render/renderer/tst_renderer.cpp +++ b/tests/auto/render/renderer/tst_renderer.cpp @@ -88,7 +88,7 @@ private Q_SLOTS: 1); // SendRenderCaptureJob // WHEN - renderer.m_sendBufferCaptureJob->addRequest({nullptr, {}}); + renderer.m_sendBufferCaptureJob->addRequest({Qt3DCore::QNodeId(), {}}); jobs = renderer.preRenderingJobs(); // THEN -- cgit v1.2.3 From 1e499f548a24482a0809a34767a04c91a940ffe8 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Tue, 8 Oct 2019 08:01:10 +0100 Subject: Remove old code from animation classes & update tests Change-Id: Ic91a4f168172d6f34d858488e6fc170e8ed875f9 Reviewed-by: Paul Lemire --- src/core/transforms/qabstractskeleton.cpp | 11 ------- src/core/transforms/qabstractskeleton.h | 1 - .../channelmapping/tst_channelmapping.cpp | 32 +++++++++++++------ tests/auto/core/qskeleton/tst_qskeleton.cpp | 36 ---------------------- tests/auto/render/skeleton/tst_skeleton.cpp | 23 +------------- 5 files changed, 24 insertions(+), 79 deletions(-) diff --git a/src/core/transforms/qabstractskeleton.cpp b/src/core/transforms/qabstractskeleton.cpp index 0cc1a28d2..e401c3043 100644 --- a/src/core/transforms/qabstractskeleton.cpp +++ b/src/core/transforms/qabstractskeleton.cpp @@ -39,7 +39,6 @@ #include "qabstractskeleton.h" #include "qabstractskeleton_p.h" -#include QT_BEGIN_NAMESPACE @@ -128,16 +127,6 @@ void QAbstractSkeletonPrivate::setJointCount(int jointCount) q->blockNotifications(block); } -void QAbstractSkeleton::sceneChangeEvent(const QSceneChangePtr &change) -{ - Q_D(QAbstractSkeleton); - if (change->type() == Qt3DCore::PropertyUpdated) { - const Qt3DCore::QPropertyUpdatedChangePtr e = qSharedPointerCast(change); - if (e->propertyName() == QByteArrayLiteral("jointCount")) - d->setJointCount(e->value().toInt()); - } -} - } // namespace Qt3DCore QT_END_NAMESPACE diff --git a/src/core/transforms/qabstractskeleton.h b/src/core/transforms/qabstractskeleton.h index 902def9f8..7da78011f 100644 --- a/src/core/transforms/qabstractskeleton.h +++ b/src/core/transforms/qabstractskeleton.h @@ -64,7 +64,6 @@ Q_SIGNALS: protected: QAbstractSkeleton(QAbstractSkeletonPrivate &dd, Qt3DCore::QNode *parent = nullptr); - void sceneChangeEvent(const QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QAbstractSkeleton) diff --git a/tests/auto/animation/channelmapping/tst_channelmapping.cpp b/tests/auto/animation/channelmapping/tst_channelmapping.cpp index e108e3d26..26a57449d 100644 --- a/tests/auto/animation/channelmapping/tst_channelmapping.cpp +++ b/tests/auto/animation/channelmapping/tst_channelmapping.cpp @@ -38,7 +38,6 @@ #include #include #include -#include #include #include "testpostmanarbiter.h" @@ -181,16 +180,31 @@ private Q_SLOTS: const char *testName = "translation"; QCOMPARE(qstrcmp(testName, backendMapping.propertyName()), 0); + } -// // WHEN -// const auto skeletonId = Qt3DCore::QNodeId::createId(); -// updateChange = QSharedPointer::create(Qt3DCore::QNodeId()); -// updateChange->setPropertyName("skeleton"); -// updateChange->setValue(QVariant::fromValue(skeletonId)); -// backendMapping.sceneChangeEvent(updateChange); + void checkSkeletonPropertyUpdate() + { + // GIVEN + Qt3DAnimation::QSkeletonMapping mapping; + Qt3DAnimation::Animation::Handler handler; + Qt3DAnimation::Animation::ChannelMapping backendMapping; + backendMapping.setHandler(&handler); + simulateInitializationSync(&mapping, &backendMapping); -// // THEN -// QCOMPARE(backendMapping.skeletonId(), skeletonId); + // WHEN + mapping.setEnabled(false); + backendMapping.syncFromFrontEnd(&mapping, false); + + // THEN + QCOMPARE(backendMapping.isEnabled(), false); + + // WHEN + auto skeleton = new Qt3DCore::QSkeleton; + mapping.setSkeleton(skeleton); + backendMapping.syncFromFrontEnd(&mapping, false); + + // THEN + QCOMPARE(backendMapping.skeletonId(), skeleton->id()); } }; diff --git a/tests/auto/core/qskeleton/tst_qskeleton.cpp b/tests/auto/core/qskeleton/tst_qskeleton.cpp index 299567806..5c88bd754 100644 --- a/tests/auto/core/qskeleton/tst_qskeleton.cpp +++ b/tests/auto/core/qskeleton/tst_qskeleton.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -160,41 +159,6 @@ private Q_SLOTS: // THEN Should not crash when the joint is destroyed (tests for failed removal of destruction helper) } } - - void checkJointCountPropertyUpdate() - { - // GIVEN - TestArbiter arbiter; - arbiter.setArbiterOnNode(this); - QSignalSpy spy(this, SIGNAL(jointCountChanged(int))); - const int newJointCount = 99; - - // THEN - QVERIFY(spy.isValid()); - - // WHEN - auto valueChange = QPropertyUpdatedChangePtr::create(Qt3DCore::QNodeId()); - valueChange->setPropertyName("jointCount"); - valueChange->setValue(QVariant(newJointCount)); - sceneChangeEvent(valueChange); - - // THEN - QCOMPARE(spy.count(), 1); - QCOMPARE(arbiter.events.size(), 0); - QCOMPARE(jointCount(), newJointCount); - - // WHEN - spy.clear(); - sceneChangeEvent(valueChange); - - // THEN - QCOMPARE(spy.count(), 0); - QCOMPARE(arbiter.events.size(), 0); - QCOMPARE(jointCount(), newJointCount); - - // Cleanup - QNodePrivate::get(this)->setArbiter(nullptr); - } }; QTEST_MAIN(tst_QSkeleton) diff --git a/tests/auto/render/skeleton/tst_skeleton.cpp b/tests/auto/render/skeleton/tst_skeleton.cpp index 6af055fb0..2786f27a8 100644 --- a/tests/auto/render/skeleton/tst_skeleton.cpp +++ b/tests/auto/render/skeleton/tst_skeleton.cpp @@ -34,9 +34,7 @@ #include #include #include -#include #include -#include #include #include #include @@ -49,24 +47,6 @@ Q_DECLARE_METATYPE(Qt3DRender::Render::JointInfo) Q_DECLARE_METATYPE(Qt3DRender::Render::SkeletonData) Q_DECLARE_METATYPE(Qt3DCore::Sqt) -namespace { - -void linearizeTreeHelper(QJoint *joint, QVector &joints) -{ - joints.push_back(joint); - for (const auto child : joint->childJoints()) - linearizeTreeHelper(child, joints); -} - -QVector linearizeTree(QJoint *rootJoint) -{ - QVector joints; - linearizeTreeHelper(rootJoint, joints); - return joints; -} - -} - class tst_Skeleton : public Qt3DCore::QBackendNodeTester { Q_OBJECT @@ -155,7 +135,6 @@ private Q_SLOTS: backendSkeleton.setRenderer(&renderer); backendSkeleton.setSkeletonManager(nodeManagers.skeletonManager()); backendSkeleton.setDataType(Skeleton::File); - Qt3DCore::QPropertyUpdatedChangePtr updateChange; // Initialize to ensure skeleton manager is set QSkeletonLoader skeleton; @@ -225,7 +204,7 @@ private Q_SLOTS: QTest::addColumn("skeletonData"); QTest::addColumn("expectedRootJoint"); - QTest::newRow("empty") << SkeletonData() << (QJoint*)nullptr; + QTest::newRow("empty") << SkeletonData() << static_cast(nullptr); SkeletonData skeletonData; JointInfo rootJointInfo; -- cgit v1.2.3 From 7f3bba6e8a4a3bdb36f40a636b76c02902c09d02 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Tue, 22 Oct 2019 07:53:00 +0200 Subject: QMouseEvent: fix BIC issue following Modifier/Modifiers change Will have to be done only in Qt6 unfortunately. For now we abused the fact that an int is used to store the enum so that we store multiple Modifiers values into one Modifiers enum. Change-Id: Ib111140afbe07cfd62fcf3cb8e1a57d3ad848a89 Reviewed-by: Mike Krus --- src/input/frontend/qmouseevent.cpp | 6 +- src/input/frontend/qmouseevent.h | 15 ++-- tests/auto/input/input.pro | 3 +- tests/auto/input/qmouseevent/qmouseevent.pro | 11 +++ tests/auto/input/qmouseevent/tst_qmouseevent.cpp | 93 ++++++++++++++++++++++++ 5 files changed, 116 insertions(+), 12 deletions(-) create mode 100644 tests/auto/input/qmouseevent/qmouseevent.pro create mode 100644 tests/auto/input/qmouseevent/tst_qmouseevent.cpp diff --git a/src/input/frontend/qmouseevent.cpp b/src/input/frontend/qmouseevent.cpp index 2033eed36..2b06c824d 100644 --- a/src/input/frontend/qmouseevent.cpp +++ b/src/input/frontend/qmouseevent.cpp @@ -49,7 +49,7 @@ template typename EventClass::Modifiers modifiersForEvent(const QtEventClass &event) { const Qt::KeyboardModifiers eventModifiers = event.modifiers(); - typename EventClass::Modifiers modifiers = EventClass::NoModifier; + int modifiers = EventClass::NoModifier; if (eventModifiers & Qt::ShiftModifier) modifiers |= EventClass::ShiftModifier; @@ -66,7 +66,9 @@ typename EventClass::Modifiers modifiersForEvent(const QtEventClass &event) if (eventModifiers & Qt::KeypadModifier) modifiers |= EventClass::KeypadModifier; - return modifiers; + // Abuse the int used to store an enum to store multiple + // modifiers into one + return static_cast(modifiers); } } // anonymous diff --git a/src/input/frontend/qmouseevent.h b/src/input/frontend/qmouseevent.h index 1402d8210..ae44d9365 100644 --- a/src/input/frontend/qmouseevent.h +++ b/src/input/frontend/qmouseevent.h @@ -70,7 +70,7 @@ public: }; Q_ENUM(Buttons) // LCOV_EXCL_LINE - enum Modifier { + enum Modifiers { NoModifier = Qt::NoModifier, ShiftModifier = Qt::ShiftModifier, ControlModifier = Qt::ControlModifier, @@ -78,8 +78,8 @@ public: MetaModifier = Qt::MetaModifier, KeypadModifier = Qt::KeypadModifier }; - Q_DECLARE_FLAGS(Modifiers, Modifier) - Q_FLAG(Modifiers) + Q_ENUM(Modifiers) // LCOV_EXCL_LINE + // TO DO Qt6 Modifiers -> Modifier and add Q_FLAG(Modifiers) explicit QMouseEvent(const QT_PREPEND_NAMESPACE(QMouseEvent) &e); ~QMouseEvent(); @@ -128,7 +128,7 @@ public: }; Q_ENUM(Buttons) // LCOV_EXCL_LINE - enum Modifier { + enum Modifiers { NoModifier = Qt::NoModifier, ShiftModifier = Qt::ShiftModifier, ControlModifier = Qt::ControlModifier, @@ -136,8 +136,8 @@ public: MetaModifier = Qt::MetaModifier, KeypadModifier = Qt::KeypadModifier }; - Q_DECLARE_FLAGS(Modifiers, Modifier) - Q_FLAG(Modifiers) + Q_ENUM(Modifiers) // LCOV_EXCL_LINE + // TO DO Qt6 Modifiers -> Modifier and add Q_FLAG(Modifiers) explicit QWheelEvent(const QT_PREPEND_NAMESPACE(QWheelEvent) &e); ~QWheelEvent(); @@ -161,9 +161,6 @@ typedef QSharedPointer QWheelEventPtr; } // namespace Qt3DInput -Q_DECLARE_OPERATORS_FOR_FLAGS(Qt3DInput::QMouseEvent::Modifiers) -Q_DECLARE_OPERATORS_FOR_FLAGS(Qt3DInput::QWheelEvent::Modifiers) - QT_END_NAMESPACE Q_DECLARE_METATYPE(Qt3DInput::QMouseEvent*) // LCOV_EXCL_LINE diff --git a/tests/auto/input/input.pro b/tests/auto/input/input.pro index 6169d3f7c..7799c2b89 100644 --- a/tests/auto/input/input.pro +++ b/tests/auto/input/input.pro @@ -29,5 +29,6 @@ qtConfig(private_tests) { mousedevice \ utils \ axisaccumulator \ - axisaccumulatorjob + axisaccumulatorjob \ + qmouseevent } diff --git a/tests/auto/input/qmouseevent/qmouseevent.pro b/tests/auto/input/qmouseevent/qmouseevent.pro new file mode 100644 index 000000000..70f4c6eda --- /dev/null +++ b/tests/auto/input/qmouseevent/qmouseevent.pro @@ -0,0 +1,11 @@ +TEMPLATE = app + +TARGET = tst_qmouseevent + +QT += 3dcore 3dcore-private 3dinput 3dinput-private testlib + +CONFIG += testcase + +SOURCES += tst_qmouseevent.cpp + +include(../commons/commons.pri) diff --git a/tests/auto/input/qmouseevent/tst_qmouseevent.cpp b/tests/auto/input/qmouseevent/tst_qmouseevent.cpp new file mode 100644 index 000000000..b48afb99d --- /dev/null +++ b/tests/auto/input/qmouseevent/tst_qmouseevent.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include +#include +#include +#include +#include + +class tst_QMouseEvent : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void checkModifiers() + { + { + // GIVEN + QT_PREPEND_NAMESPACE(QMouseEvent) event(QEvent::MouseButtonPress, + QPointF(500, 500), + QPointF(500, 500), + Qt::LeftButton, + Qt::LeftButton, + Qt::NoModifier); + + // WHEN + Qt3DInput::QMouseEvent event3D(event); + + // THEN + QCOMPARE(event3D.modifiers(), Qt3DInput::QMouseEvent::NoModifier); + } + { + // GIVEN + QT_PREPEND_NAMESPACE(QMouseEvent) event(QEvent::MouseButtonPress, + QPointF(500, 500), + QPointF(500, 500), + Qt::LeftButton, + Qt::LeftButton, + Qt::ShiftModifier); + + // WHEN + Qt3DInput::QMouseEvent event3D(event); + + // THEN + QCOMPARE(event3D.modifiers(), Qt3DInput::QMouseEvent::ShiftModifier); + } + { + // GIVEN + QT_PREPEND_NAMESPACE(QMouseEvent) event(QEvent::MouseButtonPress, + QPointF(500, 500), + QPointF(500, 500), + Qt::LeftButton, + Qt::LeftButton, + Qt::ShiftModifier|Qt::ControlModifier); + + // WHEN + Qt3DInput::QMouseEvent event3D(event); + + // THEN + QCOMPARE(int(event3D.modifiers()), int(Qt3DInput::QMouseEvent::ShiftModifier|Qt3DInput::QMouseEvent::ControlModifier)); + } + } +}; + +QTEST_MAIN(tst_QMouseEvent) + +#include "tst_qmouseevent.moc" -- cgit v1.2.3 From 4d0f8bcdea22f70dbf693545d56e1399b3ca0250 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Tue, 22 Oct 2019 08:03:42 +0100 Subject: Remove remaining messaging code in QSkeletonLoader And matching unit tests Change-Id: Iff0b13b2ad9ff07d08c767f4b20de2a1685a5570 Reviewed-by: Paul Lemire --- src/core/transforms/qskeletonloader.cpp | 12 ---- .../core/qskeletonloader/tst_qskeletonloader.cpp | 65 ---------------------- tests/auto/render/skeleton/tst_skeleton.cpp | 64 --------------------- 3 files changed, 141 deletions(-) diff --git a/src/core/transforms/qskeletonloader.cpp b/src/core/transforms/qskeletonloader.cpp index d5296ecc9..b8cd6e29b 100644 --- a/src/core/transforms/qskeletonloader.cpp +++ b/src/core/transforms/qskeletonloader.cpp @@ -238,18 +238,6 @@ void QSkeletonLoader::setRootJoint(QJoint *rootJoint) /*! \internal */ void QSkeletonLoader::sceneChangeEvent(const QSceneChangePtr &change) { - Q_D(QSkeletonLoader); - if (change->type() == Qt3DCore::PropertyUpdated) { - auto propertyChange = qSharedPointerCast(change); - if (propertyChange->propertyName() == QByteArrayLiteral("status")) { - const auto e = qSharedPointerCast(change); - d->setStatus(static_cast(e->value().toInt())); - } else if (propertyChange->propertyName() == QByteArrayLiteral("rootJoint")) { - auto typedChange = qSharedPointerCast(propertyChange); - auto rootJoint = std::move(typedChange->data); - setRootJoint(rootJoint.release()); - } - } QAbstractSkeleton::sceneChangeEvent(change); } diff --git a/tests/auto/core/qskeletonloader/tst_qskeletonloader.cpp b/tests/auto/core/qskeletonloader/tst_qskeletonloader.cpp index 7fcdc4bbe..f0f4c3872 100644 --- a/tests/auto/core/qskeletonloader/tst_qskeletonloader.cpp +++ b/tests/auto/core/qskeletonloader/tst_qskeletonloader.cpp @@ -209,71 +209,6 @@ private Q_SLOTS: QCOMPARE(arbiter.events.size(), 0); } } - - void checkStatusPropertyUpdate() - { - // GIVEN - qRegisterMetaType("Status"); - TestArbiter arbiter; - arbiter.setArbiterOnNode(this); - QSignalSpy spy(this, SIGNAL(statusChanged(Status))); - const QSkeletonLoader::Status newStatus = QSkeletonLoader::Error; - - // THEN - QVERIFY(spy.isValid()); - - // WHEN - QPropertyUpdatedChangePtr valueChange(new QPropertyUpdatedChange(QNodeId())); - valueChange->setPropertyName("status"); - valueChange->setValue(QVariant::fromValue(newStatus)); - sceneChangeEvent(valueChange); - - // THEN - QCOMPARE(spy.count(), 1); - QCOMPARE(arbiter.events.size(), 0); - QCOMPARE(status(), newStatus); - - // WHEN - spy.clear(); - sceneChangeEvent(valueChange); - - // THEN - QCOMPARE(spy.count(), 0); - QCOMPARE(arbiter.events.size(), 0); - QCOMPARE(status(), newStatus); - - // Cleanup - QNodePrivate::get(this)->setArbiter(nullptr); - } - - void checkRootJointPropertyUpdate() - { - // GIVEN - qRegisterMetaType(); - TestArbiter arbiter; - arbiter.setArbiterOnNode(this); - QSignalSpy spy(this, SIGNAL(rootJointChanged(Qt3DCore::QJoint*))); - std::unique_ptr root(new QJoint()); - - // THEN - QVERIFY(spy.isValid()); - QVERIFY(rootJoint() == nullptr); - - // WHEN - auto valueChange = QJointChangePtr::create(id()); - valueChange->setDeliveryFlags(Qt3DCore::QSceneChange::Nodes); - valueChange->setPropertyName("rootJoint"); - valueChange->data = std::move(root); - sceneChangeEvent(valueChange); - - // THEN - QCOMPARE(spy.count(), 1); - QCOMPARE(arbiter.dirtyNodes.size(), 1); - QVERIFY(rootJoint() != nullptr); - - // Cleanup - QNodePrivate::get(this)->setArbiter(nullptr); - } }; QTEST_MAIN(tst_QSkeletonLoader) diff --git a/tests/auto/render/skeleton/tst_skeleton.cpp b/tests/auto/render/skeleton/tst_skeleton.cpp index 2786f27a8..63ed51058 100644 --- a/tests/auto/render/skeleton/tst_skeleton.cpp +++ b/tests/auto/render/skeleton/tst_skeleton.cpp @@ -198,70 +198,6 @@ private Q_SLOTS: joint->setName(name); QTest::newRow("inverseBind") << m << localPose << name << joint; } - - void checkCreateFrontendJoints_data() - { - QTest::addColumn("skeletonData"); - QTest::addColumn("expectedRootJoint"); - - QTest::newRow("empty") << SkeletonData() << static_cast(nullptr); - - SkeletonData skeletonData; - JointInfo rootJointInfo; - skeletonData.joints.push_back(rootJointInfo); - skeletonData.jointNames.push_back(QLatin1String("rootJoint")); - skeletonData.localPoses.push_back(Qt3DCore::Sqt()); - const int childCount = 10; - for (int i = 0; i < childCount; ++i) { - JointInfo childJointInfo; - childJointInfo.parentIndex = 0; - skeletonData.joints.push_back(childJointInfo); - - const float x = static_cast(i); - Qt3DCore::Sqt localPose; - localPose.translation = QVector3D(x, x, x); - skeletonData.localPoses.push_back(localPose); - - skeletonData.jointNames.push_back(QString("Child-%1").arg(i)); - } - - QJoint *rootJoint = new QJoint(); - for (int i = 0; i < childCount; ++i) { - QJoint *childJoint = new QJoint(); - const float x = static_cast(i); - childJoint->setTranslation(QVector3D(x, x, x)); - rootJoint->addChildJoint(childJoint); - } - - QTest::newRow("wide") << skeletonData << rootJoint; - - skeletonData.joints.clear(); - skeletonData.joints.push_back(rootJointInfo); - for (int i = 0; i < childCount; ++i) { - JointInfo childJointInfo; - childJointInfo.parentIndex = i; - skeletonData.joints.push_back(childJointInfo); - - const float x = static_cast(i); - Qt3DCore::Sqt localPose; - localPose.translation = QVector3D(x, x, x); - skeletonData.localPoses.push_back(localPose); - - skeletonData.jointNames.push_back(QString("Child-%1").arg(i)); - } - - rootJoint = new QJoint(); - QJoint *previousJoint = rootJoint; - for (int i = 0; i < childCount; ++i) { - QJoint *childJoint = new QJoint(); - const float x = static_cast(i); - childJoint->setTranslation(QVector3D(x, x, x)); - previousJoint->addChildJoint(childJoint); - previousJoint = childJoint; - } - - QTest::newRow("deep") << skeletonData << rootJoint; - } }; QTEST_APPLESS_MAIN(tst_Skeleton) -- cgit v1.2.3 From 6303910dc48a87b84112f31c1dd328b930f7e957 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Fri, 11 Oct 2019 11:05:12 +0200 Subject: ComputeCommand/SubtreeEnabler use direct sync job to update frontend Change-Id: I773955df33f0b4dcdaa0953633761ff82f3d0da4 Reviewed-by: Mike Krus --- src/render/backend/computecommand.cpp | 24 ++++++++++----- src/render/backend/computecommand_p.h | 3 ++ src/render/framegraph/subtreeenabler.cpp | 18 ----------- src/render/renderers/opengl/renderer/renderer.cpp | 36 +++++++++++++--------- src/render/renderers/opengl/renderer/renderer_p.h | 6 ++-- .../renderers/opengl/renderer/renderview.cpp | 5 --- .../render/computecommand/tst_computecommand.cpp | 27 ++++++++++------ tests/auto/render/renderer/tst_renderer.cpp | 8 +++++ 8 files changed, 69 insertions(+), 58 deletions(-) diff --git a/src/render/backend/computecommand.cpp b/src/render/backend/computecommand.cpp index df79dcbe8..700769546 100644 --- a/src/render/backend/computecommand.cpp +++ b/src/render/backend/computecommand.cpp @@ -53,6 +53,7 @@ ComputeCommand::ComputeCommand() : BackendNode(ReadWrite) , m_frameCount(0) , m_runType(QComputeCommand::Continuous) + , m_hasReachedFrameCount(false) { m_workGroups[0] = 1; m_workGroups[1] = 1; @@ -71,6 +72,7 @@ void ComputeCommand::cleanup() m_workGroups[2] = 1; m_frameCount = 0; m_runType = QComputeCommand::Continuous; + m_hasReachedFrameCount = false; } void ComputeCommand::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) @@ -100,6 +102,7 @@ void ComputeCommand::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs const QComputeCommandPrivate *d = static_cast(Qt3DCore::QNodePrivate::get(node)); if (d->m_frameCount != m_frameCount) { m_frameCount = d->m_frameCount; + m_hasReachedFrameCount = m_frameCount <= 0; markDirty(AbstractRenderer::ComputeDirty); } @@ -112,14 +115,19 @@ void ComputeCommand::updateFrameCount() { // Disable frontend node when reaching 0 --m_frameCount; - if (m_frameCount <= 0) { - setEnabled(false); - auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(peerId()); - e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll); - e->setPropertyName("enabled"); - e->setValue(false); - notifyObservers(e); - } + if (m_frameCount <= 0) + m_hasReachedFrameCount = true; + // Backend will be disabled on the next sync +} + +void ComputeCommand::resetHasReachedFrameCount() +{ + m_hasReachedFrameCount = false; +} + +bool ComputeCommand::hasReachedFrameCount() const +{ + return m_hasReachedFrameCount; } } // Render diff --git a/src/render/backend/computecommand_p.h b/src/render/backend/computecommand_p.h index dc2069928..5012930ae 100644 --- a/src/render/backend/computecommand_p.h +++ b/src/render/backend/computecommand_p.h @@ -79,11 +79,14 @@ public: // Called from a job void updateFrameCount(); + bool hasReachedFrameCount() const; + void resetHasReachedFrameCount(); private: int m_workGroups[3]; int m_frameCount; QComputeCommand::RunType m_runType; + bool m_hasReachedFrameCount; }; } // Render diff --git a/src/render/framegraph/subtreeenabler.cpp b/src/render/framegraph/subtreeenabler.cpp index 160e1a5b5..4d912dc1d 100644 --- a/src/render/framegraph/subtreeenabler.cpp +++ b/src/render/framegraph/subtreeenabler.cpp @@ -52,30 +52,12 @@ SubtreeEnabler::SubtreeEnabler() { } -void SubtreeEnabler::sendDisableToFrontend() -{ - if (m_enablement != QSubtreeEnabler::SingleShot) - return; - - if (isEnabled()) - return; - - auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(peerId()); - e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll); - e->setPropertyName("enabled"); - e->setValue(false); - notifyObservers(e); -} - void SubtreeEnabler::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) { const QSubtreeEnabler *node = qobject_cast(frontEnd); if (!node) return; - if (node->isEnabled() != isEnabled()) - markDirty(AbstractRenderer::AllDirty); - FrameGraphNode::syncFromFrontEnd(frontEnd, firstTime); const auto enablement = node->enablement(); diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index 35c4d553f..474519398 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -200,7 +200,9 @@ Renderer::Renderer(QRenderAspect::RenderType type) [this] (Qt3DCore::QAspectManager *m) { sendTextureChangesToFrontend(m); }, JobTypes::SendTextureChangesToFrontend)) , m_sendSetFenceHandlesToFrontendJob(SynchronizerJobPtr::create([this] { sendSetFenceHandlesToFrontend(); }, JobTypes::SendSetFenceHandlesToFrontend)) - , m_sendDisablesToFrontendJob(SynchronizerJobPtr::create([this] { sendDisablesToFrontend(); }, JobTypes::SendDisablesToFrontend)) + , m_sendDisablesToFrontendJob(SynchronizerPostFramePtr::create([] {}, + [this] (Qt3DCore::QAspectManager *m) { sendDisablesToFrontend(m); }, + JobTypes::SendDisablesToFrontend)) , m_introspectShaderJob(SynchronizerPostFramePtr::create([this] { reloadDirtyShaders(); }, [this] (Qt3DCore::QAspectManager *m) { sendShaderChangesToFrontend(m); }, JobTypes::DirtyShaderGathering)) @@ -1231,17 +1233,24 @@ void Renderer::sendSetFenceHandlesToFrontend() } } -// Executed in a job -void Renderer::sendDisablesToFrontend() +// Executed in a job postFrame +void Renderer::sendDisablesToFrontend(Qt3DCore::QAspectManager *manager) { - const auto updatedDisables = std::move(m_updatedDisables); - FrameGraphManager *fgManager = m_nodesManager->frameGraphManager(); + // SubtreeEnabled + const auto updatedDisables = std::move(m_updatedDisableSubtreeEnablers); for (const auto &nodeId : updatedDisables) { - FrameGraphNode *fgNode = fgManager->lookupNode(nodeId); - if (fgNode != nullptr) { // Node could have been deleted before we got a chance to notify it - Q_ASSERT(fgNode->nodeType() == FrameGraphNode::SubtreeEnabler); - SubtreeEnabler *enabler = static_cast(fgNode); - enabler->sendDisableToFrontend(); + QSubtreeEnabler *frontend = static_cast(manager->lookupNode(nodeId)); + frontend->setEnabled(false); + } + + // Compute Commands + const QVector activeCommands = m_nodesManager->computeJobManager()->activeHandles(); + for (const HComputeCommand &handle :activeCommands) { + ComputeCommand *c = m_nodesManager->computeJobManager()->data(handle); + if (c->hasReachedFrameCount()) { + QComputeCommand *frontend = static_cast(manager->lookupNode(c->peerId())); + frontend->setEnabled(false); + c->resetHasReachedFrameCount(); } } } @@ -1773,7 +1782,6 @@ QVector Renderer::preRenderingJobs() QVector Renderer::renderBinJobs() { QVector renderBinJobs; - // Create the jobs to build the frame const QVector bufferJobs = createRenderBufferJobs(); @@ -1824,7 +1832,7 @@ QVector Renderer::renderBinJobs() renderBinJobs.push_back(m_updateSkinningPaletteJob); renderBinJobs.push_back(m_updateLevelOfDetailJob); renderBinJobs.push_back(m_cleanupJob); - + renderBinJobs.push_back(m_sendDisablesToFrontendJob); renderBinJobs.append(bufferJobs); // Jobs to prepare GL Resource upload @@ -1874,9 +1882,7 @@ QVector Renderer::renderBinJobs() // Handle single shot subtree enablers const auto subtreeEnablers = visitor.takeEnablersToDisable(); for (auto *node : subtreeEnablers) - m_updatedDisables.push_back(node->peerId()); - if (m_updatedDisables.size() > 0) - renderBinJobs.push_back(m_sendDisablesToFrontendJob); + m_updatedDisableSubtreeEnablers.push_back(node->peerId()); } const int fgBranchCount = m_frameGraphLeaves.size(); diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index 7b1349503..f007ab05c 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -383,7 +383,7 @@ private: SynchronizerJobPtr m_textureGathererJob; SynchronizerPostFramePtr m_sendTextureChangesToFrontendJob; SynchronizerJobPtr m_sendSetFenceHandlesToFrontendJob; - SynchronizerJobPtr m_sendDisablesToFrontendJob; + SynchronizerPostFramePtr m_sendDisablesToFrontendJob; SynchronizerPostFramePtr m_introspectShaderJob; SynchronizerJobPtr m_syncLoadingJobs; @@ -395,7 +395,7 @@ private: void sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager); void sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager); void sendSetFenceHandlesToFrontend(); - void sendDisablesToFrontend(); + void sendDisablesToFrontend(Qt3DCore::QAspectManager *manager); QMutex m_abandonedVaosMutex; QVector m_abandonedVaos; @@ -406,7 +406,7 @@ private: QVector m_dirtyTextures; QVector> m_updatedTextureProperties; QVector> m_updatedSetFences; - QVector m_updatedDisables; + QVector m_updatedDisableSubtreeEnablers; Qt3DCore::QNodeIdVector m_textureIdsToCleanup; QVector m_shaderBuilderUpdates; diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp index c38ffae80..7fb1c5fb9 100644 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ b/src/render/renderers/opengl/renderer/renderview.cpp @@ -686,11 +686,6 @@ QVector RenderView::buildComputeRenderCommands(const QV if ((computeJob = nodeManagers()->computeJobManager()->data(computeCommandHandle)) != nullptr && computeJob->isEnabled()) { - // Note: if frameCount has reached 0 in the previous frame, isEnabled - // would be false - if (computeJob->runType() == QComputeCommand::Manual) - computeJob->updateFrameCount(); - const Qt3DCore::QNodeId materialComponentId = entity->componentUuid(); const QVector renderPassData = m_parameters.value(materialComponentId); diff --git a/tests/auto/render/computecommand/tst_computecommand.cpp b/tests/auto/render/computecommand/tst_computecommand.cpp index 990c0cd98..4120153e7 100644 --- a/tests/auto/render/computecommand/tst_computecommand.cpp +++ b/tests/auto/render/computecommand/tst_computecommand.cpp @@ -54,6 +54,7 @@ private Q_SLOTS: QCOMPARE(backendComputeCommand.x(), 1); QCOMPARE(backendComputeCommand.y(), 1); QCOMPARE(backendComputeCommand.z(), 1); + QCOMPARE(backendComputeCommand.hasReachedFrameCount(), false); QCOMPARE(backendComputeCommand.runType(), Qt3DRender::QComputeCommand::Continuous); QCOMPARE(backendComputeCommand.frameCount(), 0); } @@ -61,15 +62,27 @@ private Q_SLOTS: void checkCleanupState() { // GIVEN + TestRenderer renderer; Qt3DRender::Render::ComputeCommand backendComputeCommand; + Qt3DRender::QComputeCommand computeCommand; + computeCommand.setWorkGroupX(256); + computeCommand.setWorkGroupY(512); + computeCommand.setWorkGroupZ(128); + computeCommand.setRunType(Qt3DRender::QComputeCommand::Manual); + computeCommand.trigger(1); // WHEN + backendComputeCommand.setRenderer(&renderer); + simulateInitializationSync(&computeCommand, &backendComputeCommand); + backendComputeCommand.setEnabled(true); + backendComputeCommand.hasReachedFrameCount(); backendComputeCommand.cleanup(); // THEN QCOMPARE(backendComputeCommand.isEnabled(), false); + QCOMPARE(backendComputeCommand.hasReachedFrameCount(), false); } void checkInitializeFromPeer() @@ -207,6 +220,7 @@ private Q_SLOTS: // THEN QCOMPARE(backendComputeCommand.frameCount(), 6 - (i + 1)); QCOMPARE(backendComputeCommand.isEnabled(), true); + QCOMPARE(backendComputeCommand.hasReachedFrameCount(), false); QCOMPARE(arbiter.events.size(), 0); } @@ -214,15 +228,10 @@ private Q_SLOTS: backendComputeCommand.updateFrameCount(); // THEN - QCOMPARE(backendComputeCommand.frameCount(), false); - QCOMPARE(backendComputeCommand.isEnabled(), false); - QCOMPARE(arbiter.events.size(), 1); - { - auto change = arbiter.events.first().staticCast(); - QCOMPARE(change->propertyName(), "enabled"); - QCOMPARE(change->value().value(), false); - QCOMPARE(change->type(), Qt3DCore::PropertyUpdated); - } + QCOMPARE(backendComputeCommand.hasReachedFrameCount(), true); + QCOMPARE(backendComputeCommand.frameCount(), 0); + // Backend stays with enabled == true, frontend will be updated + // to be disabled and backend should be disabled on the next sync } }; diff --git a/tests/auto/render/renderer/tst_renderer.cpp b/tests/auto/render/renderer/tst_renderer.cpp index f8125bce4..91cb7906c 100644 --- a/tests/auto/render/renderer/tst_renderer.cpp +++ b/tests/auto/render/renderer/tst_renderer.cpp @@ -192,6 +192,7 @@ private Q_SLOTS: 1 + // SyncLoadingJobs 1 + // updateLevelOfDetailJob 1 + // cleanupJob + 1 + // sendDisablesToFrontend 1 + // VAOGatherer 1 + // BufferGathererJob 1 + // TexturesGathererJob @@ -221,6 +222,7 @@ private Q_SLOTS: 1 + // VAOGatherer 1 + // updateSkinningPaletteJob 1 + // SyncLoadingJobs + 1 + // sendDisablesToFrontend singleRenderViewJobCount + singleRenderViewCommandRebuildJobCount + renderViewBuilderMaterialCacheJobCount + @@ -240,6 +242,7 @@ private Q_SLOTS: 1 + // VAOGatherer 1 + // updateSkinningPaletteJob 1 + // SyncLoadingJobs + 1 + // sendDisablesToFrontend 1 + // EntityEnabledDirty singleRenderViewJobCount + layerCacheJobCount); @@ -261,6 +264,7 @@ private Q_SLOTS: 1 + // UpdateShaderDataTransform 1 + // updateSkinningPaletteJob 1 + // SyncLoadingJobs + 1 + // sendDisablesToFrontend 1 + // ExpandBoundingVolumeJob singleRenderViewJobCount); @@ -278,6 +282,7 @@ private Q_SLOTS: 1 + // VAOGatherer 1 + // updateSkinningPaletteJob 1 + // SyncLoadingJobs + 1 + // sendDisablesToFrontend singleRenderViewJobCount + singleRenderViewCommandRebuildJobCount + renderViewBuilderMaterialCacheJobCount); @@ -301,6 +306,7 @@ private Q_SLOTS: 1 + // ExpandBoundingVolumeJob 1 + // RenderableEntityFilterPtr 1 + // SyncRenderableEntities + 1 + // sendDisablesToFrontend singleRenderViewCommandRebuildJobCount + singleRenderViewJobCount); @@ -321,6 +327,7 @@ private Q_SLOTS: 1 + // CalculateBoundingVolumeJob 1 + // UpdateMeshTriangleListJob 1 + // BufferGathererJob + 1 + // sendDisablesToFrontend singleRenderViewJobCount); renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); @@ -338,6 +345,7 @@ private Q_SLOTS: 1 + // TexturesGathererJob 1 + // updateSkinningPaletteJob 1 + // SyncTexturesGathererJob + 1 + // sendDisablesToFrontend singleRenderViewJobCount); renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); -- cgit v1.2.3 From 6035dc924ba1d6456307371e197130b496e603ab Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Tue, 22 Oct 2019 07:17:08 +0200 Subject: Restore sceneChangeEvent overload that were removed Not BIC compatible so they must stay until Qt6. Added TODO above them to make it easier to track for Qt6. Change-Id: Ia1adba25be5d55d3fa836727877c7c1f7346b668 Reviewed-by: Mike Krus --- src/animation/frontend/qabstractanimationclip.cpp | 5 +++++ src/animation/frontend/qabstractanimationclip.h | 3 ++- src/animation/frontend/qabstractclipanimator.cpp | 5 +++++ src/animation/frontend/qabstractclipanimator.h | 2 ++ src/animation/frontend/qanimationcliploader.cpp | 5 +++++ src/animation/frontend/qanimationcliploader.h | 2 ++ src/core/transforms/qtransform.cpp | 1 + src/core/transforms/qtransform.h | 1 + src/input/frontend/qaction.cpp | 5 +++++ src/input/frontend/qaction.h | 4 ++++ src/input/frontend/qaxis.cpp | 5 +++++ src/input/frontend/qaxis.h | 4 ++++ src/input/frontend/qaxisaccumulator.cpp | 5 +++++ src/input/frontend/qaxisaccumulator.h | 4 ++++ src/input/frontend/qkeyboarddevice.cpp | 5 +++++ src/input/frontend/qkeyboarddevice.h | 2 ++ src/input/frontend/qkeyboardhandler.cpp | 5 +++++ src/input/frontend/qkeyboardhandler.h | 4 ++++ src/input/frontend/qmousehandler.cpp | 5 +++++ src/input/frontend/qmousehandler.h | 2 ++ src/render/frontend/qlevelofdetail.cpp | 5 +++++ src/render/frontend/qlevelofdetail.h | 2 ++ src/render/frontend/qlevelofdetailswitch.cpp | 5 +++++ src/render/frontend/qlevelofdetailswitch.h | 2 ++ src/render/geometry/qgeometryrenderer.cpp | 5 +++++ src/render/geometry/qgeometryrenderer.h | 2 ++ src/render/geometry/qmesh.cpp | 5 +++++ src/render/geometry/qmesh.h | 2 ++ src/render/io/qsceneloader.cpp | 5 +++++ src/render/io/qsceneloader.h | 2 ++ src/render/materialsystem/qshaderprogrambuilder.cpp | 5 +++++ src/render/materialsystem/qshaderprogrambuilder.h | 2 ++ src/render/picking/qobjectpicker.cpp | 5 +++++ src/render/picking/qobjectpicker.h | 4 ++++ 34 files changed, 124 insertions(+), 1 deletion(-) diff --git a/src/animation/frontend/qabstractanimationclip.cpp b/src/animation/frontend/qabstractanimationclip.cpp index cd1cce464..53ae46809 100644 --- a/src/animation/frontend/qabstractanimationclip.cpp +++ b/src/animation/frontend/qabstractanimationclip.cpp @@ -133,6 +133,11 @@ QAbstractAnimationClip::QAbstractAnimationClip(QAbstractAnimationClipPrivate &dd { } +// TODO Unused remove in Qt6 +void QAbstractAnimationClip::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + /*! Destroys this animation clip. */ diff --git a/src/animation/frontend/qabstractanimationclip.h b/src/animation/frontend/qabstractanimationclip.h index f68950c4c..fddee3dec 100644 --- a/src/animation/frontend/qabstractanimationclip.h +++ b/src/animation/frontend/qabstractanimationclip.h @@ -62,7 +62,8 @@ Q_SIGNALS: protected: QAbstractAnimationClip(QAbstractAnimationClipPrivate &dd, Qt3DCore::QNode *parent = nullptr); - + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QAbstractAnimationClip) }; diff --git a/src/animation/frontend/qabstractclipanimator.cpp b/src/animation/frontend/qabstractclipanimator.cpp index cb4621182..8c282da49 100644 --- a/src/animation/frontend/qabstractclipanimator.cpp +++ b/src/animation/frontend/qabstractclipanimator.cpp @@ -122,6 +122,11 @@ QAbstractClipAnimator::QAbstractClipAnimator(QAbstractClipAnimatorPrivate &dd, Q { } +// TODO Unused remove in Qt6 +void QAbstractClipAnimator::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + QAbstractClipAnimator::~QAbstractClipAnimator() { } diff --git a/src/animation/frontend/qabstractclipanimator.h b/src/animation/frontend/qabstractclipanimator.h index 687589b5e..dc9dc9077 100644 --- a/src/animation/frontend/qabstractclipanimator.h +++ b/src/animation/frontend/qabstractclipanimator.h @@ -94,6 +94,8 @@ protected: explicit QAbstractClipAnimator(Qt3DCore::QNode *parent = nullptr); QAbstractClipAnimator(QAbstractClipAnimatorPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QAbstractClipAnimator) }; diff --git a/src/animation/frontend/qanimationcliploader.cpp b/src/animation/frontend/qanimationcliploader.cpp index d3b2b5bf4..bf901e54f 100644 --- a/src/animation/frontend/qanimationcliploader.cpp +++ b/src/animation/frontend/qanimationcliploader.cpp @@ -112,6 +112,11 @@ QAnimationClipLoader::QAnimationClipLoader(QAnimationClipLoaderPrivate &dd, Qt3D { } +// TODO Unused remove in Qt6 +void QAnimationClipLoader::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + QAnimationClipLoader::~QAnimationClipLoader() { } diff --git a/src/animation/frontend/qanimationcliploader.h b/src/animation/frontend/qanimationcliploader.h index 1ff388297..1b68e852f 100644 --- a/src/animation/frontend/qanimationcliploader.h +++ b/src/animation/frontend/qanimationcliploader.h @@ -78,6 +78,8 @@ Q_SIGNALS: protected: explicit QAnimationClipLoader(QAnimationClipLoaderPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QAnimationClipLoader) diff --git a/src/core/transforms/qtransform.cpp b/src/core/transforms/qtransform.cpp index e5902f11f..d41b87f79 100644 --- a/src/core/transforms/qtransform.cpp +++ b/src/core/transforms/qtransform.cpp @@ -237,6 +237,7 @@ QTransform::QTransform(QTransformPrivate &dd, QNode *parent) /*! \internal */ +// TODO Unused remove in Qt6 void QTransform::sceneChangeEvent(const QSceneChangePtr &change) { Q_D(QTransform); diff --git a/src/core/transforms/qtransform.h b/src/core/transforms/qtransform.h index 503ea4d4a..ce6bf42fa 100644 --- a/src/core/transforms/qtransform.h +++ b/src/core/transforms/qtransform.h @@ -119,6 +119,7 @@ Q_SIGNALS: protected: explicit QTransform(QTransformPrivate &dd, QNode *parent = nullptr); + // TODO Unused remove in Qt6 void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: diff --git a/src/input/frontend/qaction.cpp b/src/input/frontend/qaction.cpp index 512a5aca7..8cceaab51 100644 --- a/src/input/frontend/qaction.cpp +++ b/src/input/frontend/qaction.cpp @@ -148,6 +148,11 @@ QVector QAction::inputs() const return d->m_inputs; } +// TODO Unused remove in Qt6 +void QAction::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + Qt3DCore::QNodeCreatedChangeBasePtr QAction::createNodeCreationChange() const { auto creationChange = Qt3DCore::QNodeCreatedChangePtr::create(this); diff --git a/src/input/frontend/qaction.h b/src/input/frontend/qaction.h index 8175bab8e..ef74debe5 100644 --- a/src/input/frontend/qaction.h +++ b/src/input/frontend/qaction.h @@ -67,6 +67,10 @@ public: Q_SIGNALS: void activeChanged(bool isActive); +protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; + private: Q_DECLARE_PRIVATE(QAction) Qt3DCore::QNodeCreatedChangeBasePtr createNodeCreationChange() const override; diff --git a/src/input/frontend/qaxis.cpp b/src/input/frontend/qaxis.cpp index 7faa6a459..d76135fd7 100644 --- a/src/input/frontend/qaxis.cpp +++ b/src/input/frontend/qaxis.cpp @@ -167,6 +167,11 @@ float QAxis::value() const return d->m_value; } +// TODO Unused remove in Qt6 +void QAxis::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + Qt3DCore::QNodeCreatedChangeBasePtr QAxis::createNodeCreationChange() const { auto creationChange = Qt3DCore::QNodeCreatedChangePtr::create(this); diff --git a/src/input/frontend/qaxis.h b/src/input/frontend/qaxis.h index 1a542cf22..3dbe54a4f 100644 --- a/src/input/frontend/qaxis.h +++ b/src/input/frontend/qaxis.h @@ -66,6 +66,10 @@ public: Q_SIGNALS: void valueChanged(float value); +protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; + private: Q_DECLARE_PRIVATE(QAxis) Qt3DCore::QNodeCreatedChangeBasePtr createNodeCreationChange() const override; diff --git a/src/input/frontend/qaxisaccumulator.cpp b/src/input/frontend/qaxisaccumulator.cpp index 03f6e3bd1..a7bb14441 100644 --- a/src/input/frontend/qaxisaccumulator.cpp +++ b/src/input/frontend/qaxisaccumulator.cpp @@ -289,6 +289,11 @@ void QAxisAccumulator::setScale(float scale) emit scaleChanged(scale); } +// TODO Unused remove in Qt6 +void QAxisAccumulator::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + /*! \internal */ Qt3DCore::QNodeCreatedChangeBasePtr QAxisAccumulator::createNodeCreationChange() const { diff --git a/src/input/frontend/qaxisaccumulator.h b/src/input/frontend/qaxisaccumulator.h index bb2e2696b..e711b0691 100644 --- a/src/input/frontend/qaxisaccumulator.h +++ b/src/input/frontend/qaxisaccumulator.h @@ -87,6 +87,10 @@ Q_SIGNALS: void velocityChanged(float value); void scaleChanged(float scale); +protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; + private: Q_DECLARE_PRIVATE(QAxisAccumulator) Qt3DCore::QNodeCreatedChangeBasePtr createNodeCreationChange() const override; diff --git a/src/input/frontend/qkeyboarddevice.cpp b/src/input/frontend/qkeyboarddevice.cpp index 0fe3a1338..1ec1f8ead 100644 --- a/src/input/frontend/qkeyboarddevice.cpp +++ b/src/input/frontend/qkeyboarddevice.cpp @@ -309,6 +309,11 @@ QKeyboardDevice::QKeyboardDevice(QKeyboardDevicePrivate &dd, QNode *parent) { } +// TODO Unused remove in Qt6 +void QKeyboardDevice::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + /*! * Set the active input to \a activeInput */ diff --git a/src/input/frontend/qkeyboarddevice.h b/src/input/frontend/qkeyboarddevice.h index ee4b864f7..df2f47020 100644 --- a/src/input/frontend/qkeyboarddevice.h +++ b/src/input/frontend/qkeyboarddevice.h @@ -71,6 +71,8 @@ public: protected: explicit QKeyboardDevice(QKeyboardDevicePrivate &dd, QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; Q_SIGNALS: void activeInputChanged(QKeyboardHandler *activeInput); diff --git a/src/input/frontend/qkeyboardhandler.cpp b/src/input/frontend/qkeyboardhandler.cpp index 1581f763c..92ce39c31 100644 --- a/src/input/frontend/qkeyboardhandler.cpp +++ b/src/input/frontend/qkeyboardhandler.cpp @@ -237,6 +237,11 @@ void QKeyboardHandler::setFocus(bool focus) } } +// TODO Unused remove in Qt6 +void QKeyboardHandler::sceneChangeEvent(const QSceneChangePtr &) +{ +} + Qt3DCore::QNodeCreatedChangeBasePtr QKeyboardHandler::createNodeCreationChange() const { auto creationChange = Qt3DCore::QNodeCreatedChangePtr::create(this); diff --git a/src/input/frontend/qkeyboardhandler.h b/src/input/frontend/qkeyboardhandler.h index d69476286..b4425de72 100644 --- a/src/input/frontend/qkeyboardhandler.h +++ b/src/input/frontend/qkeyboardhandler.h @@ -115,6 +115,10 @@ Q_SIGNALS: void pressed(Qt3DInput::QKeyEvent *event); void released(Qt3DInput::QKeyEvent *event); +protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; + private: Q_DECLARE_PRIVATE(QKeyboardHandler) Qt3DCore::QNodeCreatedChangeBasePtr createNodeCreationChange() const override; diff --git a/src/input/frontend/qmousehandler.cpp b/src/input/frontend/qmousehandler.cpp index f3e7a18c8..1d45d85b6 100644 --- a/src/input/frontend/qmousehandler.cpp +++ b/src/input/frontend/qmousehandler.cpp @@ -298,6 +298,11 @@ void QMouseHandler::setSourceDevice(QMouseDevice *mouseDevice) } } +// TODO Unused remove in Qt6 +void QMouseHandler::sceneChangeEvent(const QSceneChangePtr &) +{ +} + /*! * \property Qt3DInput::QMouseHandler::sourceDevice * diff --git a/src/input/frontend/qmousehandler.h b/src/input/frontend/qmousehandler.h index 5331893b2..d95dbf4c3 100644 --- a/src/input/frontend/qmousehandler.h +++ b/src/input/frontend/qmousehandler.h @@ -87,6 +87,8 @@ Q_SIGNALS: #endif protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; void setContainsMouse(bool contains); private: diff --git a/src/render/frontend/qlevelofdetail.cpp b/src/render/frontend/qlevelofdetail.cpp index 3d0cb9553..ced0604c7 100644 --- a/src/render/frontend/qlevelofdetail.cpp +++ b/src/render/frontend/qlevelofdetail.cpp @@ -325,6 +325,11 @@ Qt3DCore::QNodeCreatedChangeBasePtr QLevelOfDetail::createNodeCreationChange() c return creationChange; } +// TODO Unused remove in Qt6 +void QLevelOfDetail::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + QCamera *QLevelOfDetail::camera() const { Q_D(const QLevelOfDetail); diff --git a/src/render/frontend/qlevelofdetail.h b/src/render/frontend/qlevelofdetail.h index f6c09a287..81fcf3235 100644 --- a/src/render/frontend/qlevelofdetail.h +++ b/src/render/frontend/qlevelofdetail.h @@ -97,6 +97,8 @@ Q_SIGNALS: protected: explicit QLevelOfDetail(QLevelOfDetailPrivate &dd, Qt3DCore::QNode *parent = nullptr); Qt3DCore::QNodeCreatedChangeBasePtr createNodeCreationChange() const override; + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QLevelOfDetail) diff --git a/src/render/frontend/qlevelofdetailswitch.cpp b/src/render/frontend/qlevelofdetailswitch.cpp index c0bbdc0f8..c07d4c4b1 100644 --- a/src/render/frontend/qlevelofdetailswitch.cpp +++ b/src/render/frontend/qlevelofdetailswitch.cpp @@ -133,6 +133,11 @@ QLevelOfDetailSwitch::QLevelOfDetailSwitch(QLevelOfDetailPrivate &dd, QNode *par { } +// TODO Unused remove in Qt6 +void QLevelOfDetailSwitch::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + } // namespace Qt3DRender QT_END_NAMESPACE diff --git a/src/render/frontend/qlevelofdetailswitch.h b/src/render/frontend/qlevelofdetailswitch.h index 90f4ee3e2..325b885ed 100644 --- a/src/render/frontend/qlevelofdetailswitch.h +++ b/src/render/frontend/qlevelofdetailswitch.h @@ -57,6 +57,8 @@ public: protected: explicit QLevelOfDetailSwitch(QLevelOfDetailPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QLevelOfDetailSwitch) diff --git a/src/render/geometry/qgeometryrenderer.cpp b/src/render/geometry/qgeometryrenderer.cpp index 6e0a24f61..64f3e058e 100644 --- a/src/render/geometry/qgeometryrenderer.cpp +++ b/src/render/geometry/qgeometryrenderer.cpp @@ -218,6 +218,11 @@ QGeometryRenderer::QGeometryRenderer(QGeometryRendererPrivate &dd, QNode *parent { } +// TODO Unused remove in Qt6 +void QGeometryRenderer::sceneChangeEvent(const QSceneChangePtr &) +{ +} + /*! \property QGeometryRenderer::instanceCount diff --git a/src/render/geometry/qgeometryrenderer.h b/src/render/geometry/qgeometryrenderer.h index eceeb9173..14de40d0b 100644 --- a/src/render/geometry/qgeometryrenderer.h +++ b/src/render/geometry/qgeometryrenderer.h @@ -134,6 +134,8 @@ Q_SIGNALS: protected: explicit QGeometryRenderer(QGeometryRendererPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QGeometryRenderer) diff --git a/src/render/geometry/qmesh.cpp b/src/render/geometry/qmesh.cpp index 1d7d33f9a..f5307f7a9 100644 --- a/src/render/geometry/qmesh.cpp +++ b/src/render/geometry/qmesh.cpp @@ -215,6 +215,11 @@ QMesh::QMesh(QMeshPrivate &dd, QNode *parent) { } +// TODO Unused remove in Qt6 +void QMesh::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + void QMesh::setSource(const QUrl& source) { Q_D(QMesh); diff --git a/src/render/geometry/qmesh.h b/src/render/geometry/qmesh.h index 04fdedc20..e8ff52b35 100644 --- a/src/render/geometry/qmesh.h +++ b/src/render/geometry/qmesh.h @@ -88,6 +88,8 @@ Q_SIGNALS: protected: explicit QMesh(QMeshPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QMesh) diff --git a/src/render/io/qsceneloader.cpp b/src/render/io/qsceneloader.cpp index 1b6a56e36..7d4413bff 100644 --- a/src/render/io/qsceneloader.cpp +++ b/src/render/io/qsceneloader.cpp @@ -252,6 +252,11 @@ QSceneLoader::~QSceneLoader() { } +// TODO Unused remove in Qt6 +void QSceneLoader::sceneChangeEvent(const QSceneChangePtr &) +{ +} + /*! \internal */ QSceneLoader::QSceneLoader(QSceneLoaderPrivate &dd, QNode *parent) : Qt3DCore::QComponent(dd, parent) diff --git a/src/render/io/qsceneloader.h b/src/render/io/qsceneloader.h index 6842a6926..51ba42de7 100644 --- a/src/render/io/qsceneloader.h +++ b/src/render/io/qsceneloader.h @@ -60,6 +60,8 @@ public: explicit QSceneLoader(Qt3DCore::QNode *parent = nullptr); ~QSceneLoader(); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; enum Status { None = 0, Loading, diff --git a/src/render/materialsystem/qshaderprogrambuilder.cpp b/src/render/materialsystem/qshaderprogrambuilder.cpp index 6613661d1..7f98fbf5e 100644 --- a/src/render/materialsystem/qshaderprogrambuilder.cpp +++ b/src/render/materialsystem/qshaderprogrambuilder.cpp @@ -135,6 +135,11 @@ QShaderProgramBuilder::QShaderProgramBuilder(QShaderProgramBuilderPrivate &dd, Q { } +// TODO Unused remove in Qt6 +void QShaderProgramBuilder::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + /*! \qmlproperty string ShaderProgramBuilder::shaderProgram diff --git a/src/render/materialsystem/qshaderprogrambuilder.h b/src/render/materialsystem/qshaderprogrambuilder.h index 5dc6b54ff..48e189c8c 100644 --- a/src/render/materialsystem/qshaderprogrambuilder.h +++ b/src/render/materialsystem/qshaderprogrambuilder.h @@ -117,6 +117,8 @@ Q_SIGNALS: protected: explicit QShaderProgramBuilder(QShaderProgramBuilderPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QShaderProgramBuilder) diff --git a/src/render/picking/qobjectpicker.cpp b/src/render/picking/qobjectpicker.cpp index 7d9741f21..b7f2c0815 100644 --- a/src/render/picking/qobjectpicker.cpp +++ b/src/render/picking/qobjectpicker.cpp @@ -292,6 +292,11 @@ void QObjectPicker::setPriority(int priority) } } +// TODO Unused remove in Qt6 +void QObjectPicker::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &) +{ +} + /*! \qmlproperty bool Qt3D.Render::ObjectPicker::dragEnabled */ diff --git a/src/render/picking/qobjectpicker.h b/src/render/picking/qobjectpicker.h index ee63c9418..ea65040ba 100644 --- a/src/render/picking/qobjectpicker.h +++ b/src/render/picking/qobjectpicker.h @@ -77,6 +77,10 @@ public Q_SLOTS: void setDragEnabled(bool dragEnabled); Q_REVISION(13) void setPriority(int priority); +protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; + Q_SIGNALS: void pressed(Qt3DRender::QPickEvent *pick); void released(Qt3DRender::QPickEvent *pick); -- cgit v1.2.3 From c795ccb968da8a7d1ac766553c14df943e4f8fb4 Mon Sep 17 00:00:00 2001 From: Kai Koehne Date: Tue, 24 Sep 2019 12:44:38 +0200 Subject: Update plugins.qmltypes for 5.14 Task-number: QTBUG-78690 Change-Id: I0c12b4f404aa24b7d2587c63be7c88eb5ca99327 Reviewed-by: Paul Lemire --- src/quick3d/imports/animation/plugins.qmltypes | 55 +++++- src/quick3d/imports/core/plugins.qmltypes | 73 ++++++- src/quick3d/imports/extras/plugins.qmltypes | 55 +++++- src/quick3d/imports/input/plugins.qmltypes | 2 +- src/quick3d/imports/logic/plugins.qmltypes | 2 +- src/quick3d/imports/render/plugins.qmltypes | 255 ++++++++++++++++++++++++- src/quick3d/imports/scene2d/plugins.qmltypes | 2 +- src/quick3d/imports/scene3d/plugins.qmltypes | 38 +++- 8 files changed, 463 insertions(+), 19 deletions(-) diff --git a/src/quick3d/imports/animation/plugins.qmltypes b/src/quick3d/imports/animation/plugins.qmltypes index a8f207245..aff5ccb9c 100644 --- a/src/quick3d/imports/animation/plugins.qmltypes +++ b/src/quick3d/imports/animation/plugins.qmltypes @@ -4,7 +4,7 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Animation 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Animation 2.14' Module { dependencies: ["Qt3D.Core 2.0"] @@ -699,4 +699,57 @@ Module { isReadonly: true } } + Component { + name: "Qt3DCore::QNode" + defaultProperty: "data" + prototype: "QObject" + exports: ["Qt3D.Animation/Node 2.9"] + isCreatable: false + exportMetaObjectRevisions: [209] + Enum { + name: "PropertyTrackingMode" + values: { + "TrackFinalValues": 0, + "DontTrackValues": 1, + "TrackAllValues": 2 + } + } + Property { name: "parent"; type: "Qt3DCore::QNode"; isPointer: true } + Property { name: "enabled"; type: "bool" } + Property { name: "defaultPropertyTrackingMode"; revision: 9; type: "PropertyTrackingMode" } + Signal { + name: "parentChanged" + Parameter { name: "parent"; type: "QObject"; isPointer: true } + } + Signal { + name: "enabledChanged" + Parameter { name: "enabled"; type: "bool" } + } + Signal { + name: "defaultPropertyTrackingModeChanged" + Parameter { name: "mode"; type: "PropertyTrackingMode" } + } + Signal { name: "nodeDestroyed" } + Method { + name: "setParent" + Parameter { name: "parent"; type: "QNode"; isPointer: true } + } + Method { + name: "setEnabled" + Parameter { name: "isEnabled"; type: "bool" } + } + Method { + name: "setDefaultPropertyTrackingMode" + Parameter { name: "mode"; type: "PropertyTrackingMode" } + } + Property { name: "propertyTrackingOverrides"; revision: 209; type: "QJSValue" } + Property { name: "data"; revision: 209; type: "QObject"; isList: true; isReadonly: true } + Property { + name: "childNodes" + revision: 209 + type: "Qt3DCore::QNode" + isList: true + isReadonly: true + } + } } diff --git a/src/quick3d/imports/core/plugins.qmltypes b/src/quick3d/imports/core/plugins.qmltypes index 390fd78fb..476bb99a7 100644 --- a/src/quick3d/imports/core/plugins.qmltypes +++ b/src/quick3d/imports/core/plugins.qmltypes @@ -4,10 +4,72 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable Qt3D.Core 2.13' +// 'qmlplugindump -nonrelocatable Qt3D.Core 2.14' Module { dependencies: ["QtQuick 2.0"] + Component { + name: "QQmlEasingValueType" + exports: ["Qt3D.Core/Easing 2.0"] + isCreatable: false + exportMetaObjectRevisions: [0] + Enum { + name: "Type" + values: { + "Linear": 0, + "InQuad": 1, + "OutQuad": 2, + "InOutQuad": 3, + "OutInQuad": 4, + "InCubic": 5, + "OutCubic": 6, + "InOutCubic": 7, + "OutInCubic": 8, + "InQuart": 9, + "OutQuart": 10, + "InOutQuart": 11, + "OutInQuart": 12, + "InQuint": 13, + "OutQuint": 14, + "InOutQuint": 15, + "OutInQuint": 16, + "InSine": 17, + "OutSine": 18, + "InOutSine": 19, + "OutInSine": 20, + "InExpo": 21, + "OutExpo": 22, + "InOutExpo": 23, + "OutInExpo": 24, + "InCirc": 25, + "OutCirc": 26, + "InOutCirc": 27, + "OutInCirc": 28, + "InElastic": 29, + "OutElastic": 30, + "InOutElastic": 31, + "OutInElastic": 32, + "InBack": 33, + "OutBack": 34, + "InOutBack": 35, + "OutInBack": 36, + "InBounce": 37, + "OutBounce": 38, + "InOutBounce": 39, + "OutInBounce": 40, + "InCurve": 41, + "OutCurve": 42, + "SineCurve": 43, + "CosineCurve": 44, + "Bezier": 45 + } + } + Property { name: "type"; type: "Type" } + Property { name: "amplitude"; type: "double" } + Property { name: "overshoot"; type: "double" } + Property { name: "period"; type: "double" } + Property { name: "bezierCurve"; type: "QVariantList" } + } Component { name: "Qt3DCore::QAbstractSkeleton" prototype: "Qt3DCore::QNode" @@ -266,8 +328,8 @@ Module { Component { name: "Qt3DCore::QTransform" prototype: "Qt3DCore::QComponent" - exports: ["Qt3D.Core/Transform 2.0"] - exportMetaObjectRevisions: [0] + exports: ["Qt3D.Core/Transform 2.0", "Qt3D.Core/Transform 2.14"] + exportMetaObjectRevisions: [0, 14] Property { name: "matrix"; type: "QMatrix4x4" } Property { name: "scale"; type: "float" } Property { name: "scale3D"; type: "QVector3D" } @@ -276,6 +338,7 @@ Module { Property { name: "rotationX"; type: "float" } Property { name: "rotationY"; type: "float" } Property { name: "rotationZ"; type: "float" } + Property { name: "worldMatrix"; revision: 14; type: "QMatrix4x4"; isReadonly: true } Signal { name: "scaleChanged" Parameter { name: "scale"; type: "float" } @@ -304,6 +367,10 @@ Module { name: "rotationZChanged" Parameter { name: "rotationZ"; type: "float" } } + Signal { + name: "worldMatrixChanged" + Parameter { name: "worldMatrix"; type: "QMatrix4x4" } + } Method { name: "setScale" Parameter { name: "scale"; type: "float" } diff --git a/src/quick3d/imports/extras/plugins.qmltypes b/src/quick3d/imports/extras/plugins.qmltypes index 72857d402..fcc15e022 100644 --- a/src/quick3d/imports/extras/plugins.qmltypes +++ b/src/quick3d/imports/extras/plugins.qmltypes @@ -4,10 +4,51 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Extras 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Extras 2.14' Module { dependencies: ["Qt3D.Logic 2.0", "Qt3D.Render 2.0"] + Component { name: "Qt3DCore::QEntity"; prototype: "Qt3DCore::QNode" } + Component { + name: "Qt3DCore::QNode" + prototype: "QObject" + Enum { + name: "PropertyTrackingMode" + values: { + "TrackFinalValues": 0, + "DontTrackValues": 1, + "TrackAllValues": 2 + } + } + Property { name: "parent"; type: "Qt3DCore::QNode"; isPointer: true } + Property { name: "enabled"; type: "bool" } + Property { name: "defaultPropertyTrackingMode"; revision: 9; type: "PropertyTrackingMode" } + Signal { + name: "parentChanged" + Parameter { name: "parent"; type: "QObject"; isPointer: true } + } + Signal { + name: "enabledChanged" + Parameter { name: "enabled"; type: "bool" } + } + Signal { + name: "defaultPropertyTrackingModeChanged" + Parameter { name: "mode"; type: "PropertyTrackingMode" } + } + Signal { name: "nodeDestroyed" } + Method { + name: "setParent" + Parameter { name: "parent"; type: "QNode"; isPointer: true } + } + Method { + name: "setEnabled" + Parameter { name: "isEnabled"; type: "bool" } + } + Method { + name: "setDefaultPropertyTrackingMode" + Parameter { name: "mode"; type: "PropertyTrackingMode" } + } + } Component { name: "Qt3DExtras::Extras::Quick::Quick3DLevelOfDetailLoader" prototype: "Qt3DCore::QEntity" @@ -758,13 +799,15 @@ Module { prototype: "Qt3DRender::QTechniqueFilter" exports: [ "Qt3D.Extras/ForwardRenderer 2.0", + "Qt3D.Extras/ForwardRenderer 2.14", "Qt3D.Extras/ForwardRenderer 2.9" ] - exportMetaObjectRevisions: [0, 9] + exportMetaObjectRevisions: [0, 14, 9] Property { name: "surface"; type: "QObject"; isPointer: true } Property { name: "window"; type: "QObject"; isPointer: true } Property { name: "viewportRect"; type: "QRectF" } Property { name: "clearColor"; type: "QColor" } + Property { name: "buffersToClear"; revision: 14; type: "Qt3DRender::QClearBuffers::BufferType" } Property { name: "camera"; type: "Qt3DCore::QEntity"; isPointer: true } Property { name: "externalRenderTargetSize"; type: "QSize" } Property { name: "frustumCulling"; type: "bool" } @@ -777,6 +820,10 @@ Module { name: "clearColorChanged" Parameter { name: "clearColor"; type: "QColor" } } + Signal { + name: "buffersToClearChanged" + Parameter { type: "Qt3DRender::QClearBuffers::BufferType" } + } Signal { name: "cameraChanged" Parameter { name: "camera"; type: "Qt3DCore::QEntity"; isPointer: true } @@ -805,6 +852,10 @@ Module { name: "setClearColor" Parameter { name: "clearColor"; type: "QColor" } } + Method { + name: "setBuffersToClear" + Parameter { type: "Qt3DRender::QClearBuffers::BufferType" } + } Method { name: "setCamera" Parameter { name: "camera"; type: "Qt3DCore::QEntity"; isPointer: true } diff --git a/src/quick3d/imports/input/plugins.qmltypes b/src/quick3d/imports/input/plugins.qmltypes index 8e9cac4d1..0a70b97c3 100644 --- a/src/quick3d/imports/input/plugins.qmltypes +++ b/src/quick3d/imports/input/plugins.qmltypes @@ -4,7 +4,7 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Input 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Input 2.14' Module { dependencies: ["Qt3D.Core 2.0"] diff --git a/src/quick3d/imports/logic/plugins.qmltypes b/src/quick3d/imports/logic/plugins.qmltypes index 294f6b068..1ad7b1f58 100644 --- a/src/quick3d/imports/logic/plugins.qmltypes +++ b/src/quick3d/imports/logic/plugins.qmltypes @@ -4,7 +4,7 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Logic 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Logic 2.14' Module { dependencies: ["Qt3D.Core 2.0"] diff --git a/src/quick3d/imports/render/plugins.qmltypes b/src/quick3d/imports/render/plugins.qmltypes index f5f5b3c61..6408abb27 100644 --- a/src/quick3d/imports/render/plugins.qmltypes +++ b/src/quick3d/imports/render/plugins.qmltypes @@ -4,7 +4,7 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Render 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json Qt3D.Render 2.14' Module { dependencies: ["Qt3D.Core 2.0"] @@ -362,7 +362,8 @@ Module { "R5G6B5": 36194, "RGB5A1": 32855, "RGBA4": 32854, - "RGB10A2": 36975, + "RGB10A2": 32857, + "RGB10A2U": 36975, "D16": 33189, "D24": 33190, "D24S8": 35056, @@ -588,6 +589,10 @@ Module { name: "setSamples" Parameter { name: "samples"; type: "int" } } + Method { + name: "updateData" + Parameter { name: "update"; type: "QTextureDataUpdate" } + } } Component { name: "Qt3DRender::QAbstractTextureImage" @@ -1068,8 +1073,12 @@ Module { Component { name: "Qt3DRender::QCamera" prototype: "Qt3DCore::QEntity" - exports: ["Qt3D.Render/Camera 2.0", "Qt3D.Render/Camera 2.9"] - exportMetaObjectRevisions: [0, 9] + exports: [ + "Qt3D.Render/Camera 2.0", + "Qt3D.Render/Camera 2.14", + "Qt3D.Render/Camera 2.9" + ] + exportMetaObjectRevisions: [0, 14, 9] Enum { name: "CameraTranslationOption" values: { @@ -1093,6 +1102,20 @@ Module { Property { name: "viewCenter"; type: "QVector3D" } Property { name: "viewVector"; type: "QVector3D"; isReadonly: true } Property { name: "viewMatrix"; type: "QMatrix4x4"; isReadonly: true } + Property { + name: "lens" + revision: 14 + type: "Qt3DRender::QCameraLens" + isReadonly: true + isPointer: true + } + Property { + name: "transform" + revision: 14 + type: "Qt3DCore::QTransform" + isReadonly: true + isPointer: true + } Signal { name: "projectionTypeChanged" Parameter { name: "projectionType"; type: "QCameraLens::ProjectionType" } @@ -1665,6 +1688,30 @@ Module { Parameter { name: "mode"; type: "CullingMode" } } } + Component { + name: "Qt3DRender::QDepthRange" + prototype: "Qt3DRender::QRenderState" + exports: ["Qt3D.Render/DepthRange 2.14"] + exportMetaObjectRevisions: [0] + Property { name: "nearValue"; type: "double" } + Property { name: "farValue"; type: "double" } + Signal { + name: "nearValueChanged" + Parameter { name: "nearValue"; type: "double" } + } + Signal { + name: "farValueChanged" + Parameter { name: "farValue"; type: "double" } + } + Method { + name: "setNearValue" + Parameter { name: "value"; type: "double" } + } + Method { + name: "setFarValue" + Parameter { name: "value"; type: "double" } + } + } Component { name: "Qt3DRender::QDepthTest" prototype: "Qt3DRender::QRenderState" @@ -2334,6 +2381,12 @@ Module { exports: ["Qt3D.Render/NoDraw 2.0"] exportMetaObjectRevisions: [0] } + Component { + name: "Qt3DRender::QNoPicking" + prototype: "Qt3DRender::QFrameGraphNode" + exports: ["Qt3D.Render/NoPicking 2.14"] + exportMetaObjectRevisions: [0] + } Component { name: "Qt3DRender::QObjectPicker" prototype: "Qt3DCore::QComponent" @@ -2429,9 +2482,9 @@ Module { Component { name: "Qt3DRender::QPickEvent" prototype: "QObject" - exports: ["Qt3D.Render/PickEvent 2.0"] + exports: ["Qt3D.Render/PickEvent 2.0", "Qt3D.Render/PickEvent 2.14"] isCreatable: false - exportMetaObjectRevisions: [0] + exportMetaObjectRevisions: [0, 14] Enum { name: "Buttons" values: { @@ -2461,6 +2514,20 @@ Module { Property { name: "button"; type: "Qt3DRender::QPickEvent::Buttons"; isReadonly: true } Property { name: "buttons"; type: "int"; isReadonly: true } Property { name: "modifiers"; type: "int"; isReadonly: true } + Property { + name: "viewport" + revision: 14 + type: "Qt3DRender::QViewport" + isReadonly: true + isPointer: true + } + Property { + name: "entity" + revision: 14 + type: "Qt3DCore::QEntity" + isReadonly: true + isPointer: true + } Signal { name: "acceptedChanged" Parameter { name: "accepted"; type: "bool" } @@ -2653,6 +2720,46 @@ Module { Parameter { name: "distanceThreshold"; type: "float" } } } + Component { + name: "Qt3DRender::QRasterMode" + prototype: "Qt3DRender::QRenderState" + exports: ["Qt3D.Render/RasterMode 2.13"] + exportMetaObjectRevisions: [0] + Enum { + name: "RasterMode" + values: { + "Points": 6912, + "Lines": 6913, + "Fill": 6914 + } + } + Enum { + name: "FaceMode" + values: { + "Front": 1028, + "Back": 1029, + "FrontAndBack": 1032 + } + } + Property { name: "rasterMode"; type: "RasterMode" } + Property { name: "faceMode"; type: "FaceMode" } + Signal { + name: "rasterModeChanged" + Parameter { name: "rasterMode"; type: "RasterMode" } + } + Signal { + name: "faceModeChanged" + Parameter { name: "faceMode"; type: "FaceMode" } + } + Method { + name: "setRasterMode" + Parameter { name: "rasterMode"; type: "RasterMode" } + } + Method { + name: "setFaceMode" + Parameter { name: "faceMode"; type: "FaceMode" } + } + } Component { name: "Qt3DRender::QRayCaster" prototype: "Qt3DRender::QAbstractRayCaster" @@ -3150,6 +3257,120 @@ Module { isCreatable: false exportMetaObjectRevisions: [0] } + Component { + name: "Qt3DRender::QShaderImage" + prototype: "Qt3DCore::QNode" + exports: ["Qt3D.Render/ShaderImage 2.14"] + exportMetaObjectRevisions: [0] + Enum { + name: "Access" + values: { + "ReadOnly": 0, + "WriteOnly": 1, + "ReadWrite": 2 + } + } + Enum { + name: "ImageFormat" + values: { + "NoFormat": 0, + "Automatic": 1, + "R8_UNorm": 33321, + "RG8_UNorm": 33323, + "RGBA8_UNorm": 32856, + "R16_UNorm": 33322, + "RG16_UNorm": 33324, + "RGBA16_UNorm": 32859, + "R8_SNorm": 36756, + "RG8_SNorm": 36757, + "RGBA8_SNorm": 36759, + "R16_SNorm": 36760, + "RG16_SNorm": 36761, + "RGBA16_SNorm": 36763, + "R8U": 33330, + "RG8U": 33336, + "RGBA8U": 36220, + "R16U": 33332, + "RG16U": 33338, + "RGBA16U": 36214, + "R32U": 33334, + "RG32U": 33340, + "RGBA32U": 36208, + "R8I": 33329, + "RG8I": 33335, + "RGBA8I": 36238, + "R16I": 33331, + "RG16I": 33337, + "RGBA16I": 36232, + "R32I": 33333, + "RG32I": 33339, + "RGBA32I": 36226, + "R16F": 33325, + "RG16F": 33327, + "RGBA16F": 34842, + "R32F": 33326, + "RG32F": 33328, + "RGBA32F": 34836, + "RG11B10F": 35898, + "RGB10A2": 32857, + "RGB10A2U": 36975 + } + } + Property { name: "texture"; type: "Qt3DRender::QAbstractTexture"; isPointer: true } + Property { name: "layered"; type: "bool" } + Property { name: "mipLevel"; type: "int" } + Property { name: "layer"; type: "int" } + Property { name: "access"; type: "Access" } + Property { name: "format"; type: "ImageFormat" } + Signal { + name: "textureChanged" + Parameter { name: "texture"; type: "Qt3DRender::QAbstractTexture"; isPointer: true } + } + Signal { + name: "layeredChanged" + Parameter { name: "layered"; type: "bool" } + } + Signal { + name: "mipLevelChanged" + Parameter { name: "mipLevel"; type: "int" } + } + Signal { + name: "layerChanged" + Parameter { name: "layer"; type: "int" } + } + Signal { + name: "accessChanged" + Parameter { name: "access"; type: "Access" } + } + Signal { + name: "formatChanged" + Parameter { name: "format"; type: "ImageFormat" } + } + Method { + name: "setTexture" + Parameter { name: "texture"; type: "Qt3DRender::QAbstractTexture"; isPointer: true } + } + Method { + name: "setLayered" + Parameter { name: "layered"; type: "bool" } + } + Method { + name: "setMipLevel" + Parameter { name: "mipLevel"; type: "int" } + } + Method { + name: "setLayer" + Parameter { name: "layer"; type: "int" } + } + Method { + name: "setAccess" + Parameter { name: "access"; type: "Access" } + } + Method { + name: "setFormat" + Parameter { name: "format"; type: "ImageFormat" } + } + } Component { name: "Qt3DRender::QShaderProgram" prototype: "Qt3DCore::QNode" @@ -3400,7 +3621,8 @@ Module { "StateChangeCost": 1, "BackToFront": 2, "Material": 4, - "FrontToBack": 8 + "FrontToBack": 8, + "Texture": 16 } } Property { name: "sortTypes"; type: "QVector" } @@ -3652,6 +3874,25 @@ Module { Parameter { name: "stencilFunction"; type: "StencilFunction" } } } + Component { + name: "Qt3DRender::QSubtreeEnabler" + prototype: "Qt3DRender::QFrameGraphNode" + exports: ["Qt3D.Render/SubtreeEnabler 2.14"] + exportMetaObjectRevisions: [0] + Enum { + name: "Enablement" + values: { + "Persistent": 0, + "SingleShot": 1 + } + } + Property { name: "enablement"; type: "Enablement" } + Signal { + name: "enablementChanged" + Parameter { name: "enablement"; type: "Qt3DRender::QSubtreeEnabler::Enablement" } + } + Method { name: "requestUpdate" } + } Component { name: "Qt3DRender::QTechnique" defaultProperty: "data" diff --git a/src/quick3d/imports/scene2d/plugins.qmltypes b/src/quick3d/imports/scene2d/plugins.qmltypes index 9d2c855a6..32fb8122f 100644 --- a/src/quick3d/imports/scene2d/plugins.qmltypes +++ b/src/quick3d/imports/scene2d/plugins.qmltypes @@ -4,7 +4,7 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json QtQuick.Scene2D 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json QtQuick.Scene2D 2.14' Module { dependencies: ["Qt3D.Core 2.0", "Qt3D.Render 2.0"] diff --git a/src/quick3d/imports/scene3d/plugins.qmltypes b/src/quick3d/imports/scene3d/plugins.qmltypes index da3d7ec3e..aca01ac25 100644 --- a/src/quick3d/imports/scene3d/plugins.qmltypes +++ b/src/quick3d/imports/scene3d/plugins.qmltypes @@ -4,7 +4,7 @@ import QtQuick.tooling 1.2 // It is used for QML tooling purposes only. // // This file was auto-generated by: -// 'qmlplugindump -nonrelocatable -dependencies dependencies.json QtQuick.Scene3D 2.13' +// 'qmlplugindump -nonrelocatable -dependencies dependencies.json QtQuick.Scene3D 2.14' Module { dependencies: ["Qt3D.Core 2.0", "QtQuick 2.0"] @@ -12,8 +12,11 @@ Module { name: "Qt3DRender::Scene3DItem" defaultProperty: "entity" prototype: "QQuickItem" - exports: ["QtQuick.Scene3D/Scene3D 2.0"] - exportMetaObjectRevisions: [0] + exports: [ + "QtQuick.Scene3D/Scene3D 2.0", + "QtQuick.Scene3D/Scene3D 2.14" + ] + exportMetaObjectRevisions: [0, 14] Enum { name: "CameraAspectRatioMode" values: { @@ -21,11 +24,19 @@ Module { "UserAspectRatio": 1 } } + Enum { + name: "CompositingMode" + values: { + "FBO": 0, + "Underlay": 1 + } + } Property { name: "entity"; type: "Qt3DCore::QEntity"; isPointer: true } Property { name: "aspects"; type: "QStringList" } Property { name: "multisample"; type: "bool" } Property { name: "cameraAspectRatioMode"; type: "CameraAspectRatioMode" } Property { name: "hoverEnabled"; type: "bool" } + Property { name: "compositingMode"; revision: 14; type: "CompositingMode" } Signal { name: "cameraAspectRatioModeChanged" Parameter { name: "mode"; type: "CameraAspectRatioMode" } @@ -46,10 +57,31 @@ Module { name: "setHoverEnabled" Parameter { name: "enabled"; type: "bool" } } + Method { + name: "setCompositingMode" + Parameter { name: "mode"; type: "CompositingMode" } + } Method { name: "setItemAreaAndDevicePixelRatio" Parameter { name: "area"; type: "QSize" } Parameter { name: "devicePixelRatio"; type: "double" } } } + Component { + name: "Qt3DRender::Scene3DView" + defaultProperty: "entity" + prototype: "QQuickItem" + exports: ["QtQuick.Scene3D/Scene3DView 2.14"] + exportMetaObjectRevisions: [0] + Property { name: "entity"; type: "Qt3DCore::QEntity"; isPointer: true } + Property { name: "scene3D"; type: "Qt3DRender::Scene3DItem"; isPointer: true } + Method { + name: "setEntity" + Parameter { name: "entity"; type: "Qt3DCore::QEntity"; isPointer: true } + } + Method { + name: "setScene3D" + Parameter { name: "scene3D"; type: "Scene3DItem"; isPointer: true } + } + } } -- cgit v1.2.3 From 257c9bc8b53fb62fcad6bb8977b048d3a7563469 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Wed, 16 Oct 2019 10:52:17 +0200 Subject: Renderer: build cache data for new RenderViews Change-Id: I95690444badaf573b9e2775b50c61113de8d1c77 Reviewed-by: Michael Brasser --- src/render/renderers/opengl/renderer/renderer.cpp | 19 ++++++++------- tests/auto/render/renderer/tst_renderer.cpp | 29 ++++++++++++++++++++++- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index 474519398..9220a719a 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -1887,14 +1887,17 @@ QVector Renderer::renderBinJobs() const int fgBranchCount = m_frameGraphLeaves.size(); for (int i = 0; i < fgBranchCount; ++i) { - RenderViewBuilder builder(m_frameGraphLeaves.at(i), i, this); - builder.setLayerCacheNeedsToBeRebuilt(layersCacheNeedsToBeRebuilt); - builder.setRenderableCacheNeedsToBeRebuilt(renderableDirty); - builder.setComputableCacheNeedsToBeRebuilt(computeableDirty); - builder.setLightGathererCacheNeedsToBeRebuilt(lightsDirty); - builder.setMaterialGathererCacheNeedsToBeRebuilt(materialCacheNeedsToBeRebuilt); - builder.setLightGathererCacheNeedsToBeRebuilt(lightsDirty); - builder.setRenderCommandCacheNeedsToBeRebuilt(renderCommandsDirty); + FrameGraphNode *leaf = m_frameGraphLeaves.at(i); + RenderViewBuilder builder(leaf, i, this); + // If we have a new RV (wasn't in the cache before, then it contains no cached data) + const bool isNewRV = !m_cache.leafNodeCache.contains(leaf); + builder.setLayerCacheNeedsToBeRebuilt(layersCacheNeedsToBeRebuilt || isNewRV); + builder.setRenderableCacheNeedsToBeRebuilt(renderableDirty || isNewRV); + builder.setComputableCacheNeedsToBeRebuilt(computeableDirty || isNewRV); + builder.setLightGathererCacheNeedsToBeRebuilt(lightsDirty || isNewRV); + builder.setMaterialGathererCacheNeedsToBeRebuilt(materialCacheNeedsToBeRebuilt || isNewRV); + builder.setLightGathererCacheNeedsToBeRebuilt(lightsDirty || isNewRV); + builder.setRenderCommandCacheNeedsToBeRebuilt(renderCommandsDirty || isNewRV); builder.prepareJobs(); renderBinJobs.append(builder.buildJobHierachy()); diff --git a/tests/auto/render/renderer/tst_renderer.cpp b/tests/auto/render/renderer/tst_renderer.cpp index 91cb7906c..0940348bd 100644 --- a/tests/auto/render/renderer/tst_renderer.cpp +++ b/tests/auto/render/renderer/tst_renderer.cpp @@ -211,8 +211,35 @@ private Q_SLOTS: renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); renderQueue->reset(); - // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) + // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) (Nothing in cache) + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::FrameGraphDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + 1 + // sendDisablesToFrontend + 1 + // LightGathererJob + 1 + // CacheLightJob + 1 + // RenderableEntityFilterJob + 1 + // CacheRenderableEntitiesJob + 1 + // ComputableEntityFilterJob + 1 + // CacheComputableEntitiesJob + singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + + renderViewBuilderMaterialCacheJobCount + + layerCacheJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) (RV leaf in cache) renderer.markDirty(Qt3DRender::Render::AbstractRenderer::FrameGraphDirty, nullptr); + renderer.cache()->leafNodeCache[renderer.m_frameGraphLeaves.first()] = {}; jobs = renderer.renderBinJobs(); // THEN (level -- cgit v1.2.3 From 84766ed9098f10efc53e4e43a75eef38fce7fbf6 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Mon, 21 Oct 2019 17:01:18 +0100 Subject: Fix post FF API changes Change-Id: I347f6df41c0a4f2295831e78248669b4a2d6b5ef Reviewed-by: Paul Lemire --- src/animation/frontend/qanimationaspect.cpp | 20 ++-- src/core/aspects/qabstractaspect.cpp | 30 ++--- src/core/aspects/qabstractaspect.h | 12 -- src/core/aspects/qabstractaspect_p.h | 12 +- src/core/aspects/qaspectmanager.cpp | 4 +- src/core/changes/qscenechange.h | 8 -- src/core/changes/qscenechange_p.h | 8 ++ src/core/jobs/qaspectjob.cpp | 7 -- src/core/jobs/qaspectjob.h | 1 - src/core/qchangearbiter_p.h | 1 + src/core/qscheduler.cpp | 4 +- src/input/frontend/qinputaspect.cpp | 38 +++--- src/quick3d/quick3dscene2d/items/qscene2d.cpp | 9 -- src/quick3d/quick3dscene2d/items/qscene2d.h | 3 +- src/quick3d/quick3dscene2d/items/scene2d.cpp | 2 +- src/render/frontend/qlevelofdetail.cpp | 20 ++++ src/render/frontend/qlevelofdetailswitch.cpp | 37 +----- src/render/frontend/qlevelofdetailswitch.h | 3 +- src/render/frontend/qrenderaspect.cpp | 127 ++++++++++----------- src/render/frontend/qrenderaspect_p.h | 1 - src/render/frontend/qrenderplugin_p.h | 3 +- tests/auto/core/common/testpostmanarbiter.h | 1 + tests/auto/core/nodes/tst_nodes.cpp | 12 +- .../render/raycastingjob/tst_raycastingjob.cpp | 4 +- 24 files changed, 159 insertions(+), 208 deletions(-) diff --git a/src/animation/frontend/qanimationaspect.cpp b/src/animation/frontend/qanimationaspect.cpp index 744346e1f..850132a39 100644 --- a/src/animation/frontend/qanimationaspect.cpp +++ b/src/animation/frontend/qanimationaspect.cpp @@ -104,34 +104,34 @@ QAnimationAspect::QAnimationAspect(QAnimationAspectPrivate &dd, QObject *parent) qRegisterMetaType>(); qRegisterMetaType(); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->animationClipLoaderManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->clockManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->clipAnimatorManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->blendedClipAnimatorManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->channelMappingManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->channelMapperManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->clipBlendNodeManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->clipBlendNodeManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->clipBlendNodeManager())); - registerBackendType( + d->registerBackendType( QSharedPointer>::create(d->m_handler.data(), d->m_handler->skeletonManager())); } diff --git a/src/core/aspects/qabstractaspect.cpp b/src/core/aspects/qabstractaspect.cpp index 05afdd293..19b6f70c1 100644 --- a/src/core/aspects/qabstractaspect.cpp +++ b/src/core/aspects/qabstractaspect.cpp @@ -91,6 +91,13 @@ void QAbstractAspectPrivate::onEngineAboutToShutdown() { } +/*! \internal */ +void QAbstractAspectPrivate::registerBackendType(const QMetaObject &obj, const QBackendNodeMapperPtr &functor, bool supportsSyncing) +{ + const auto f = supportsSyncing ? QAbstractAspectPrivate::SupportsSyncing : QAbstractAspectPrivate::DefaultMapper; + m_backendCreatorFunctors.insert(&obj, {functor, f}); +} + /*! \internal */ void QAbstractAspectPrivate::unregisterBackendType(const QMetaObject &mo) { @@ -183,13 +190,6 @@ void QAbstractAspect::registerBackendType(const QMetaObject &obj, const QBackend d->m_backendCreatorFunctors.insert(&obj, {functor, QAbstractAspectPrivate::DefaultMapper}); } -void QAbstractAspect::registerBackendType(const QMetaObject &obj, const QBackendNodeMapperPtr &functor, bool supportsSyncing) -{ - Q_D(QAbstractAspect); - const auto f = supportsSyncing ? QAbstractAspectPrivate::SupportsSyncing : QAbstractAspectPrivate::DefaultMapper; - d->m_backendCreatorFunctors.insert(&obj, {functor, f}); -} - void QAbstractAspect::unregisterBackendType(const QMetaObject &obj) { Q_D(QAbstractAspect); @@ -198,28 +198,16 @@ void QAbstractAspect::unregisterBackendType(const QMetaObject &obj) QVariant QAbstractAspect::executeCommand(const QStringList &args) { - Q_UNUSED(args); + Q_UNUSED(args) return QVariant(); } QVector QAbstractAspect::jobsToExecute(qint64 time) { - Q_UNUSED(time); + Q_UNUSED(time) return QVector(); } -void QAbstractAspect::syncDirtyFrontEndNodes(const QVector &nodes) -{ - Q_D(QAbstractAspect); - d->syncDirtyFrontEndNodes(nodes); -} - -void QAbstractAspect::syncDirtyFrontEndSubNodes(const QVector &nodes) -{ - Q_D(QAbstractAspect); - d->syncDirtyFrontEndSubNodes(nodes); -} - QAbstractAspectPrivate::BackendNodeMapperAndInfo QAbstractAspectPrivate::mapperForNode(const QMetaObject *metaObj) const { Q_ASSERT(metaObj); diff --git a/src/core/aspects/qabstractaspect.h b/src/core/aspects/qabstractaspect.h index 8059421a6..cb3d02089 100644 --- a/src/core/aspects/qabstractaspect.h +++ b/src/core/aspects/qabstractaspect.h @@ -78,18 +78,12 @@ protected: template void registerBackendType(const QBackendNodeMapperPtr &functor); - template - void registerBackendType(const QBackendNodeMapperPtr &functor); void registerBackendType(const QMetaObject &obj, const QBackendNodeMapperPtr &functor); - void registerBackendType(const QMetaObject &obj, const QBackendNodeMapperPtr &functor, bool supportsSyncing); template void unregisterBackendType(); void unregisterBackendType(const QMetaObject &); private: - void syncDirtyFrontEndNodes(const QVector &nodes); - void syncDirtyFrontEndSubNodes(const QVector &nodes); - virtual QVariant executeCommand(const QStringList &args); virtual QVector jobsToExecute(qint64 time); @@ -111,12 +105,6 @@ void QAbstractAspect::registerBackendType(const QBackendNodeMapperPtr &functor) registerBackendType(Frontend::staticMetaObject, functor); } -template -void QAbstractAspect::registerBackendType(const QBackendNodeMapperPtr &functor) -{ - registerBackendType(Frontend::staticMetaObject, functor, supportsSyncing); -} - template void QAbstractAspect::unregisterBackendType() { diff --git a/src/core/aspects/qabstractaspect_p.h b/src/core/aspects/qabstractaspect_p.h index 670302cfa..325fca678 100644 --- a/src/core/aspects/qabstractaspect_p.h +++ b/src/core/aspects/qabstractaspect_p.h @@ -57,6 +57,7 @@ #include #include #include +#include #include #include @@ -136,7 +137,10 @@ public: virtual void onEngineAboutToShutdown(); - // TODO: Make these public in 5.8 + // TODO: Make public at some point + template + void registerBackendType(const QBackendNodeMapperPtr &functor); + void registerBackendType(const QMetaObject &obj, const QBackendNodeMapperPtr &functor, bool supportsSyncing); template void unregisterBackendType(); void unregisterBackendType(const QMetaObject &mo); @@ -162,6 +166,12 @@ public: static QAbstractAspectPrivate *get(QAbstractAspect *aspect); }; +template +void QAbstractAspectPrivate::registerBackendType(const QBackendNodeMapperPtr &functor) +{ + registerBackendType(Frontend::staticMetaObject, functor, supportsSyncing); +} + template void QAbstractAspectPrivate::unregisterBackendType() { diff --git a/src/core/aspects/qaspectmanager.cpp b/src/core/aspects/qaspectmanager.cpp index 027264977..dffdd1c1a 100644 --- a/src/core/aspects/qaspectmanager.cpp +++ b/src/core/aspects/qaspectmanager.cpp @@ -480,13 +480,13 @@ void QAspectManager::processFrame() const auto dirtySubNodes = m_changeArbiter->takeDirtyFrontEndSubNodes(); if (dirtySubNodes.size()) for (QAbstractAspect *aspect : qAsConst(m_aspects)) - aspect->syncDirtyFrontEndSubNodes(dirtySubNodes); + QAbstractAspectPrivate::get(aspect)->syncDirtyFrontEndSubNodes(dirtySubNodes); // Sync property updates const auto dirtyFrontEndNodes = m_changeArbiter->takeDirtyFrontEndNodes(); if (dirtyFrontEndNodes.size()) for (QAbstractAspect *aspect : qAsConst(m_aspects)) - aspect->syncDirtyFrontEndNodes(dirtyFrontEndNodes); + QAbstractAspectPrivate::get(aspect)->syncDirtyFrontEndNodes(dirtyFrontEndNodes); // TO DO: Having this done in the main thread actually means aspects could just // as simply read info out of the Frontend classes without risk of introducing diff --git a/src/core/changes/qscenechange.h b/src/core/changes/qscenechange.h index e8c0ea748..4a0740819 100644 --- a/src/core/changes/qscenechange.h +++ b/src/core/changes/qscenechange.h @@ -64,14 +64,6 @@ Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag) Q_DECLARE_OPERATORS_FOR_FLAGS(ChangeFlags) class QNode; -//! internal -struct NodeRelationshipChange { - QNode *node; - QNode *subNode; - ChangeFlag change; - const char *property; -}; - class QSceneChangePrivate; class Q_3DCORESHARED_EXPORT QSceneChange diff --git a/src/core/changes/qscenechange_p.h b/src/core/changes/qscenechange_p.h index d32f6eec3..358beab49 100644 --- a/src/core/changes/qscenechange_p.h +++ b/src/core/changes/qscenechange_p.h @@ -60,6 +60,14 @@ QT_BEGIN_NAMESPACE namespace Qt3DCore { +//! internal +struct NodeRelationshipChange { + QNode *node; + QNode *subNode; + ChangeFlag change; + const char *property; +}; + class QSceneChange; class QNodeId; diff --git a/src/core/jobs/qaspectjob.cpp b/src/core/jobs/qaspectjob.cpp index 00ad1ace8..318a431ac 100644 --- a/src/core/jobs/qaspectjob.cpp +++ b/src/core/jobs/qaspectjob.cpp @@ -140,13 +140,6 @@ QVector > QAspectJob::dependencies() const return d->m_dependencies; } -void QAspectJob::postFrame(QAspectManager *aspectManager) -{ - Q_D(QAspectJob); - if (aspectManager) - d->postFrame(aspectManager); -} - } // namespace Qt3DCore QT_END_NAMESPACE diff --git a/src/core/jobs/qaspectjob.h b/src/core/jobs/qaspectjob.h index 7cc784e0f..deb8cf2ed 100644 --- a/src/core/jobs/qaspectjob.h +++ b/src/core/jobs/qaspectjob.h @@ -63,7 +63,6 @@ public: QVector > dependencies() const; virtual void run() = 0; - void postFrame(QAspectManager *aspectManager); protected: explicit QAspectJob(QAspectJobPrivate &dd); diff --git a/src/core/qchangearbiter_p.h b/src/core/qchangearbiter_p.h index f31480685..81f33f625 100644 --- a/src/core/qchangearbiter_p.h +++ b/src/core/qchangearbiter_p.h @@ -53,6 +53,7 @@ #include #include +#include #include #include #include diff --git a/src/core/qscheduler.cpp b/src/core/qscheduler.cpp index edfbb391c..e714e477d 100644 --- a/src/core/qscheduler.cpp +++ b/src/core/qscheduler.cpp @@ -40,7 +40,7 @@ #include "qscheduler_p.h" #include - +#include #include #include #include @@ -93,7 +93,7 @@ void QScheduler::scheduleAndWaitForFrameAspectJobs(qint64 time) m_aspectManager->jobManager()->waitForAllJobs(); for (auto &job : qAsConst(jobQueue)) - job->postFrame(m_aspectManager); + QAspectJobPrivate::get(job.data())->postFrame(m_aspectManager); } } // namespace Qt3DCore diff --git a/src/input/frontend/qinputaspect.cpp b/src/input/frontend/qinputaspect.cpp index e109461f0..31a0f8b1e 100644 --- a/src/input/frontend/qinputaspect.cpp +++ b/src/input/frontend/qinputaspect.cpp @@ -141,33 +141,33 @@ QInputAspect::QInputAspect(QObject *parent) QInputAspect::QInputAspect(QInputAspectPrivate &dd, QObject *parent) : QAbstractAspect(dd, parent) { + Q_D(QInputAspect); setObjectName(QStringLiteral("Input Aspect")); qRegisterMetaType(); - registerBackendType(QBackendNodeMapperPtr(new Input::KeyboardDeviceFunctor(this, d_func()->m_inputHandler.data()))); - registerBackendType(QBackendNodeMapperPtr(new Input::KeyboardHandlerFunctor(d_func()->m_inputHandler.data()))); - registerBackendType(QBackendNodeMapperPtr(new Input::MouseDeviceFunctor(this, d_func()->m_inputHandler.data()))); - registerBackendType(QBackendNodeMapperPtr(new Input::MouseHandlerFunctor(d_func()->m_inputHandler.data()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->axisManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->axisAccumulatorManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->analogAxisInputManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->buttonAxisInputManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->axisSettingManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->actionManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->actionInputManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->inputChordManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->inputSequenceManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::LogicalDeviceNodeFunctor(d_func()->m_inputHandler->logicalDeviceManager()))); - registerBackendType(QBackendNodeMapperPtr(new Input::GenericDeviceBackendFunctor(this, d_func()->m_inputHandler.data()))); - registerBackendType(QBackendNodeMapperPtr(new Input::InputSettingsFunctor(d_func()->m_inputHandler.data()))); - registerBackendType(QBackendNodeMapperPtr(new Input::PhysicalDeviceProxyNodeFunctor(d_func()->m_inputHandler->physicalDeviceProxyManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::KeyboardDeviceFunctor(this, d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::KeyboardHandlerFunctor(d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::MouseDeviceFunctor(this, d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::MouseHandlerFunctor(d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->axisManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->axisAccumulatorManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->analogAxisInputManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->buttonAxisInputManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->axisSettingManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->actionManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->actionInputManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->inputChordManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputNodeFunctor(d_func()->m_inputHandler->inputSequenceManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::LogicalDeviceNodeFunctor(d_func()->m_inputHandler->logicalDeviceManager()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::GenericDeviceBackendFunctor(this, d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::InputSettingsFunctor(d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::PhysicalDeviceProxyNodeFunctor(d_func()->m_inputHandler->physicalDeviceProxyManager()))); #ifdef HAVE_QGAMEPAD - registerBackendType(QBackendNodeMapperPtr(new Input::GenericDeviceBackendFunctor(this, d_func()->m_inputHandler.data()))); + d->registerBackendType(QBackendNodeMapperPtr(new Input::GenericDeviceBackendFunctor(this, d_func()->m_inputHandler.data()))); #endif - Q_D(QInputAspect); // Plugins are QInputDeviceIntegration instances d->loadInputDevicePlugins(); diff --git a/src/quick3d/quick3dscene2d/items/qscene2d.cpp b/src/quick3d/quick3dscene2d/items/qscene2d.cpp index cbdc83e7d..dfa3f261f 100644 --- a/src/quick3d/quick3dscene2d/items/qscene2d.cpp +++ b/src/quick3d/quick3dscene2d/items/qscene2d.cpp @@ -303,15 +303,6 @@ QVector QScene2D::entities() return d->m_entities; } -/*! - Retrieve entities associated with the QScene2D. - */ -QVector QScene2D::entities() const -{ - Q_D(const QScene2D); - return d->m_entities; -} - /*! Adds an \a entity to the the QScene2D object. If the entities have QObjectPicker, the pick events from that entity are sent to QScene2D and converted to mouse events. diff --git a/src/quick3d/quick3dscene2d/items/qscene2d.h b/src/quick3d/quick3dscene2d/items/qscene2d.h index 2f5c1010e..eab900ca4 100644 --- a/src/quick3d/quick3dscene2d/items/qscene2d.h +++ b/src/quick3d/quick3dscene2d/items/qscene2d.h @@ -86,8 +86,7 @@ public: QQuickItem *item() const; bool isMouseEnabled() const; - Q_DECL_DEPRECATED QVector entities(); - QVector entities() const; + QVector entities(); void addEntity(Qt3DCore::QEntity *entity); void removeEntity(Qt3DCore::QEntity *entity); diff --git a/src/quick3d/quick3dscene2d/items/scene2d.cpp b/src/quick3d/quick3dscene2d/items/scene2d.cpp index 981b290e2..b8f99ae1b 100644 --- a/src/quick3d/quick3dscene2d/items/scene2d.cpp +++ b/src/quick3d/quick3dscene2d/items/scene2d.cpp @@ -193,7 +193,7 @@ void Scene2D::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) if (id != m_outputId) setOutput(id); - auto ids = Qt3DCore::qIdsForNodes(node->entities()); + auto ids = Qt3DCore::qIdsForNodes(const_cast(node)->entities()); std::sort(std::begin(ids), std::end(ids)); Qt3DCore::QNodeIdVector addedEntities; Qt3DCore::QNodeIdVector removedEntities; diff --git a/src/render/frontend/qlevelofdetail.cpp b/src/render/frontend/qlevelofdetail.cpp index ced0604c7..52f5ea7c9 100644 --- a/src/render/frontend/qlevelofdetail.cpp +++ b/src/render/frontend/qlevelofdetail.cpp @@ -39,6 +39,7 @@ #include "qlevelofdetail.h" #include "qlevelofdetail_p.h" +#include "qlevelofdetailswitch.h" #include "qcamera.h" QT_BEGIN_NAMESPACE @@ -60,6 +61,25 @@ void QLevelOfDetailPrivate::setCurrentIndex(int currentIndex) if (m_currentIndex != currentIndex) { m_currentIndex = currentIndex; emit q->currentIndexChanged(m_currentIndex); + + // TODO use derived pimpl + QLevelOfDetailSwitch *qswitch = qobject_cast(q); + if (qswitch) { + int entityIndex = 0; + const auto entities = q->entities(); + if (entities.size()) { + // only work on the first entity, LOD should not be shared + Qt3DCore::QEntity *entity = entities.front(); + const auto childNodes = entity->childNodes(); + for (Qt3DCore::QNode *childNode : childNodes) { + Qt3DCore::QEntity *childEntity = qobject_cast(childNode); + if (childEntity) { + childEntity->setEnabled(entityIndex == currentIndex); + entityIndex++; + } + } + } + } } } diff --git a/src/render/frontend/qlevelofdetailswitch.cpp b/src/render/frontend/qlevelofdetailswitch.cpp index c07d4c4b1..ec658b172 100644 --- a/src/render/frontend/qlevelofdetailswitch.cpp +++ b/src/render/frontend/qlevelofdetailswitch.cpp @@ -38,7 +38,6 @@ ****************************************************************************/ #include "qlevelofdetailswitch.h" -#include "qlevelofdetailswitch_p.h" #include "qlevelofdetail_p.h" #include "qglobal.h" #include @@ -47,38 +46,6 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { -QLevelOfDetailSwitchPrivate::QLevelOfDetailSwitchPrivate() - : QLevelOfDetailPrivate() -{ - -} - -void QLevelOfDetailSwitchPrivate::setCurrentIndex(int currentIndex) -{ - Q_Q(QLevelOfDetailSwitch); - - bool changed = m_currentIndex != currentIndex; - QLevelOfDetailPrivate::setCurrentIndex(currentIndex); - - if (!changed) - return; - - int entityIndex = 0; - const auto entities = q->entities(); - for (Qt3DCore::QEntity *entity : entities) { - const auto childNodes = entity->childNodes(); - for (Qt3DCore::QNode *childNode : childNodes) { - Qt3DCore::QEntity *childEntity = qobject_cast(childNode); - if (childEntity) { - childEntity->setEnabled(entityIndex == currentIndex); - entityIndex++; - } - } - - break; // only work on the first entity, LOD should not be shared - } -} - /*! \class Qt3DRender::QLevelOfDetailSwitch \inmodule Qt3DRender @@ -116,9 +83,9 @@ void QLevelOfDetailSwitchPrivate::setCurrentIndex(int currentIndex) Constructs a new QLevelOfDetailSwitch with the specified \a parent. */ QLevelOfDetailSwitch::QLevelOfDetailSwitch(QNode *parent) - : QLevelOfDetail(*new QLevelOfDetailSwitchPrivate(), parent) + : QLevelOfDetail(parent) { - Q_D(QLevelOfDetailSwitch); + Q_D(QLevelOfDetail); d->m_currentIndex = -1; } diff --git a/src/render/frontend/qlevelofdetailswitch.h b/src/render/frontend/qlevelofdetailswitch.h index 325b885ed..a292f7eb3 100644 --- a/src/render/frontend/qlevelofdetailswitch.h +++ b/src/render/frontend/qlevelofdetailswitch.h @@ -45,7 +45,6 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { -class QLevelOfDetailSwitchPrivate; class Q_3DRENDERSHARED_EXPORT QLevelOfDetailSwitch : public QLevelOfDetail { @@ -61,7 +60,7 @@ protected: void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: - Q_DECLARE_PRIVATE(QLevelOfDetailSwitch) + Q_DECLARE_PRIVATE(QLevelOfDetail) }; } // namespace Qt3DRender diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index 271eb9c11..72f114481 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -252,77 +252,77 @@ void QRenderAspectPrivate::registerBackendTypes() qRegisterMetaType(); qRegisterMetaType(); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - - q->registerBackendType(QSharedPointer::create(m_renderer, q)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->sceneManager())); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); + registerBackendType(QSharedPointer >::create(m_renderer)); + + registerBackendType(QSharedPointer::create(m_renderer, q)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->sceneManager())); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); // Geometry + Compute - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->bufferManager())); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->geometryRendererManager())); - q->registerBackendType(QSharedPointer>::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->skeletonManager(), m_nodeManagers->jointManager())); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->jointManager(), m_nodeManagers->skeletonManager())); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->bufferManager())); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->geometryRendererManager())); + registerBackendType(QSharedPointer>::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->skeletonManager(), m_nodeManagers->jointManager())); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->jointManager(), m_nodeManagers->skeletonManager())); // Textures - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->textureManager())); - q->registerBackendType(QSharedPointer::create(m_renderer, + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->textureManager())); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->textureImageManager())); // Material system - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); - q->registerBackendType(QSharedPointer>::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); + registerBackendType(QSharedPointer>::create(m_renderer)); // Framegraph - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); // Picking - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); + registerBackendType(QSharedPointer >::create(m_renderer)); // Plugins for (const QString &plugin : qAsConst(m_pluginConfig)) @@ -403,13 +403,6 @@ void QRenderAspectPrivate::unregisterBackendTypes() plugin->unregisterBackendTypes(q); } -void QRenderAspectPrivate::registerBackendType(const QMetaObject &obj, - const QBackendNodeMapperPtr &functor) -{ - Q_Q(QRenderAspect); - q->registerBackendType(obj, functor); -} - /*! * The constructor creates a new QRenderAspect::QRenderAspect instance with the * specified \a parent. diff --git a/src/render/frontend/qrenderaspect_p.h b/src/render/frontend/qrenderaspect_p.h index 62e373b11..b4cb0812c 100644 --- a/src/render/frontend/qrenderaspect_p.h +++ b/src/render/frontend/qrenderaspect_p.h @@ -95,7 +95,6 @@ public: void renderInitialize(QOpenGLContext *context); void renderSynchronous(bool swapBuffers = true); void renderShutdown(); - void registerBackendType(const QMetaObject &, const Qt3DCore::QBackendNodeMapperPtr &functor); QVector createGeometryRendererJobs(); Render::NodeManagers *m_nodeManagers; diff --git a/src/render/frontend/qrenderplugin_p.h b/src/render/frontend/qrenderplugin_p.h index 110c8295a..4aa0ec697 100644 --- a/src/render/frontend/qrenderplugin_p.h +++ b/src/render/frontend/qrenderplugin_p.h @@ -51,6 +51,7 @@ #include #include +#include #include #include @@ -77,7 +78,7 @@ protected: } void registerBackendType(QRenderAspect *aspect, const QMetaObject &obj, const Qt3DCore::QBackendNodeMapperPtr &functor, bool supportsSyncing) { - aspect->registerBackendType(obj, functor, supportsSyncing); + Qt3DCore::QAbstractAspectPrivate::get(aspect)->registerBackendType(obj, functor, supportsSyncing); } void unregisterBackendType(QRenderAspect *aspect, const QMetaObject &obj) { diff --git a/tests/auto/core/common/testpostmanarbiter.h b/tests/auto/core/common/testpostmanarbiter.h index cecc24f93..6649c7bbe 100644 --- a/tests/auto/core/common/testpostmanarbiter.h +++ b/tests/auto/core/common/testpostmanarbiter.h @@ -28,6 +28,7 @@ #include #include +#include QT_BEGIN_NAMESPACE diff --git a/tests/auto/core/nodes/tst_nodes.cpp b/tests/auto/core/nodes/tst_nodes.cpp index 3b93e7715..25565d470 100644 --- a/tests/auto/core/nodes/tst_nodes.cpp +++ b/tests/auto/core/nodes/tst_nodes.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include #include @@ -516,7 +517,7 @@ public: void syncDirtyFrontEndNode(Qt3DCore::QNode *node, Qt3DCore::QBackendNode *backend, bool firstTime) const override { - Q_UNUSED(backend); + Q_UNUSED(backend) auto q = q_func(); if (firstTime) q->allNodes.insert(node->id(), node); @@ -527,10 +528,11 @@ public: TestAspect::TestAspect(QObject *parent) : TestAspect(*new TestAspectPrivate, parent) { - registerBackendType(QSharedPointer::create(this)); - registerBackendType(QSharedPointer::create(this)); - registerBackendType(QSharedPointer::create(this)); - registerBackendType(QSharedPointer::create(this)); + Q_D(TestAspect); + d->registerBackendType(QSharedPointer::create(this)); + d->registerBackendType(QSharedPointer::create(this)); + d->registerBackendType(QSharedPointer::create(this)); + d->registerBackendType(QSharedPointer::create(this)); } TestAspect::TestAspect(TestAspectPrivate &dd, QObject *parent) diff --git a/tests/auto/render/raycastingjob/tst_raycastingjob.cpp b/tests/auto/render/raycastingjob/tst_raycastingjob.cpp index 1ff899936..eaf85f5b6 100644 --- a/tests/auto/render/raycastingjob/tst_raycastingjob.cpp +++ b/tests/auto/render/raycastingjob/tst_raycastingjob.cpp @@ -285,7 +285,7 @@ private Q_SLOTS: initializeJob(&rayCastingJob, test.data()); bool earlyReturn = !rayCastingJob.runHelper(); - rayCastingJob.postFrame(test->aspectManager()); + Qt3DCore::QAspectJobPrivate::get(&rayCastingJob)->postFrame(test->aspectManager()); QCoreApplication::processEvents(); // THEN @@ -345,7 +345,7 @@ private Q_SLOTS: initializeJob(&rayCastingJob, test.data()); bool earlyReturn = !rayCastingJob.runHelper(); - rayCastingJob.postFrame(test->aspectManager()); + Qt3DCore::QAspectJobPrivate::get(&rayCastingJob)->postFrame(test->aspectManager()); QCoreApplication::processEvents(); // THEN -- cgit v1.2.3 From d521b994450f0a4febbd789ba66701ba24fdbe22 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Tue, 22 Oct 2019 06:56:06 +0100 Subject: Update jobs to remove post FF changes Made the d_ptr private again. Change-Id: Ia5ba23b03cd22290d5c922e9a1c657a67ff98977 Reviewed-by: Paul Lemire --- src/animation/backend/abstractevaluateclipanimatorjob.cpp | 2 +- src/animation/backend/abstractevaluateclipanimatorjob_p.h | 3 --- src/animation/backend/loadanimationclipjob.cpp | 2 +- src/animation/backend/loadanimationclipjob_p.h | 2 -- src/core/jobs/qaspectjob.cpp | 5 +++++ src/core/jobs/qaspectjob.h | 2 +- src/core/jobs/qaspectjob_p.h | 4 ++++ src/input/backend/assignkeyboardfocusjob.cpp | 2 +- src/input/backend/assignkeyboardfocusjob_p.h | 2 -- src/input/backend/axisaccumulatorjob.cpp | 2 +- src/input/backend/axisaccumulatorjob_p.h | 2 -- src/input/backend/keyeventdispatcherjob.cpp | 2 +- src/input/backend/keyeventdispatcherjob_p.h | 2 -- src/input/backend/loadproxydevicejob.cpp | 2 +- src/input/backend/loadproxydevicejob_p.h | 2 -- src/input/backend/mouseeventdispatcherjob.cpp | 2 +- src/input/backend/mouseeventdispatcherjob_p.h | 2 -- src/input/backend/updateaxisactionjob.cpp | 4 ++-- src/input/backend/updateaxisactionjob_p.h | 2 -- src/render/jobs/loadbufferjob.cpp | 4 ++-- src/render/jobs/loadbufferjob_p.h | 3 --- src/render/jobs/loadgeometryjob.cpp | 2 +- src/render/jobs/loadgeometryjob_p.h | 3 --- src/render/jobs/loadscenejob.cpp | 2 +- src/render/jobs/loadscenejob_p.h | 1 - src/render/jobs/loadskeletonjob.cpp | 4 ++-- src/render/jobs/loadskeletonjob_p.h | 3 --- src/render/jobs/pickboundingvolumejob.cpp | 4 ++-- src/render/jobs/pickboundingvolumejob_p.h | 2 -- src/render/jobs/raycastingjob.cpp | 2 +- src/render/jobs/raycastingjob_p.h | 2 -- src/render/jobs/sendbuffercapturejob.cpp | 8 ++++---- src/render/jobs/sendbuffercapturejob_p.h | 1 - src/render/jobs/updatelevelofdetailjob.cpp | 2 +- src/render/jobs/updatelevelofdetailjob_p.h | 2 -- src/render/jobs/updateworldtransformjob.cpp | 2 +- src/render/jobs/updateworldtransformjob_p.h | 1 - 37 files changed, 34 insertions(+), 60 deletions(-) diff --git a/src/animation/backend/abstractevaluateclipanimatorjob.cpp b/src/animation/backend/abstractevaluateclipanimatorjob.cpp index 5267d4526..e3c8e9e40 100644 --- a/src/animation/backend/abstractevaluateclipanimatorjob.cpp +++ b/src/animation/backend/abstractevaluateclipanimatorjob.cpp @@ -75,7 +75,7 @@ void AbstractEvaluateClipAnimatorJob::setPostFrameData(const AnimationRecord &re }), mainThreadCB.end()); // Should now only have callbacks to be called on main thread - Q_D(AbstractEvaluateClipAnimatorJob); + Q_DJOB(AbstractEvaluateClipAnimatorJob); d->m_record = record; d->m_callbacks = mainThreadCB; } diff --git a/src/animation/backend/abstractevaluateclipanimatorjob_p.h b/src/animation/backend/abstractevaluateclipanimatorjob_p.h index 2a8914faa..7027a8639 100644 --- a/src/animation/backend/abstractevaluateclipanimatorjob_p.h +++ b/src/animation/backend/abstractevaluateclipanimatorjob_p.h @@ -64,9 +64,6 @@ protected: AbstractEvaluateClipAnimatorJob(); void setPostFrameData(const AnimationRecord &record, const QVector &callbacks); - -private: - Q_DECLARE_PRIVATE(AbstractEvaluateClipAnimatorJob) }; } // Animation diff --git a/src/animation/backend/loadanimationclipjob.cpp b/src/animation/backend/loadanimationclipjob.cpp index 93d4c2d9d..86d7edf87 100644 --- a/src/animation/backend/loadanimationclipjob.cpp +++ b/src/animation/backend/loadanimationclipjob.cpp @@ -85,7 +85,7 @@ void LoadAnimationClipJob::clearDirtyAnimationClips() void LoadAnimationClipJob::run() { Q_ASSERT(m_handler); - Q_D(LoadAnimationClipJob); + Q_DJOB(LoadAnimationClipJob); d->m_updatedNodes.reserve(m_animationClipHandles.size()); AnimationClipLoaderManager *animationClipManager = m_handler->animationClipLoaderManager(); diff --git a/src/animation/backend/loadanimationclipjob_p.h b/src/animation/backend/loadanimationclipjob_p.h index 07d78d416..42cf27854 100644 --- a/src/animation/backend/loadanimationclipjob_p.h +++ b/src/animation/backend/loadanimationclipjob_p.h @@ -76,8 +76,6 @@ protected: void run() override; private: - Q_DECLARE_PRIVATE(LoadAnimationClipJob) - QVector m_animationClipHandles; Handler *m_handler; }; diff --git a/src/core/jobs/qaspectjob.cpp b/src/core/jobs/qaspectjob.cpp index 318a431ac..bdb2063ba 100644 --- a/src/core/jobs/qaspectjob.cpp +++ b/src/core/jobs/qaspectjob.cpp @@ -66,6 +66,11 @@ QAspectJobPrivate *QAspectJobPrivate::get(QAspectJob *job) return job->d_func(); } +const QAspectJobPrivate *QAspectJobPrivate::get(const QAspectJob *job) +{ + return job->d_func(); +} + void QAspectJobPrivate::postFrame(QAspectManager *aspectManager) { Q_UNUSED(aspectManager) diff --git a/src/core/jobs/qaspectjob.h b/src/core/jobs/qaspectjob.h index deb8cf2ed..bd86a61e1 100644 --- a/src/core/jobs/qaspectjob.h +++ b/src/core/jobs/qaspectjob.h @@ -66,11 +66,11 @@ public: protected: explicit QAspectJob(QAspectJobPrivate &dd); - QAspectJobPrivate *d_ptr; private: Q_DISABLE_COPY(QAspectJob) Q_DECLARE_PRIVATE(QAspectJob) + QAspectJobPrivate *d_ptr; }; typedef QSharedPointer QAspectJobPtr; diff --git a/src/core/jobs/qaspectjob_p.h b/src/core/jobs/qaspectjob_p.h index b16c3cad2..5504bd936 100644 --- a/src/core/jobs/qaspectjob_p.h +++ b/src/core/jobs/qaspectjob_p.h @@ -111,6 +111,7 @@ public: virtual ~QAspectJobPrivate(); static QAspectJobPrivate *get(QAspectJob *job); + static const QAspectJobPrivate *get(const QAspectJob *job); virtual void postFrame(QAspectManager *aspectManager); @@ -122,6 +123,9 @@ public: } // Qt3D +#define Q_DJOB(Class) \ + Class##Private *d = static_cast(Qt3DCore::QAspectJobPrivate::get(this)) + #if QT_CONFIG(qt3d_profile_jobs) #include diff --git a/src/input/backend/assignkeyboardfocusjob.cpp b/src/input/backend/assignkeyboardfocusjob.cpp index 5fe329004..d5947f9c9 100644 --- a/src/input/backend/assignkeyboardfocusjob.cpp +++ b/src/input/backend/assignkeyboardfocusjob.cpp @@ -77,7 +77,7 @@ void AssignKeyboardFocusJob::setInputHandler(InputHandler *handler) void AssignKeyboardFocusJob::run() { - Q_D(AssignKeyboardFocusJob); + Q_DJOB(AssignKeyboardFocusJob); KeyboardDevice *keyboardDevice = m_inputHandler->keyboardDeviceManager()->lookupResource(m_keyboardDevice); const auto handles = m_inputHandler->keyboardInputManager()->activeHandles(); diff --git a/src/input/backend/assignkeyboardfocusjob_p.h b/src/input/backend/assignkeyboardfocusjob_p.h index 200fd72f1..87cc2fbda 100644 --- a/src/input/backend/assignkeyboardfocusjob_p.h +++ b/src/input/backend/assignkeyboardfocusjob_p.h @@ -70,8 +70,6 @@ public: void run() override; private: - Q_DECLARE_PRIVATE(AssignKeyboardFocusJob) - InputHandler *m_inputHandler; const Qt3DCore::QNodeId m_keyboardDevice; }; diff --git a/src/input/backend/axisaccumulatorjob.cpp b/src/input/backend/axisaccumulatorjob.cpp index 16a68349e..b6c1c8482 100644 --- a/src/input/backend/axisaccumulatorjob.cpp +++ b/src/input/backend/axisaccumulatorjob.cpp @@ -73,7 +73,7 @@ AxisAccumulatorJob::AxisAccumulatorJob(AxisAccumulatorManager *axisAccumulatorma void AxisAccumulatorJob::run() { - Q_D(AxisAccumulatorJob); + Q_DJOB(AxisAccumulatorJob); // Iterate over the accumulators and ask each to step the integrations const auto activeHandles = m_axisAccumulatorManager->activeHandles(); d->updates.reserve(activeHandles.size()); diff --git a/src/input/backend/axisaccumulatorjob_p.h b/src/input/backend/axisaccumulatorjob_p.h index 702004dd2..3e8122287 100644 --- a/src/input/backend/axisaccumulatorjob_p.h +++ b/src/input/backend/axisaccumulatorjob_p.h @@ -75,8 +75,6 @@ public: void run() override; private: - Q_DECLARE_PRIVATE(AxisAccumulatorJob) - AxisAccumulatorManager *m_axisAccumulatorManager; AxisManager *m_axisManager; float m_dt; diff --git a/src/input/backend/keyeventdispatcherjob.cpp b/src/input/backend/keyeventdispatcherjob.cpp index 26a35e885..31db01e53 100644 --- a/src/input/backend/keyeventdispatcherjob.cpp +++ b/src/input/backend/keyeventdispatcherjob.cpp @@ -67,7 +67,7 @@ KeyEventDispatcherJob::KeyEventDispatcherJob(Qt3DCore::QNodeId input, const QLis : QAspectJob(*new KeyEventDispatcherJobPrivate) , m_inputHandler(nullptr) { - Q_D(KeyEventDispatcherJob); + Q_DJOB(KeyEventDispatcherJob); d->m_keyboardHandler = input; d->m_events = events; SET_JOB_RUN_STAT_TYPE(this, JobTypes::KeyEventDispatcher, 0) diff --git a/src/input/backend/keyeventdispatcherjob_p.h b/src/input/backend/keyeventdispatcherjob_p.h index bd0c770d4..975dc3d31 100644 --- a/src/input/backend/keyeventdispatcherjob_p.h +++ b/src/input/backend/keyeventdispatcherjob_p.h @@ -71,8 +71,6 @@ public: void run() override; private: - Q_DECLARE_PRIVATE(KeyEventDispatcherJob) - InputHandler *m_inputHandler; }; diff --git a/src/input/backend/loadproxydevicejob.cpp b/src/input/backend/loadproxydevicejob.cpp index 69f14beae..059d14bc0 100644 --- a/src/input/backend/loadproxydevicejob.cpp +++ b/src/input/backend/loadproxydevicejob.cpp @@ -94,7 +94,7 @@ QVector LoadProxyDeviceJob::proxies() const void LoadProxyDeviceJob::run() { - Q_D(LoadProxyDeviceJob); + Q_DJOB(LoadProxyDeviceJob); d->updates.reserve(m_proxies.size()); Q_ASSERT(m_inputHandler); diff --git a/src/input/backend/loadproxydevicejob_p.h b/src/input/backend/loadproxydevicejob_p.h index 0848c8529..0a425f3a5 100644 --- a/src/input/backend/loadproxydevicejob_p.h +++ b/src/input/backend/loadproxydevicejob_p.h @@ -76,8 +76,6 @@ public: void run() final; private: - Q_DECLARE_PRIVATE(LoadProxyDeviceJob) - InputHandler *m_inputHandler; QVector m_proxies; }; diff --git a/src/input/backend/mouseeventdispatcherjob.cpp b/src/input/backend/mouseeventdispatcherjob.cpp index 0ee6862fb..b91a7b638 100644 --- a/src/input/backend/mouseeventdispatcherjob.cpp +++ b/src/input/backend/mouseeventdispatcherjob.cpp @@ -75,7 +75,7 @@ MouseEventDispatcherJob::MouseEventDispatcherJob(Qt3DCore::QNodeId input, : QAspectJob(*new MouseEventDispatcherJobPrivate) , m_inputHandler(nullptr) { - Q_D(MouseEventDispatcherJob); + Q_DJOB(MouseEventDispatcherJob); d->m_mouseInput = input; d->m_mouseEvents = mouseEvents; #if QT_CONFIG(wheelevent) diff --git a/src/input/backend/mouseeventdispatcherjob_p.h b/src/input/backend/mouseeventdispatcherjob_p.h index 696d60da4..983837446 100644 --- a/src/input/backend/mouseeventdispatcherjob_p.h +++ b/src/input/backend/mouseeventdispatcherjob_p.h @@ -76,8 +76,6 @@ public: void run() final; private: - Q_DECLARE_PRIVATE(MouseEventDispatcherJob) - InputHandler *m_inputHandler; }; diff --git a/src/input/backend/updateaxisactionjob.cpp b/src/input/backend/updateaxisactionjob.cpp index 58ed36639..5732c2a9b 100644 --- a/src/input/backend/updateaxisactionjob.cpp +++ b/src/input/backend/updateaxisactionjob.cpp @@ -89,7 +89,7 @@ void UpdateAxisActionJob::run() void UpdateAxisActionJob::updateAction(LogicalDevice *device) { - Q_D(UpdateAxisActionJob); + Q_DJOB(UpdateAxisActionJob); const auto actionIds = device->actions(); d->m_triggeredActions.reserve(actionIds.size()); @@ -117,7 +117,7 @@ bool UpdateAxisActionJob::processActionInput(const Qt3DCore::QNodeId actionInput void UpdateAxisActionJob::updateAxis(LogicalDevice *device) { - Q_D(UpdateAxisActionJob); + Q_DJOB(UpdateAxisActionJob); const auto axisIds = device->axes(); d->m_triggeredAxis.reserve(axisIds.size()); diff --git a/src/input/backend/updateaxisactionjob_p.h b/src/input/backend/updateaxisactionjob_p.h index 040ed9775..39b5f5cf6 100644 --- a/src/input/backend/updateaxisactionjob_p.h +++ b/src/input/backend/updateaxisactionjob_p.h @@ -76,8 +76,6 @@ public: void run() final; private: - Q_DECLARE_PRIVATE(UpdateAxisActionJob) - void updateAction(LogicalDevice *device); bool processActionInput(const Qt3DCore::QNodeId actionInputId); void updateAxis(LogicalDevice *device); diff --git a/src/render/jobs/loadbufferjob.cpp b/src/render/jobs/loadbufferjob.cpp index c9cbb623d..68e92cfa7 100644 --- a/src/render/jobs/loadbufferjob.cpp +++ b/src/render/jobs/loadbufferjob.cpp @@ -68,7 +68,7 @@ LoadBufferJob::LoadBufferJob(const HBuffer &handle) , m_handle(handle) , m_nodeManagers(nullptr) { - SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadBuffer, 0); + SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadBuffer, 0) } LoadBufferJob::~LoadBufferJob() @@ -77,7 +77,7 @@ LoadBufferJob::~LoadBufferJob() void LoadBufferJob::run() { - Q_D(LoadBufferJob); + Q_DJOB(LoadBufferJob); // Let's leave it for the moment until this has been properly tested qCDebug(Jobs) << Q_FUNC_INFO; Buffer *buffer = m_nodeManagers->data(m_handle); diff --git a/src/render/jobs/loadbufferjob_p.h b/src/render/jobs/loadbufferjob_p.h index e86e4f835..884870a62 100644 --- a/src/render/jobs/loadbufferjob_p.h +++ b/src/render/jobs/loadbufferjob_p.h @@ -77,9 +77,6 @@ public: protected: HBuffer m_handle; NodeManagers *m_nodeManagers; - -private: - Q_DECLARE_PRIVATE(LoadBufferJob) }; typedef QSharedPointer LoadBufferJobPtr; diff --git a/src/render/jobs/loadgeometryjob.cpp b/src/render/jobs/loadgeometryjob.cpp index 88930038a..3d32f7d4e 100644 --- a/src/render/jobs/loadgeometryjob.cpp +++ b/src/render/jobs/loadgeometryjob.cpp @@ -75,7 +75,7 @@ LoadGeometryJob::~LoadGeometryJob() void LoadGeometryJob::run() { - Q_D(LoadGeometryJob); + Q_DJOB(LoadGeometryJob); GeometryRenderer *geometryRenderer = m_nodeManagers->geometryRendererManager()->data(m_handle); if (geometryRenderer != nullptr) d->m_updates.push_back({ geometryRenderer->peerId(), geometryRenderer->executeFunctor() }); diff --git a/src/render/jobs/loadgeometryjob_p.h b/src/render/jobs/loadgeometryjob_p.h index 998d543ac..869abbe18 100644 --- a/src/render/jobs/loadgeometryjob_p.h +++ b/src/render/jobs/loadgeometryjob_p.h @@ -76,9 +76,6 @@ protected: void run() override; HGeometryRenderer m_handle; NodeManagers *m_nodeManagers; - -private: - Q_DECLARE_PRIVATE(LoadGeometryJob) }; typedef QSharedPointer LoadGeometryJobPtr; diff --git a/src/render/jobs/loadscenejob.cpp b/src/render/jobs/loadscenejob.cpp index f858f82e3..22d5da887 100644 --- a/src/render/jobs/loadscenejob.cpp +++ b/src/render/jobs/loadscenejob.cpp @@ -139,7 +139,7 @@ void LoadSceneJob::run() } } - Q_D(LoadSceneJob); + Q_DJOB(LoadSceneJob); d->m_sceneSubtree = sceneSubTree; d->m_status = finalStatus; diff --git a/src/render/jobs/loadscenejob_p.h b/src/render/jobs/loadscenejob_p.h index 3675d94c1..79c8a2935 100644 --- a/src/render/jobs/loadscenejob_p.h +++ b/src/render/jobs/loadscenejob_p.h @@ -113,7 +113,6 @@ private: Qt3DCore::QEntity *tryLoadScene(QSceneLoader::Status &finalStatus, const QStringList &extensions, const std::function &importerSetupFunc); - Q_DECLARE_PRIVATE(LoadSceneJob) }; typedef QSharedPointer LoadSceneJobPtr; diff --git a/src/render/jobs/loadskeletonjob.cpp b/src/render/jobs/loadskeletonjob.cpp index 8d0d47fb9..ddd59f5d7 100644 --- a/src/render/jobs/loadskeletonjob.cpp +++ b/src/render/jobs/loadskeletonjob.cpp @@ -75,7 +75,7 @@ LoadSkeletonJob::LoadSkeletonJob(const HSkeleton &handle) void LoadSkeletonJob::run() { - Q_D(LoadSkeletonJob); + Q_DJOB(LoadSkeletonJob); d->m_backendSkeleton = nullptr; Skeleton *skeleton = m_nodeManagers->skeletonManager()->data(m_handle); @@ -120,7 +120,7 @@ void LoadSkeletonJob::loadSkeleton(Skeleton *skeleton) void LoadSkeletonJob::loadSkeletonFromUrl(Skeleton *skeleton) { - Q_D(LoadSkeletonJob); + Q_DJOB(LoadSkeletonJob); using namespace Qt3DCore; diff --git a/src/render/jobs/loadskeletonjob_p.h b/src/render/jobs/loadskeletonjob_p.h index 0cc09da3d..5ea4912ee 100644 --- a/src/render/jobs/loadskeletonjob_p.h +++ b/src/render/jobs/loadskeletonjob_p.h @@ -88,9 +88,6 @@ protected: HSkeleton m_handle; NodeManagers *m_nodeManagers; - -private: - Q_DECLARE_PRIVATE(LoadSkeletonJob) }; typedef QSharedPointer LoadSkeletonJobPtr; diff --git a/src/render/jobs/pickboundingvolumejob.cpp b/src/render/jobs/pickboundingvolumejob.cpp index 2973ee100..ae0cb2350 100644 --- a/src/render/jobs/pickboundingvolumejob.cpp +++ b/src/render/jobs/pickboundingvolumejob.cpp @@ -380,7 +380,7 @@ void PickBoundingVolumeJob::dispatchPickEvents(const QMouseEvent &event, bool allHitsRequested, Qt3DCore::QNodeId viewportNodeId) { - Q_D(PickBoundingVolumeJob); + Q_DJOB(PickBoundingVolumeJob); ObjectPicker *lastCurrentPicker = m_manager->objectPickerManager()->data(m_currentPicker); // If we have hits @@ -541,7 +541,7 @@ void PickBoundingVolumeJob::dispatchPickEvents(const QMouseEvent &event, void PickBoundingVolumeJob::clearPreviouslyHoveredPickers() { - Q_D(PickBoundingVolumeJob); + Q_DJOB(PickBoundingVolumeJob); for (const HObjectPicker &pickHandle : qAsConst(m_hoveredPickersToClear)) { ObjectPicker *pick = m_manager->objectPickerManager()->data(pickHandle); diff --git a/src/render/jobs/pickboundingvolumejob_p.h b/src/render/jobs/pickboundingvolumejob_p.h index 49b11b775..751d0be7b 100644 --- a/src/render/jobs/pickboundingvolumejob_p.h +++ b/src/render/jobs/pickboundingvolumejob_p.h @@ -102,8 +102,6 @@ protected: Qt3DCore::QNodeId viewportNodeId); private: - Q_DECLARE_PRIVATE(PickBoundingVolumeJob) - void clearPreviouslyHoveredPickers(); QList> m_pendingMouseEvents; diff --git a/src/render/jobs/raycastingjob.cpp b/src/render/jobs/raycastingjob.cpp index 380447873..a6f172b86 100644 --- a/src/render/jobs/raycastingjob.cpp +++ b/src/render/jobs/raycastingjob.cpp @@ -273,7 +273,7 @@ void RayCastingJob::dispatchHits(RayCaster *rayCaster, const PickingUtils::HitLi }; } - Q_D(RayCastingJob); + Q_DJOB(RayCastingJob); d->dispatches.push_back({rayCaster, hits}); } diff --git a/src/render/jobs/raycastingjob_p.h b/src/render/jobs/raycastingjob_p.h index 4b8b91ad5..ba0e2f309 100644 --- a/src/render/jobs/raycastingjob_p.h +++ b/src/render/jobs/raycastingjob_p.h @@ -82,8 +82,6 @@ protected: void dispatchHits(RayCaster *rayCaster, const PickingUtils::HitList &sphereHits); private: - Q_DECLARE_PRIVATE(RayCastingJob) - bool m_castersDirty; bool m_oneEnabledAtLeast; }; diff --git a/src/render/jobs/sendbuffercapturejob.cpp b/src/render/jobs/sendbuffercapturejob.cpp index 3fa185684..889a86c68 100644 --- a/src/render/jobs/sendbuffercapturejob.cpp +++ b/src/render/jobs/sendbuffercapturejob.cpp @@ -69,7 +69,7 @@ SendBufferCaptureJob::SendBufferCaptureJob() : Qt3DCore::QAspectJob(*new SendBufferCaptureJobPrivate) , m_nodeManagers(nullptr) { - SET_JOB_RUN_STAT_TYPE(this, JobTypes::SendBufferCapture, 0); + SET_JOB_RUN_STAT_TYPE(this, JobTypes::SendBufferCapture, 0) } SendBufferCaptureJob::~SendBufferCaptureJob() @@ -79,7 +79,7 @@ SendBufferCaptureJob::~SendBufferCaptureJob() // Called from SubmitRenderView while rendering void SendBufferCaptureJob::addRequest(QPair request) { - Q_D(SendBufferCaptureJob); + Q_DJOB(SendBufferCaptureJob); QMutexLocker locker(&d->m_mutex); d->m_buffersToCapture.push_back(request); } @@ -87,7 +87,7 @@ void SendBufferCaptureJob::addRequest(QPair reque // Called by aspect thread jobs to execute (we may still be rendering at this point) bool SendBufferCaptureJob::hasRequests() const { - Q_D(const SendBufferCaptureJob); + Q_DJOB(const SendBufferCaptureJob); QMutexLocker locker(&d->m_mutex); return d->m_buffersToCapture.size() > 0; } @@ -95,7 +95,7 @@ bool SendBufferCaptureJob::hasRequests() const void SendBufferCaptureJob::run() { Q_ASSERT(m_nodeManagers); - Q_D(SendBufferCaptureJob); + Q_DJOB(SendBufferCaptureJob); QMutexLocker locker(&d->m_mutex); for (const QPair &pendingCapture : qAsConst(d->m_buffersToCapture)) { Buffer *buffer = m_nodeManagers->bufferManager()->lookupResource(pendingCapture.first); diff --git a/src/render/jobs/sendbuffercapturejob_p.h b/src/render/jobs/sendbuffercapturejob_p.h index 3b9f5d12b..ce797f0a9 100644 --- a/src/render/jobs/sendbuffercapturejob_p.h +++ b/src/render/jobs/sendbuffercapturejob_p.h @@ -83,7 +83,6 @@ public: void run() final; private: - Q_DECLARE_PRIVATE(SendBufferCaptureJob) NodeManagers *m_nodeManagers; }; diff --git a/src/render/jobs/updatelevelofdetailjob.cpp b/src/render/jobs/updatelevelofdetailjob.cpp index 0a28b7628..9ac923d8b 100644 --- a/src/render/jobs/updatelevelofdetailjob.cpp +++ b/src/render/jobs/updatelevelofdetailjob.cpp @@ -248,7 +248,7 @@ void UpdateLevelOfDetailJob::setFrameGraphRoot(FrameGraphNode *frameGraphRoot) void UpdateLevelOfDetailJob::run() { - Q_D(UpdateLevelOfDetailJob); + Q_DJOB(UpdateLevelOfDetailJob); Q_ASSERT(m_frameGraphRoot && m_root && m_manager); diff --git a/src/render/jobs/updatelevelofdetailjob_p.h b/src/render/jobs/updatelevelofdetailjob_p.h index 9ac5cf0e9..e0f9bd064 100644 --- a/src/render/jobs/updatelevelofdetailjob_p.h +++ b/src/render/jobs/updatelevelofdetailjob_p.h @@ -82,8 +82,6 @@ public: Entity *root() const { return m_root; } private: - Q_DECLARE_PRIVATE(UpdateLevelOfDetailJob) - NodeManagers *m_manager; FrameGraphNode *m_frameGraphRoot; Entity *m_root; diff --git a/src/render/jobs/updateworldtransformjob.cpp b/src/render/jobs/updateworldtransformjob.cpp index fc661a7ce..e3487e68b 100644 --- a/src/render/jobs/updateworldtransformjob.cpp +++ b/src/render/jobs/updateworldtransformjob.cpp @@ -128,7 +128,7 @@ void UpdateWorldTransformJob::run() // TODO: Parallelise this on each level using a parallel_for // implementation. - Q_D(UpdateWorldTransformJob); + Q_DJOB(UpdateWorldTransformJob); qCDebug(Jobs) << "Entering" << Q_FUNC_INFO << QThread::currentThread(); Matrix4x4 parentTransform; diff --git a/src/render/jobs/updateworldtransformjob_p.h b/src/render/jobs/updateworldtransformjob_p.h index e7ff592de..ded501a07 100644 --- a/src/render/jobs/updateworldtransformjob_p.h +++ b/src/render/jobs/updateworldtransformjob_p.h @@ -78,7 +78,6 @@ public: private: Entity *m_node; NodeManagers *m_manager; - Q_DECLARE_PRIVATE(UpdateWorldTransformJob) }; typedef QSharedPointer UpdateWorldTransformJobPtr; -- cgit v1.2.3 From b9057e508c85c5b1b12efea57daf9dd6f98971d3 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Wed, 23 Oct 2019 08:53:46 +0100 Subject: Fix Scene2D initialization The entity that Scene2D uses to track events may not exist yet when Scene2D is initialized. If so, mark QScene2D as dirty again so it gets updated again on the next frame. Change-Id: I0649a4073afca38ff569cd683d8f2b96c1899ba8 Reviewed-by: Paul Lemire --- src/quick3d/quick3dscene2d/items/scene2d.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/quick3d/quick3dscene2d/items/scene2d.cpp b/src/quick3d/quick3dscene2d/items/scene2d.cpp index b8f99ae1b..bfd6ce7ef 100644 --- a/src/quick3d/quick3dscene2d/items/scene2d.cpp +++ b/src/quick3d/quick3dscene2d/items/scene2d.cpp @@ -208,11 +208,16 @@ void Scene2D::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) if (!entity) return; - registerObjectPickerEvents(entity); + if (registerObjectPickerEvents(entity)) + m_entities.push_back(id); + else + Qt3DCore::QNodePrivate::get(const_cast(frontEnd))->update(); } - for (const auto &id: removedEntities) + for (const auto &id: removedEntities) { + m_entities.removeOne(id); unregisterObjectPickerEvents(id); - m_entities = ids; + } + std::sort(std::begin(m_entities), std::end(m_entities)); if (firstTime) setSharedObject(dnode->m_renderManager->m_sharedObject); @@ -428,8 +433,11 @@ bool Scene2D::registerObjectPickerEvents(Qt3DCore::QEntity *qentity) { Entity *entity = nullptr; if (!resourceAccessor()->accessResource(RenderBackendResourceAccessor::EntityHandle, - qentity->id(), (void**)&entity, nullptr)) + qentity->id(), (void**)&entity, nullptr)) { + qCWarning(Qt3DRender::Quick::Scene2D) << Q_FUNC_INFO + << "Entity not yet available in backend"; return false; + } if (!entity->containsComponentsOfType() || !entity->containsComponentsOfType()) { -- cgit v1.2.3 From 3b649e32327fa561c75b5ccb762f12e8fd8c18a9 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 21 Oct 2019 14:49:28 +0200 Subject: planets-qml: fix flickerring by using less precise scale unit Essentially use 10^3 KM instead of KM so that we don't end up with too much precision in the positions which can then result in the camera flickering when the viewMatrix is computed for rendering Change-Id: Id2f878c2e1ccd22a2e72a3494d2e7f623f2b4eb6 Reviewed-by: Mike Krus --- examples/qt3d/planets-qml/SolarSystem.qml | 14 +++++++------- examples/qt3d/planets-qml/planets.js | 32 ++++++++++++++++--------------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/examples/qt3d/planets-qml/SolarSystem.qml b/examples/qt3d/planets-qml/SolarSystem.qml index 8c0cfccd4..2b56237f5 100644 --- a/examples/qt3d/planets-qml/SolarSystem.qml +++ b/examples/qt3d/planets-qml/SolarSystem.qml @@ -133,8 +133,8 @@ Entity { projectionType: CameraLens.PerspectiveProjection fieldOfView: 45 aspectRatio: width / height - nearPlane: 2500000.0 - farPlane: 20000000.0 + nearPlane: 2500.0 + farPlane: 20000.0 position: defaultCameraPosition upVector: defaultUp viewCenter: Qt.vector3d( xLookAtOffset, yLookAtOffset, zLookAtOffset ) @@ -211,9 +211,9 @@ Entity { //saturnRing.makeRing() //uranusRing.makeRing() saturnRingOuterRadius = planetData[Planets.SATURN].radius + Planets.saturnOuterRadius - saturnRingInnerRadius = planetData[Planets.SATURN].radius + 6.630 + saturnRingInnerRadius = planetData[Planets.SATURN].radius + 0.006630 uranusRingOuterRadius = planetData[Planets.URANUS].radius + Planets.uranusOuterRadius - uranusRingInnerRadius = planetData[Planets.URANUS].radius + 2 + uranusRingInnerRadius = planetData[Planets.URANUS].radius + 0.002 ready = true changeScale(1200) changeSpeed(0.2) @@ -286,7 +286,7 @@ Entity { // Limit minimum scaling in focus mode to avoid jitter caused by rounding errors if (actualScale <= focusedMinimumScale) { planetScale = focusedMinimumScale - changeScale(focusedMinimumScale, true) + changeScale(focusedMinimumSfocusedPlanetcale, true) } focusedScaling = true } else if (focusedScaling === true) { @@ -423,7 +423,7 @@ Entity { return var scaling = setScale(scale, focused) - sun.r = planetData[Planets.SUN].radius * scaling / 100 + sun.r = planetData[Planets.SUN].radius * scaling / 10 mercury.r = planetData[Planets.MERCURY].radius * scaling venus.r = planetData[Planets.VENUS].radius * scaling earth.r = planetData[Planets.EARTH].radius * scaling @@ -511,7 +511,7 @@ Entity { } property Transform transformStarfield: Transform { - scale: 8500000 + scale: 8500 translation: Qt.vector3d(0, 0, 0) } diff --git a/examples/qt3d/planets-qml/planets.js b/examples/qt3d/planets-qml/planets.js index f64ec3149..b3517ac5a 100644 --- a/examples/qt3d/planets-qml/planets.js +++ b/examples/qt3d/planets-qml/planets.js @@ -115,11 +115,13 @@ function planetIndex(planetName) { var planets = []; // Planet data info -var solarDistance = 2600000; -var saturnOuterRadius = 120.700; -var uranusOuterRadius = 40; +// Units are in 10^3 KM -var auScale = 149597.870700; // AU in thousands of kilometers +var solarDistance = 2600.000; +var saturnOuterRadius = 0.120700; +var uranusOuterRadius = 0.040; + +var auScale = 149.597870700; // 0.001 AU (in thousands of kilometers) function loadPlanetData() { @@ -136,11 +138,11 @@ function loadPlanetData() { // centerOfOrbit - the planet in the center of the orbit // (orbital elements based on http://www.stjarnhimlen.se/comp/ppcomp.html) - var sun = { radius: 694.439, tilt: 63.87, period: 25.05, x: 0, y: 0, z: 0, + var sun = { radius: 0.694439, tilt: 63.87, period: 25.05, x: 0, y: 0, z: 0, roll: 0 }; planets.push(sun); var mercury = { - radius: 2.433722, tilt: 0.04, N1: 48.3313, N2: 0.0000324587, + radius: 0.002433722, tilt: 0.04, N1: 48.3313, N2: 0.0000324587, i1: 7.0047, i2: 0.0000000500, w1: 29.1241, w2: 0.0000101444, a1: 0.387098, a2: 0, e1: 0.205635, e2: 0.000000000559, M1: 168.6562, M2: 4.0923344368, period: 58.646, x: 0, y: 0, z: 0, @@ -148,7 +150,7 @@ function loadPlanetData() { }; planets.push(mercury); var venus = { - radius: 6.046079, tilt: 177.36, N1: 76.6799, N2: 0.0000246590, + radius: 0.006046079, tilt: 177.36, N1: 76.6799, N2: 0.0000246590, i1: 3.3946, i2: 0.0000000275, w1: 54.8910, w2: 0.0000138374, a1: 0.723330, a2: 0, e1: 0.006773, e2: -0.000000001302, M1: 48.0052, M2: 1.6021302244, period: 243.0185, x: 0, y: 0, z: 0, @@ -156,7 +158,7 @@ function loadPlanetData() { }; planets.push(venus); var earth = { - radius: 6.371, tilt: 25.44, N1: 174.873, N2: 0, + radius: 0.006371, tilt: 25.44, N1: 174.873, N2: 0, i1: 0.00005, i2: 0, w1: 102.94719, w2: 0, a1: 1, a2: 0, e1: 0.01671022, e2: 0, M1: 357.529, M2: 0.985608, period: 0.997, x: 0, y: 0, z: 0, @@ -164,7 +166,7 @@ function loadPlanetData() { }; planets.push(earth); var mars = { - radius: 3.389372, tilt: 25.19, N1: 49.5574, N2: 0.0000211081, + radius: 0.003389372, tilt: 25.19, N1: 49.5574, N2: 0.0000211081, i1: 1.8497, i2: -0.0000000178, w1: 286.5016, w2: 0.0000292961, a1: 1.523688, a2: 0, e1: 0.093405, e2: 0.000000002516, M1: 18.6021, M2: 0.5240207766, period: 1.025957, x: 0, y: 0, z: 0, @@ -172,7 +174,7 @@ function loadPlanetData() { }; planets.push(mars); var jupiter = { - radius: 71.41254, tilt: 3.13, N1: 100.4542, N2: 0.0000276854, + radius: 0.07141254, tilt: 3.13, N1: 100.4542, N2: 0.0000276854, i1: 1.3030, i2: -0.0000001557, w1: 273.8777, w2: 0.0000164505, a1: 5.20256, a2: 0, e1: 0.048498, e2: 0.000000004469, M1: 19.8950, M2: 0.0830853001, period: 0.4135, x: 0, y: 0, z: 0, @@ -180,7 +182,7 @@ function loadPlanetData() { }; planets.push(jupiter); var saturn = { - radius: 60.19958, tilt: 26.73, N1: 113.6634, N2: 0.0000238980, + radius: 0.06019958, tilt: 26.73, N1: 113.6634, N2: 0.0000238980, i1: 2.4886, i2: -0.0000001081, w1: 339.3939, w2: 0.0000297661, a1: 9.55475, a2: 0, e1: 0.055546, e2: -0.000000009499, M1: 316.9670, M2: 0.0334442282, period: 0.4395, x: 0, y: 0, z: 0, @@ -188,7 +190,7 @@ function loadPlanetData() { }; planets.push(saturn); var uranus = { - radius: 25.5286, tilt: 97.77, N1: 74.0005, N2: 0.000013978, + radius: 0.0255286, tilt: 97.77, N1: 74.0005, N2: 0.000013978, i1: 0.7733, i2: 0.000000019, w1: 96.6612, w2: 0.000030565, a1: 19.18171, a2: -0.0000000155, e1: 0.047318, e2: 0.00000000745, M1: 142.5905, M2: 0.011725806, period: 0.71833, x: 0, y: 0, z: 0, @@ -196,7 +198,7 @@ function loadPlanetData() { }; planets.push(uranus); var neptune = { - radius: 24.73859, tilt: 28.32, N1: 131.7806, N2: 0.000030173, + radius: 0.02473859, tilt: 28.32, N1: 131.7806, N2: 0.000030173, i1: 1.7700, i2: -0.000000255, w1: 272.8461, w2: 0.000006027, a1: 30.05826, a2: 0.00000003313, e1: 0.008606, e2: 0.00000000215, M1: 260.2471, M2: 0.005995147, period: 0.6713, x: 0, y: 0, z: 0, @@ -204,7 +206,7 @@ function loadPlanetData() { }; planets.push(neptune); var moon = { - radius: 1.5424, tilt: 28.32, N1: 125.1228, N2: -0.0529538083, + radius: 0.0015424, tilt: 28.32, N1: 125.1228, N2: -0.0529538083, i1: 5.1454, i2: 0, w1: 318.0634, w2: 0.1643573223, a1: 0.273, a2: 0, e1: 0.054900, e2: 0, M1: 115.3654, M2: 13.0649929509, period: 27.321582, x: 0, y: 0, z: 0, @@ -224,7 +226,7 @@ function getOuterRadius(planet) { } else if (planet === URANUS) { outerRadius =+ uranusOuterRadius; } else if (planet === SUN) { - outerRadius = planets[planet]["radius"] / 100; + outerRadius = planets[planet]["radius"] / 10; } } -- cgit v1.2.3 From ed97ebb1884b36f7e71b295ebae99fd962832bd3 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Tue, 15 Oct 2019 09:05:05 +0200 Subject: Add manual test to check manual trigger mode on ComputeCommands Change-Id: I8048795277828ecba7d46dbc846685e606b2b8b9 Reviewed-by: Mike Krus --- tests/manual/compute-manual/ComputeFrameGraph.qml | 91 ++++++++++ tests/manual/compute-manual/ComputeMaterial.qml | 118 +++++++++++++ tests/manual/compute-manual/ParticlesScene.qml | 200 ++++++++++++++++++++++ tests/manual/compute-manual/compute-manual.pro | 14 ++ tests/manual/compute-manual/compute-manual.qrc | 11 ++ tests/manual/compute-manual/main.cpp | 66 +++++++ tests/manual/compute-manual/main.qml | 109 ++++++++++++ tests/manual/compute-manual/particles.comp | 31 ++++ tests/manual/compute-manual/particles.frag | 33 ++++ tests/manual/compute-manual/particles.vert | 27 +++ tests/manual/manual.pro | 2 + 11 files changed, 702 insertions(+) create mode 100644 tests/manual/compute-manual/ComputeFrameGraph.qml create mode 100644 tests/manual/compute-manual/ComputeMaterial.qml create mode 100644 tests/manual/compute-manual/ParticlesScene.qml create mode 100644 tests/manual/compute-manual/compute-manual.pro create mode 100644 tests/manual/compute-manual/compute-manual.qrc create mode 100644 tests/manual/compute-manual/main.cpp create mode 100644 tests/manual/compute-manual/main.qml create mode 100644 tests/manual/compute-manual/particles.comp create mode 100644 tests/manual/compute-manual/particles.frag create mode 100644 tests/manual/compute-manual/particles.vert diff --git a/tests/manual/compute-manual/ComputeFrameGraph.qml b/tests/manual/compute-manual/ComputeFrameGraph.qml new file mode 100644 index 000000000..47d57161c --- /dev/null +++ b/tests/manual/compute-manual/ComputeFrameGraph.qml @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 + +Viewport { + property alias camera: selector.camera + + RenderSurfaceSelector { + id: surfaceSelector + + // Clear Buffer + ClearBuffers { + buffers: ClearBuffers.ColorDepthBuffer + NoDraw {} + } + + // Compute Pass + DispatchCompute { + // 1024 x 1024 particles + // We will launch 1024 local workgroup that will work + // on 1024 particles each + workGroupX: 1024; workGroupY: 1; workGroupZ: 1 + TechniqueFilter { + matchAll: [ + FilterKey { name: "type"; value: "compute"} + ] + } + } + + // Draw particles from buffer computed in the Compute Pass + CameraSelector { + id: selector + TechniqueFilter { + MemoryBarrier { waitFor: MemoryBarrier.VertexAttributeArray } + matchAll: [ + FilterKey { name: "type"; value: "draw"} + ] + } + } + } +} + diff --git a/tests/manual/compute-manual/ComputeMaterial.qml b/tests/manual/compute-manual/ComputeMaterial.qml new file mode 100644 index 000000000..9116a8b66 --- /dev/null +++ b/tests/manual/compute-manual/ComputeMaterial.qml @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 + +Material { + property Buffer dataBuffer; + property real particleStep: 0.4 + property real finalCollisionFactor: 0.2 + + parameters: [ + Parameter { name: "particleStep"; value: particleStep }, + Parameter { name: "finalCollisionFactor"; value: finalCollisionFactor } + ] + + ShaderProgram { + id: computeShader + computeShaderCode: loadSource("qrc:/particles.comp") + } + + ShaderProgram { + id: drawShader + vertexShaderCode: loadSource("qrc:/particles.vert") + fragmentShaderCode: loadSource("qrc:/particles.frag") + } + + effect: Effect { + techniques: [ + Technique { + renderPasses: [ + RenderPass { + shaderProgram: computeShader + // We set the buffer as the parameter data + parameters: [ + Parameter { name: "Particles"; value: dataBuffer } + ] + } + ] + filterKeys: [ + FilterKey { name: "type"; value: "compute" } + ] + graphicsApiFilter { + api: GraphicsApiFilter.OpenGL + profile: GraphicsApiFilter.CoreProfile + majorVersion: 4 + minorVersion: 3 + } + }, + Technique { + renderPasses: [ + RenderPass { + shaderProgram: drawShader + // We assume the mesh to be drawn will also receive + // Vertex buffers attributes that will be used to position and color + } + ] + filterKeys: [ + FilterKey { name: "type"; value: "draw" } + ] + graphicsApiFilter { + api: GraphicsApiFilter.OpenGL + profile: GraphicsApiFilter.CoreProfile + majorVersion: 4 + minorVersion: 3 + } + } + ] // techniques + } +} + diff --git a/tests/manual/compute-manual/ParticlesScene.qml b/tests/manual/compute-manual/ParticlesScene.qml new file mode 100644 index 000000000..68572f6b4 --- /dev/null +++ b/tests/manual/compute-manual/ParticlesScene.qml @@ -0,0 +1,200 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 +import Qt3D.Extras 2.14 +import Qt3D.Input 2.14 + +Entity { + + property alias computeMode: particlesComputeJob.runType + + function triggerCompute(frames) { + particlesComputeJob.trigger(frames) + } + + components: [ + RenderSettings { + ComputeFrameGraph { + camera: sceneCamera + } + // explicitly set RenderingPolicy to AlwaysRender, as changes in the + // scene won't be reflected in actual Qt scene-graph changes (due to + // GPU compute calls) + renderPolicy: RenderSettings.Always + }, + InputSettings {} + ] + + FirstPersonCameraController { camera: sceneCamera } + + Camera { + id: sceneCamera + projectionType: CameraLens.PerspectiveProjection + viewCenter: Qt.vector3d(0, 0, 0) + position: Qt.vector3d(0, 20, -800) + nearPlane: 0.1 + farPlane: 1000 + fieldOfView: 60 + } + + property int particlesCount: 1024 * 1024 + readonly property int floatSize: 4 + + function buildParticlesBuffer() { + var byteSizeOfParticleData = 8; + var bufferData = new Float32Array(particlesCount * byteSizeOfParticleData); + for (var x = 0; x < 1024; ++x) { + for (var z = 0; z < 1024; ++z) { + var i = x * 1024 + z; + var positionIdx = i * byteSizeOfParticleData; + var colorIdx = i * byteSizeOfParticleData + 8; + + bufferData[positionIdx] = -1024 + x * 2; + bufferData[positionIdx + 1] = 0; + bufferData[positionIdx + 2] = -1024 + z * 2; + bufferData[positionIdx + 3] = 1.0; + + bufferData[colorIdx] = 0.25 + Math.sin(x / 1024) * 0.75; + bufferData[colorIdx + 1] = 0.25 + Math.sin(z / 1024) * 0.75; + bufferData[colorIdx + 2] = 0.25 + Math.sin(x / 1024) * 0.75; + bufferData[colorIdx + 3] = 1.0; + } + } + return bufferData + } + + Buffer { + id: particleBuffer + type: Buffer.VertexBuffer + // struct ParticleData + // { + // vec3 position; // Aligned to 4 floats + // vec3 color; // Aligned to 4 floats + // }; + data: buildParticlesBuffer() + } + + Attribute { + id: particlePositionDataAttribute + name: "particlePosition" + attributeType: Attribute.VertexAttribute + vertexBaseType: Attribute.Float + vertexSize: 3 + divisor: 1 + byteStride: 8 * floatSize + buffer: particleBuffer + } + + Attribute { + id: particleColorDataAttribute + name: "particleColor" + attributeType: Attribute.VertexAttribute + vertexBaseType: Attribute.Float + vertexSize: 3 + divisor: 1 + byteOffset: 4 * floatSize + byteStride: 8 * floatSize + buffer: particleBuffer + } + + ComputeMaterial { + id: computeMaterial + dataBuffer: particleBuffer + } + + ComputeCommand { + id: particlesComputeJob + onRunTypeChanged: { + // Don't forget to re-enable the command + // when switching back to continuous + if (runType === ComputeCommand.Continuous) + enabled = true + } + } + + Entity { + id: particleComputeEntity + components: [ + particlesComputeJob, + computeMaterial + ] + } + + SphereGeometry { + id: sphereGeometry + rings: 10 + slices: 10 + radius: 1 + // Additional Attributes + attributes: [ + particlePositionDataAttribute, + particleColorDataAttribute + ] + } + + Entity { + id: particleRenderEntity + readonly property GeometryRenderer particlesRenderer: GeometryRenderer { + instanceCount: particlesCount + indexOffset: 0 + firstInstance: 0 + primitiveType: GeometryRenderer.Triangles + geometry: sphereGeometry + } + + components: [ + particlesRenderer, + computeMaterial + ] + } +} + diff --git a/tests/manual/compute-manual/compute-manual.pro b/tests/manual/compute-manual/compute-manual.pro new file mode 100644 index 000000000..e2a9116db --- /dev/null +++ b/tests/manual/compute-manual/compute-manual.pro @@ -0,0 +1,14 @@ +!include( ../manual.pri ) { + error( "Couldn't find the manual.pri file!" ) +} + +QT += 3dcore 3drender 3dquick 3dinput quick qml + +HEADERS += \ + + +RESOURCES += \ + compute-manual.qrc + +SOURCES += \ + main.cpp diff --git a/tests/manual/compute-manual/compute-manual.qrc b/tests/manual/compute-manual/compute-manual.qrc new file mode 100644 index 000000000..0f94fddd5 --- /dev/null +++ b/tests/manual/compute-manual/compute-manual.qrc @@ -0,0 +1,11 @@ + + + main.qml + ComputeFrameGraph.qml + ComputeMaterial.qml + particles.frag + particles.vert + ParticlesScene.qml + particles.comp + + diff --git a/tests/manual/compute-manual/main.cpp b/tests/manual/compute-manual/main.cpp new file mode 100644 index 000000000..afc9df36a --- /dev/null +++ b/tests/manual/compute-manual/main.cpp @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +int main(int argc, char* argv[]) +{ + QGuiApplication app(argc, argv); + + QQuickView view; + + view.resize(1024, 1024); + view.setResizeMode(QQuickView::SizeRootObjectToView); + view.setSource(QUrl("qrc:/main.qml")); + view.show(); + + return app.exec(); +} diff --git a/tests/manual/compute-manual/main.qml b/tests/manual/compute-manual/main.qml new file mode 100644 index 000000000..a76c8ae0c --- /dev/null +++ b/tests/manual/compute-manual/main.qml @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.14 +import QtQuick.Scene3D 2.14 +import QtQuick.Controls 2.14 +import QtQuick.Layouts 1.1 +import Qt3D.Render 2.14 + +Item { + + Scene3D { + anchors.fill: parent + aspects: ["input", "logic"] + focus: true + ParticlesScene { + id: scene + computeMode: runModeCombo.currentIndex === 0 ? ComputeCommand.Continuous : ComputeCommand.Manual + } + } + + RowLayout { + id: colorLayout + anchors.left: parent.left + anchors.leftMargin: 35 + anchors.bottom: parent.bottom + anchors.bottomMargin: 35 + spacing: 15 + + RowLayout { + Text { + text: "Run Mode:" + color: "white" + } + ComboBox { + id: runModeCombo + model: ["Continuous", "Manual"] + } + } + RowLayout { + visible: runModeCombo.currentIndex === 1 + Text { + color: "white" + text: "Frames" + } + SpinBox { + id: frameCountSpinBox + value: 5 + from: 1 + to: 10 + stepSize: 1 + } + Button { + text: "Trigger" + onClicked: { + // Trigger Compute Manual + scene.triggerCompute(frameCountSpinBox.value) + } + } + } + } +} diff --git a/tests/manual/compute-manual/particles.comp b/tests/manual/compute-manual/particles.comp new file mode 100644 index 000000000..b05e49c1d --- /dev/null +++ b/tests/manual/compute-manual/particles.comp @@ -0,0 +1,31 @@ +#version 430 core + +uniform float time; + +layout (local_size_x = 1024) in; + +struct ParticleData +{ + vec4 position; + vec4 color; +}; + +// Particles from previouse frame +layout (std430, binding = 0) coherent buffer Particles +{ + ParticleData particles[]; +} data; + +void main(void) +{ + uint globalId = gl_GlobalInvocationID.x; + + // Retrieve current particle from previous frame + ParticleData currentParticle = data.particles[globalId]; + + // New position = old position + sin(time) + currentParticle.position = currentParticle.position + vec4(0.0, 1.0, 0.0, 0.0) * sin(time * globalId); + + // Save updated particle + data.particles[globalId] = currentParticle; +} diff --git a/tests/manual/compute-manual/particles.frag b/tests/manual/compute-manual/particles.frag new file mode 100644 index 000000000..3f11b9868 --- /dev/null +++ b/tests/manual/compute-manual/particles.frag @@ -0,0 +1,33 @@ +#version 430 core + +out vec4 color; + +in VertexBlock +{ + flat vec3 color; + vec3 pos; + vec3 normal; +} frag_in; + +const vec4 lightPosition = vec4(0.0, 0.0, 0.0, 0.0); +const vec3 lightIntensity = vec3(1.0, 1.0, 1.0); +const vec3 ka = vec3(0.1, 0.1, 0.1); +const vec3 ks = vec3(0.8, 0.8, 0.8); +const float shininess = 50.0; + +vec3 ads() +{ + vec3 n = normalize( frag_in.normal); + vec3 s = normalize( vec3(lightPosition) - frag_in.pos ); + vec3 v = normalize( -frag_in.pos ); + vec3 h = normalize( v + s ); + return lightIntensity * (ka + + frag_in.color * max( dot(s, frag_in.normal ), 0.0 ) + + ks * pow( max( dot( h, n ), 0.0 ), shininess ) ); +} + + +void main(void) +{ + color = vec4(ads(), 1.0); +} diff --git a/tests/manual/compute-manual/particles.vert b/tests/manual/compute-manual/particles.vert new file mode 100644 index 000000000..5f2da2a00 --- /dev/null +++ b/tests/manual/compute-manual/particles.vert @@ -0,0 +1,27 @@ +#version 430 core + +in vec3 vertexPosition; +in vec3 vertexNormal; + +in vec3 particlePosition; +in vec3 particleColor; + +out VertexBlock +{ + flat vec3 color; + vec3 pos; + vec3 normal; +} v_out; + +uniform mat4 mvp; +uniform mat3 modelViewNormal; +uniform mat4 modelView; + +void main(void) +{ + vec4 pos = vec4(vertexPosition.xyz, 1.0) + vec4(particlePosition, 0.0); + gl_Position = mvp * pos; + v_out.pos = vec4(modelView * pos).xyz; + v_out.normal = normalize(modelViewNormal * vertexNormal); + v_out.color = mix(particleColor * 0.2, particleColor, smoothstep(0.5, 0.8, abs(v_out.normal).z)); +} diff --git a/tests/manual/manual.pro b/tests/manual/manual.pro index 1182886d3..9c2461b29 100644 --- a/tests/manual/manual.pro +++ b/tests/manual/manual.pro @@ -69,6 +69,8 @@ SUBDIRS += \ scene3d-in-sync \ compressed_textures +!macos:!uikit: SUBDIRS += compute-manual + qtHaveModule(multimedia): { SUBDIRS += \ sharedtexture \ -- cgit v1.2.3 From 14f18da717cd256e76a01dacd93e43e7d9a804a3 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Thu, 24 Oct 2019 07:45:02 +0100 Subject: Revert removal of more sceneChanged methods Removal breaks BC Change-Id: I8c324253c3a39c8fd74bf4cc14462f76cd2e4f5e Reviewed-by: Paul Lemire --- src/core/transforms/qabstractskeleton.cpp | 7 +++++++ src/core/transforms/qabstractskeleton.h | 2 ++ src/render/geometry/qbuffer.cpp | 7 +++++++ src/render/geometry/qbuffer.h | 4 ++++ 4 files changed, 20 insertions(+) diff --git a/src/core/transforms/qabstractskeleton.cpp b/src/core/transforms/qabstractskeleton.cpp index e401c3043..4a30d0710 100644 --- a/src/core/transforms/qabstractskeleton.cpp +++ b/src/core/transforms/qabstractskeleton.cpp @@ -105,6 +105,13 @@ QAbstractSkeleton::~QAbstractSkeleton() { } +/*! \internal */ +void QAbstractSkeleton::sceneChangeEvent(const QSceneChangePtr &change) +{ + // TODO Unused remove in Qt6 + Q_UNUSED(change) +} + /*! \property Qt3DCore::QAbstractSkeleton::jointCount diff --git a/src/core/transforms/qabstractskeleton.h b/src/core/transforms/qabstractskeleton.h index 7da78011f..1c2eba08f 100644 --- a/src/core/transforms/qabstractskeleton.h +++ b/src/core/transforms/qabstractskeleton.h @@ -64,6 +64,8 @@ Q_SIGNALS: protected: QAbstractSkeleton(QAbstractSkeletonPrivate &dd, Qt3DCore::QNode *parent = nullptr); + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; private: Q_DECLARE_PRIVATE(QAbstractSkeleton) diff --git a/src/render/geometry/qbuffer.cpp b/src/render/geometry/qbuffer.cpp index bbe08fdf7..8399bdd7c 100644 --- a/src/render/geometry/qbuffer.cpp +++ b/src/render/geometry/qbuffer.cpp @@ -433,6 +433,13 @@ void QBuffer::setAccessType(QBuffer::AccessType access) } } +/*! \internal */ +void QBuffer::sceneChangeEvent(const QSceneChangePtr &change) +{ + // TODO Unused remove in Qt6 + Q_UNUSED(change) +} + bool QBuffer::isSyncData() const { Q_D(const QBuffer); diff --git a/src/render/geometry/qbuffer.h b/src/render/geometry/qbuffer.h index 4d5f6c86e..aa6ebca66 100644 --- a/src/render/geometry/qbuffer.h +++ b/src/render/geometry/qbuffer.h @@ -126,6 +126,10 @@ Q_SIGNALS: void accessTypeChanged(AccessType access); void dataAvailable(); +protected: + // TODO Unused remove in Qt6 + void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; + private: Q_DECLARE_PRIVATE(QBuffer) Qt3DCore::QNodeCreatedChangeBasePtr createNodeCreationChange() const override; -- cgit v1.2.3 From 4e87fdd85ff960eac34407206de365e134a2cdcf Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Thu, 24 Oct 2019 07:45:15 +0100 Subject: Revert post FF changes Change-Id: Idf5f80bcfa0427e6545feca33312f08c1172dfb2 Reviewed-by: Paul Lemire --- src/render/backend/rendersettings.cpp | 17 +++++++++-------- src/render/frontend/qrendersettings.cpp | 6 ------ src/render/frontend/qrendersettings.h | 1 - 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/render/backend/rendersettings.cpp b/src/render/backend/rendersettings.cpp index 487f6e11a..8638352c4 100644 --- a/src/render/backend/rendersettings.cpp +++ b/src/render/backend/rendersettings.cpp @@ -79,20 +79,21 @@ void RenderSettings::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs m_renderPolicy = node->renderPolicy(); } - if (node->pickingSettings()->pickMethod() != m_pickMethod) { - m_pickMethod = node->pickingSettings()->pickMethod(); + auto ncnode = const_cast(node); + if (ncnode->pickingSettings()->pickMethod() != m_pickMethod) { + m_pickMethod = ncnode->pickingSettings()->pickMethod(); } - if (node->pickingSettings()->pickResultMode() != m_pickResultMode) { - m_pickResultMode = node->pickingSettings()->pickResultMode(); + if (ncnode->pickingSettings()->pickResultMode() != m_pickResultMode) { + m_pickResultMode = ncnode->pickingSettings()->pickResultMode(); } - if (node->pickingSettings()->worldSpaceTolerance() != m_pickWorldSpaceTolerance) { - m_pickWorldSpaceTolerance = node->pickingSettings()->worldSpaceTolerance(); + if (ncnode->pickingSettings()->worldSpaceTolerance() != m_pickWorldSpaceTolerance) { + m_pickWorldSpaceTolerance = ncnode->pickingSettings()->worldSpaceTolerance(); } - if (node->pickingSettings()->faceOrientationPickingMode() != m_faceOrientationPickingMode) { - m_faceOrientationPickingMode = node->pickingSettings()->faceOrientationPickingMode(); + if (ncnode->pickingSettings()->faceOrientationPickingMode() != m_faceOrientationPickingMode) { + m_faceOrientationPickingMode = ncnode->pickingSettings()->faceOrientationPickingMode(); } // Either because something above as changed or if QRenderSettingsPrivate::invalidFrame() diff --git a/src/render/frontend/qrendersettings.cpp b/src/render/frontend/qrendersettings.cpp index d106e4205..5916c4b73 100644 --- a/src/render/frontend/qrendersettings.cpp +++ b/src/render/frontend/qrendersettings.cpp @@ -161,12 +161,6 @@ QPickingSettings *QRenderSettings::pickingSettings() return &(d->m_pickingSettings); } -const QPickingSettings *QRenderSettings::pickingSettings() const -{ - Q_D(const QRenderSettings); - return &(d->m_pickingSettings); -} - /*! \qmlproperty FrameGraphNode RenderSettings::activeFrameGraph diff --git a/src/render/frontend/qrendersettings.h b/src/render/frontend/qrendersettings.h index c8771a8fa..9d2baa58b 100644 --- a/src/render/frontend/qrendersettings.h +++ b/src/render/frontend/qrendersettings.h @@ -71,7 +71,6 @@ public: Q_ENUM(RenderPolicy) // LCOV_EXCL_LINE QPickingSettings* pickingSettings(); - const QPickingSettings* pickingSettings() const; QFrameGraphNode *activeFrameGraph() const; RenderPolicy renderPolicy() const; -- cgit v1.2.3 From 59bcc05abb8606dfc33086870980ffdf4a3937eb Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Wed, 16 Oct 2019 10:52:49 +0200 Subject: Add manual test for QSubtreeEnabler Change-Id: Iff354956c831919cbb9d58f75014be0fa92b45c4 Reviewed-by: Mike Krus Reviewed-by: Michael Brasser --- tests/manual/manual.pro | 4 +- tests/manual/subtree-enabler-qml/FrameGraph.qml | 100 +++++++++++++++++++ tests/manual/subtree-enabler-qml/SimpleCamera.qml | 79 +++++++++++++++ tests/manual/subtree-enabler-qml/main.cpp | 64 ++++++++++++ tests/manual/subtree-enabler-qml/main.qml | 110 +++++++++++++++++++++ .../subtree-enabler-qml/subtree-enabler-qml.pro | 17 ++++ .../subtree-enabler-qml/subtree-enabler-qml.qrc | 7 ++ 7 files changed, 380 insertions(+), 1 deletion(-) create mode 100644 tests/manual/subtree-enabler-qml/FrameGraph.qml create mode 100644 tests/manual/subtree-enabler-qml/SimpleCamera.qml create mode 100644 tests/manual/subtree-enabler-qml/main.cpp create mode 100644 tests/manual/subtree-enabler-qml/main.qml create mode 100644 tests/manual/subtree-enabler-qml/subtree-enabler-qml.pro create mode 100644 tests/manual/subtree-enabler-qml/subtree-enabler-qml.qrc diff --git a/tests/manual/manual.pro b/tests/manual/manual.pro index 9c2461b29..3553219e1 100644 --- a/tests/manual/manual.pro +++ b/tests/manual/manual.pro @@ -67,10 +67,12 @@ SUBDIRS += \ qtbug-76766 \ shader-image-qml \ scene3d-in-sync \ - compressed_textures + compressed_textures \ + subtree-enabler-qml !macos:!uikit: SUBDIRS += compute-manual + qtHaveModule(multimedia): { SUBDIRS += \ sharedtexture \ diff --git a/tests/manual/subtree-enabler-qml/FrameGraph.qml b/tests/manual/subtree-enabler-qml/FrameGraph.qml new file mode 100644 index 000000000..b9cdce9ea --- /dev/null +++ b/tests/manual/subtree-enabler-qml/FrameGraph.qml @@ -0,0 +1,100 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 +import QtQuick 2.14 as QQ2 + +RenderSettings { + id: frameGraph + + property alias leftCamera: cameraSelectorLeftViewport.camera; + property alias rightCamera: cameraSelectorRightViewport.camera; + property alias window: surfaceSelector.surface + + activeFrameGraph: RenderSurfaceSelector { + id: surfaceSelector + + Viewport { + id: mainViewport + normalizedRect: Qt.rect(0, 0, 1, 1) + + ClearBuffers { + buffers: ClearBuffers.ColorDepthBuffer + clearColor: Qt.rgba(0.6, 0.6, 0.6, 1.0) + NoDraw {} + } + + Viewport { + id: leftViewport + normalizedRect: Qt.rect(0, 0, 0.5, 0.5) + CameraSelector { id: cameraSelectorLeftViewport } + } + + SubtreeEnabler { + id: enabler + enabled: true + + QQ2.Timer { + running: true + repeat: true + interval: 1000 + onTriggered: enabler.enabled = !enabler.enabled + } + + Viewport { + id: rightViewport + normalizedRect: Qt.rect(0.5, 0.5, 0.5, 0.5) + CameraSelector { id: cameraSelectorRightViewport } + } + } + } + } +} diff --git a/tests/manual/subtree-enabler-qml/SimpleCamera.qml b/tests/manual/subtree-enabler-qml/SimpleCamera.qml new file mode 100644 index 000000000..a1ef6d01c --- /dev/null +++ b/tests/manual/subtree-enabler-qml/SimpleCamera.qml @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 + +Entity { + id: root + + property vector3d position: Qt.vector3d(0.0, 0.0, 10.0) + property vector3d viewCenter: Qt.vector3d(0.0, 0.0, 0.0) + property vector3d upVector: Qt.vector3d(0.0, 1.0, 0.0) + property CameraLens lens: null + + components: [lens, transform] + + Transform { + id: transform + matrix: { + var m = Qt.matrix4x4(); + m.translate(root.position) + var zAxis = root.position.minus(root.viewCenter).normalized() + var xAxis = root.upVector.crossProduct(zAxis).normalized(); + var yAxis = zAxis.crossProduct(xAxis); + var r = Qt.matrix4x4(xAxis.x, yAxis.x, zAxis.x, 0, + xAxis.y, yAxis.y, zAxis.y, 0, + xAxis.z, yAxis.z, zAxis.z, 0, + 0, 0, 0, 1) + return m.times(r); + } + } +} diff --git a/tests/manual/subtree-enabler-qml/main.cpp b/tests/manual/subtree-enabler-qml/main.cpp new file mode 100644 index 000000000..ce5b883bd --- /dev/null +++ b/tests/manual/subtree-enabler-qml/main.cpp @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +int main(int ac, char **av) +{ + QGuiApplication app(ac, av); + Qt3DExtras::Quick::Qt3DQuickWindow view; + view.setSource(QUrl("qrc:/main.qml")); + view.show(); + + return app.exec(); +} + + diff --git a/tests/manual/subtree-enabler-qml/main.qml b/tests/manual/subtree-enabler-qml/main.qml new file mode 100644 index 000000000..c2e530893 --- /dev/null +++ b/tests/manual/subtree-enabler-qml/main.qml @@ -0,0 +1,110 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.14 +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 +import Qt3D.Input 2.14 +import Qt3D.Extras 2.14 + +Entity { + id: rootNode + components: [frameGraph] + + FrameGraph { + id: frameGraph + leftCamera: camera1 + rightCamera: camera2 + } + + CameraLens { + id: cameraLens + projectionType: CameraLens.PerspectiveProjection + fieldOfView: 45 + aspectRatio: 16/9 + nearPlane: 0.01 + farPlane: 1000.0 + } + + SimpleCamera { + id: camera1 + lens: cameraLens + position: Qt.vector3d(10.0, 1.0, 10.0) + viewCenter: Qt.vector3d(0.0, 1.0, 0.0) + } + + SimpleCamera { + id: camera2 + lens: cameraLens + position: Qt.vector3d(0.0, 0.0, 5.0) + viewCenter: Qt.vector3d(0.0, 0.0, 0.0) + } + + Entity { + id: sceneRoot + property real rotationAngle: 0 + + SequentialAnimation { + running: true + loops: Animation.Infinite + NumberAnimation { target: sceneRoot; property: "rotationAngle"; to: 360; duration: 4000; } + } + + Entity { + components: [ + Transform { + rotation: fromAxisAndAngle(Qt.vector3d(0, 0, 1), -sceneRoot.rotationAngle) + }, + CylinderMesh {}, + MetalRoughMaterial {} + ] + } + } // sceneRoot +} // rootNode diff --git a/tests/manual/subtree-enabler-qml/subtree-enabler-qml.pro b/tests/manual/subtree-enabler-qml/subtree-enabler-qml.pro new file mode 100644 index 000000000..ddd0ae561 --- /dev/null +++ b/tests/manual/subtree-enabler-qml/subtree-enabler-qml.pro @@ -0,0 +1,17 @@ +!include( ../manual.pri ) { + error( "Couldn't find the manual.pri file!" ) +} + +QT += 3dcore 3drender 3dinput 3dquick qml quick 3dquickextras + +HEADERS += \ + +SOURCES += \ + main.cpp + +OTHER_FILES += \ + main.qml + +RESOURCES += \ + subtree-enabler-qml.qrc \ + diff --git a/tests/manual/subtree-enabler-qml/subtree-enabler-qml.qrc b/tests/manual/subtree-enabler-qml/subtree-enabler-qml.qrc new file mode 100644 index 000000000..e565b719f --- /dev/null +++ b/tests/manual/subtree-enabler-qml/subtree-enabler-qml.qrc @@ -0,0 +1,7 @@ + + + main.qml + FrameGraph.qml + SimpleCamera.qml + + -- cgit v1.2.3 From 1194641110288b4e58c92cac17c3289ad7cad49d Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Tue, 15 Oct 2019 08:16:35 +0200 Subject: ComputeCommand: add unit tests for manual trigger mode Change-Id: Ia106a235648df7232fbcaf4f61c880a9ab5491ef Reviewed-by: Mike Krus --- src/render/backend/computecommand.cpp | 5 +- .../render/computecommand/tst_computecommand.cpp | 118 +++++++++++++++++++++ 2 files changed, 122 insertions(+), 1 deletion(-) diff --git a/src/render/backend/computecommand.cpp b/src/render/backend/computecommand.cpp index 700769546..bc82291f0 100644 --- a/src/render/backend/computecommand.cpp +++ b/src/render/backend/computecommand.cpp @@ -100,7 +100,10 @@ void ComputeCommand::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs markDirty(AbstractRenderer::ComputeDirty); } const QComputeCommandPrivate *d = static_cast(Qt3DCore::QNodePrivate::get(node)); - if (d->m_frameCount != m_frameCount) { + // Check frame count only if frontend is enabled + // If disabled that means we might have disabled the frontend because + // framecount reached 0 + if (d->m_enabled && d->m_frameCount != m_frameCount) { m_frameCount = d->m_frameCount; m_hasReachedFrameCount = m_frameCount <= 0; markDirty(AbstractRenderer::ComputeDirty); diff --git a/tests/auto/render/computecommand/tst_computecommand.cpp b/tests/auto/render/computecommand/tst_computecommand.cpp index 4120153e7..2046ecc76 100644 --- a/tests/auto/render/computecommand/tst_computecommand.cpp +++ b/tests/auto/render/computecommand/tst_computecommand.cpp @@ -31,12 +31,37 @@ #include #include #include +#include +#include +#include #include +#include +#include #include #include "qbackendnodetester.h" #include "testrenderer.h" #include "testpostmanarbiter.h" + +// tst_Renderer is a friend class of Renderer +class tst_Renderer : public Qt3DRender::Render::Renderer +{ +public: + tst_Renderer() + : Qt3DRender::Render::Renderer(Qt3DRender::QRenderAspect::Synchronous) + {} + + ~tst_Renderer() { + shutdown(); + } + + Qt3DRender::Render::SynchronizerPostFramePtr sendDisablesToFrontendJob() const + { + return m_sendDisablesToFrontendJob; + } +}; + + class tst_ComputeCommand : public Qt3DCore::QBackendNodeTester { Q_OBJECT @@ -232,6 +257,99 @@ private Q_SLOTS: QCOMPARE(backendComputeCommand.frameCount(), 0); // Backend stays with enabled == true, frontend will be updated // to be disabled and backend should be disabled on the next sync + + // WHEN + computeCommand.setEnabled(false); + backendComputeCommand.syncFromFrontEnd(&computeCommand, false); + + // THEN + QCOMPARE(backendComputeCommand.isEnabled(), false); + QCOMPARE(backendComputeCommand.frameCount(), 0); + + // WHEN + computeCommand.trigger(1); + backendComputeCommand.syncFromFrontEnd(&computeCommand, false); + + // THEN + QCOMPARE(computeCommand.isEnabled(), true); + QCOMPARE(backendComputeCommand.isEnabled(), true); + QCOMPARE(backendComputeCommand.hasReachedFrameCount(), false); + QCOMPARE(backendComputeCommand.frameCount(), 1); + } + + void checkDisablesFrontend() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManager; + tst_Renderer renderer; + TestArbiter arbiter; + + Qt3DCore::QAspectManager manager; + Qt3DCore::QScene scene; + + Qt3DCore::QEntity rootEntity; + Qt3DCore::QNodePrivate::get(&rootEntity)->setScene(&scene); + + Qt3DRender::QComputeCommand computeCommand; + Qt3DRender::Render::ComputeCommand *backendComputeCommand = nullptr; + + renderer.setNodeManagers(&nodeManager); + + // WHEN + computeCommand.setParent(&rootEntity); + // RootEntity is the entry point to retrieve the scene instance for lookups + manager.setRootEntity(&rootEntity, {}); + + // THEN + QVERIFY(scene.lookupNode(computeCommand.id()) != nullptr); + + // WHEN + auto handle = nodeManager.computeJobManager()->getOrAcquireHandle(computeCommand.id()); + backendComputeCommand = nodeManager.computeJobManager()->data(handle); + + // WHEN + computeCommand.setWorkGroupX(256); + computeCommand.setWorkGroupY(512); + computeCommand.setWorkGroupZ(128); + computeCommand.setRunType(Qt3DRender::QComputeCommand::Manual); + computeCommand.trigger(1); + + Qt3DCore::QBackendNodePrivate::get(backendComputeCommand)->setArbiter(&arbiter); + backendComputeCommand->setRenderer(&renderer); + simulateInitializationSync(&computeCommand, backendComputeCommand); + + // THEN + QCOMPARE(backendComputeCommand->frameCount(),1); + QCOMPARE(backendComputeCommand->isEnabled(), true); + QCOMPARE(computeCommand.isEnabled(), true); + QCOMPARE(backendComputeCommand->hasReachedFrameCount(), false); + + // WHEN + backendComputeCommand->updateFrameCount(); + + // THEN + QCOMPARE(backendComputeCommand->frameCount(), 0); + QCOMPARE(backendComputeCommand->hasReachedFrameCount(), true); + + + // Still enabled as we have yet to notify the fronted + QCOMPARE(backendComputeCommand->isEnabled(), true); + QCOMPARE(computeCommand.isEnabled(), true); + + // WHEN + auto sendDisablesJob = renderer.sendDisablesToFrontendJob(); + Qt3DCore::QAspectJobPrivate::get(sendDisablesJob.data())->postFrame(&manager); + + // THEN + QCOMPARE(computeCommand.isEnabled(), false); + QCOMPARE(backendComputeCommand->hasReachedFrameCount(), false); + + // WHEN + backendComputeCommand->syncFromFrontEnd(&computeCommand, false); + + // THEN + QCOMPARE(backendComputeCommand->frameCount(), 0); + QCOMPARE(backendComputeCommand->isEnabled(), false); } }; -- cgit v1.2.3 From ab6a70325e320ff0ea2c5b4673cc9a122ee0f601 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 21 Oct 2019 11:34:10 +0200 Subject: Scene3D: halt Qt3D simulation loop while not visible Change-Id: I09d69fab7aaf3c2fa77da6eb30e505d9cb25c01f Reviewed-by: Mike Krus --- src/quick3d/imports/scene3d/scene3ditem.cpp | 11 ++ tests/manual/manual.pro | 3 +- tests/manual/scene3d-visibility/main.cpp | 66 +++++++++ tests/manual/scene3d-visibility/main.qml | 161 +++++++++++++++++++++ .../scene3d-visibility/scene3d-visibility.pro | 10 ++ .../scene3d-visibility/scene3d-visibility.qrc | 5 + 6 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 tests/manual/scene3d-visibility/main.cpp create mode 100644 tests/manual/scene3d-visibility/main.qml create mode 100644 tests/manual/scene3d-visibility/scene3d-visibility.pro create mode 100644 tests/manual/scene3d-visibility/scene3d-visibility.qrc diff --git a/src/quick3d/imports/scene3d/scene3ditem.cpp b/src/quick3d/imports/scene3d/scene3ditem.cpp index 835485385..55e972406 100644 --- a/src/quick3d/imports/scene3d/scene3ditem.cpp +++ b/src/quick3d/imports/scene3d/scene3ditem.cpp @@ -137,6 +137,11 @@ namespace Qt3DRender { \li The Scene3D instance is instantiated prior to any Scene3DView \li The Scene3D entity property is left unset \endlist + + \note Åšetting the visibility of the Scene3D element to false will halt the + Qt 3D simulation loop. This means that binding the visible property to an + expression that depends on property updates driven by the Qt 3D simulation + loop (FrameAction) will never reavaluates. */ Scene3DItem::Scene3DItem(QQuickItem *parent) : QQuickItem(parent) @@ -455,6 +460,12 @@ bool Scene3DItem::needsRender() // processFrame will block and wait for renderer to have been finished void Scene3DItem::onBeforeSync() { + // If we are not visible, don't processFrame changes as we would end up + // waiting forever for the scene to be rendered which won't happen + // if the Scene3D item is not visible + if (!isVisible()) + return; + // Has anything in the 3D scene actually changed that requires us to render? if (!needsRender()) return; diff --git a/tests/manual/manual.pro b/tests/manual/manual.pro index 3553219e1..dbb1fbc63 100644 --- a/tests/manual/manual.pro +++ b/tests/manual/manual.pro @@ -68,7 +68,8 @@ SUBDIRS += \ shader-image-qml \ scene3d-in-sync \ compressed_textures \ - subtree-enabler-qml + subtree-enabler-qml \ + scene3d-visibility !macos:!uikit: SUBDIRS += compute-manual diff --git a/tests/manual/scene3d-visibility/main.cpp b/tests/manual/scene3d-visibility/main.cpp new file mode 100644 index 000000000..8886263f4 --- /dev/null +++ b/tests/manual/scene3d-visibility/main.cpp @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +int main(int argc, char **argv) +{ + QGuiApplication app(argc, argv); + + QQuickView view; + + view.resize(500, 500); + view.setResizeMode(QQuickView::SizeRootObjectToView); + view.setSource(QUrl("qrc:/main.qml")); + view.show(); + + return app.exec(); +} diff --git a/tests/manual/scene3d-visibility/main.qml b/tests/manual/scene3d-visibility/main.qml new file mode 100644 index 000000000..ccfa3227f --- /dev/null +++ b/tests/manual/scene3d-visibility/main.qml @@ -0,0 +1,161 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.14 +import Qt3D.Core 2.14 +import Qt3D.Render 2.14 +import Qt3D.Input 2.14 +import Qt3D.Extras 2.14 +import QtQuick.Scene3D 2.14 + +Item { + id: root + + Timer { + running: true + repeat: true + interval: 2000 + onTriggered: scene3d.visible = !scene3d.visible + } + + // Scene3D + Scene3D { + id: scene3d + visible: false + readonly property double halfWidth: width * 0.5 + + focus: true + anchors.fill: parent + // Make sure to define the input aspect if we want to handle inputs + aspects: ["render", "input"] + multisample: false + + Entity { // Root + id: sceneRoot + components: [ + RenderSettings { + activeFrameGraph: ForwardRenderer { + id: forwardRenderer + camera: mainCamera + clearColor: "yellow" + } + }, + // Event Source is the Scene3D in that case + InputSettings { } + ] + + Camera { + id: mainCamera + projectionType: CameraLens.PerspectiveProjection + fieldOfView: 45 + nearPlane : 0.1 + farPlane : 1000.0 + position: Qt.vector3d( 0.0, 0.0, -40.0 ) + upVector: Qt.vector3d( 0.0, 1.0, 0.0 ) + viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 ) + } + + PhongMaterial { + id: material + } + + TorusMesh { + id: torusMesh + radius: 5 + minorRadius: 1 + rings: 100 + slices: 20 + } + + SphereMesh { + id: sphereMesh + radius: 3 + } + + Transform { + id: torusTransform + scale3D: Qt.vector3d(1.5, 1, 0.5) + rotation: fromAxisAndAngle(Qt.vector3d(1, 0, 0), 45) + } + + Transform { + id: sphereTransform + property real userAngle: 0.0 + matrix: { + var m = Qt.matrix4x4(); + m.rotate(userAngle, Qt.vector3d(0, 1, 0)); + m.translate(Qt.vector3d(20, 0, 0)); + return m; + } + + onWorldMatrixChanged: console.log("Sphere WorldMatrix " + worldMatrix) + } + + NumberAnimation { + target: sphereTransform + property: "userAngle" + duration: 1000 + from: 0 + to: 360 + loops: Animation.Infinite + running: true + } + + Entity { + id: torusEntity + components: [ torusMesh, material, torusTransform ] + } + Entity { + id: sphereEntity + components: [ sphereMesh, material, sphereTransform ] + } + } + } +} diff --git a/tests/manual/scene3d-visibility/scene3d-visibility.pro b/tests/manual/scene3d-visibility/scene3d-visibility.pro new file mode 100644 index 000000000..a1c20a502 --- /dev/null +++ b/tests/manual/scene3d-visibility/scene3d-visibility.pro @@ -0,0 +1,10 @@ +QT += qml quick 3dinput + +SOURCES += \ + main.cpp + +OTHER_FILES += \ + main.qml + +RESOURCES += \ + scene3d-visibility.qrc diff --git a/tests/manual/scene3d-visibility/scene3d-visibility.qrc b/tests/manual/scene3d-visibility/scene3d-visibility.qrc new file mode 100644 index 000000000..5f6483ac3 --- /dev/null +++ b/tests/manual/scene3d-visibility/scene3d-visibility.qrc @@ -0,0 +1,5 @@ + + + main.qml + + -- cgit v1.2.3 From 8549dc8ce18d7a54666de67f8a2be48def91b89b Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Fri, 25 Oct 2019 08:21:07 +0200 Subject: Update AndroidManifest.xml to be compatible with Qt 5.14 The bundled_in_lib and bundled_in_assets entries have been removed, so all manifests have to be updated to no longer refer to these. In addition, android-16 is no longer supported, so the minimum SDK versions have to be updated. Change-Id: Id01326df5522195647eb107b60ea7e637a950bb3 Reviewed-by: BogDan Vatra --- examples/qt3d/planets-qml/android/AndroidManifest.xml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/examples/qt3d/planets-qml/android/AndroidManifest.xml b/examples/qt3d/planets-qml/android/AndroidManifest.xml index 0252a83b8..2acbd7b0b 100644 --- a/examples/qt3d/planets-qml/android/AndroidManifest.xml +++ b/examples/qt3d/planets-qml/android/AndroidManifest.xml @@ -1,6 +1,6 @@ - + @@ -13,12 +13,10 @@ - - - + @@ -42,7 +40,7 @@ - + int. reserved for future use, return 0 for now. + - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior + - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() + - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) + - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. + - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. + (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. + font init: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..> + became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; + you now more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. + it is now recommended that you sample the font texture with bilinear interpolation. + (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. + (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) + (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets + - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) + - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) + - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility + - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() + - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) + - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) + - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() + - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn + - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) + - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite + - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes + + + FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + ====================================== + + Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application? + A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } ) + - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application. + - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application. + - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS). + Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false. + This is because imgui needs to detect that you clicked in the void to unfocus its own windows. + Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!). + It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs. + Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also + perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags(). + Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically + have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs + were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) + + Q: How can I display an image? What is ImTextureID, how does it works? + A: Short explanation: + - You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures. + - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value. + - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason). + Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward. + + Long explanation: + - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. + At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code + to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.). + - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API. + We carry the information to identify a "texture" in the ImTextureID type. + ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice. + Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function. + - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying + an image from the end-user perspective. This is what the _examples_ rendering functions are using: + + OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp) + DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp) + DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp) + DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp) + + For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID. + Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure + tying together both the texture and information about its format and how to read it. + - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about + the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase + is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them. + If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID + representation suggested by the example bindings is probably the best choice. + (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer) + + User code may do: + + // Cast our texture type to ImTextureID / void* + MyTexture* texture = g_CoffeeTableTexture; + ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height)); + + The renderer function called after ImGui::Render() will receive that same value that the user code passed: + + // Cast ImTextureID / void* stored in the draw command as our texture type + MyTexture* texture = (MyTexture*)pcmd->TextureId; + MyEngineBindTexture2D(texture); + + Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui. + This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them. + If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using. + + Here's a simplified OpenGL example using stb_image.h: + + // Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data: + #define STB_IMAGE_IMPLEMENTATION + #include + [...] + int my_image_width, my_image_height; + unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4); + + // Turn the RGBA pixel data into an OpenGL texture: + GLuint my_opengl_texture; + glGenTextures(1, &my_opengl_texture); + glBindTexture(GL_TEXTURE_2D, my_opengl_texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); + + // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it: + ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height)); + + C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTexture / void*, and vice-versa. + Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTexture / void*. + Examples: + + GLuint my_tex = XXX; + void* my_void_ptr; + my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer) + my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint + + ID3D11ShaderResourceView* my_dx11_srv = XXX; + void* my_void_ptr; + my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void* + my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView* + + Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated. + + Q: How can I have multiple widgets with the same label or without a label? + Q: I have multiple widgets with the same label, and only the first one works. Why is that? + A: A primer on labels and the ID Stack... + + Dear ImGui internally need to uniquely identify UI elements. + Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. + Interactive widgets (such as calls to Button buttons) need a unique ID. + Unique ID are used internally to track active widgets and occasionally associate state to widgets. + Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element. + + - Unique ID are often derived from a string label: + + Button("OK"); // Label = "OK", ID = hash of (..., "OK") + Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel") + + - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having + two buttons labeled "OK" in different windows or different tree locations is fine. + We used "..." above to signify whatever was already pushed to the ID stack previously: + + Begin("MyWindow"); + Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") + End(); + + - If you have a same ID twice in the same location, you'll have a conflict: + + Button("OK"); + Button("OK"); // ID collision! Interacting with either button will trigger the first one. + + Fear not! this is easy to solve and there are many ways to solve it! + + - Solving ID conflict in a simple/local context: + When passing a label you can optionally specify extra ID information within string itself. + Use "##" to pass a complement to the ID that won't be visible to the end-user. + This helps solving the simple collision cases when you know e.g. at compilation time which items + are going to be created: + + Begin("MyWindow"); + Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") + Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above + Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above + End(); + + - If you want to completely hide the label, but still need an ID: + + Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! + + - Occasionally/rarely you might want change a label while preserving a constant ID. This allows + you to animate labels. For example you may want to include varying information in a window title bar, + but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: + + Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "ID") + Button("World###ID"); // Label = "World", ID = hash of (..., "ID") // Same as above, even though the label looks different + + sprintf(buf, "My game (%f FPS)###MyGame", fps); + Begin(buf); // Variable title, ID = hash of "MyGame" + + - Solving ID conflict in a more general manner: + Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts + within the same window. This is the most convenient way of distinguishing ID when iterating and + creating many UI elements programmatically. + You can push a pointer, a string or an integer value into the ID stack. + Remember that ID are formed from the concatenation of _everything_ in the ID stack! + + Begin("Window"); + for (int i = 0; i < 100; i++) + { + PushID(i); // Push i to the id tack + Button("Click"); // Label = "Click", ID = Hash of ("Window", i, "Click") + PopID(); + } + for (int i = 0; i < 100; i++) + { + MyObject* obj = Objects[i]; + PushID(obj); + Button("Click"); // Label = "Click", ID = Hash of ("Window", obj pointer, "Click") + PopID(); + } + for (int i = 0; i < 100; i++) + { + MyObject* obj = Objects[i]; + PushID(obj->Name); + Button("Click"); // Label = "Click", ID = Hash of ("Window", obj->Name, "Click") + PopID(); + } + End(); + + - More example showing that you can stack multiple prefixes into the ID stack: + + Button("Click"); // Label = "Click", ID = hash of (..., "Click") + PushID("node"); + Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") + PushID(my_ptr); + Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click") + PopID(); + PopID(); + + - Tree nodes implicitly creates a scope for you by calling PushID(). + + Button("Click"); // Label = "Click", ID = hash of (..., "Click") + if (TreeNode("node")) + { + Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") + TreePop(); + } + + - When working with trees, ID are used to preserve the open/close state of each tree node. + Depending on your use cases you may want to use strings, indices or pointers as ID. + e.g. when following a single pointer that may change over time, using a static string as ID + will preserve your node open/closed state when the targeted object change. + e.g. when displaying a list of objects, using indices or pointers as ID will preserve the + node open/closed state differently. See what makes more sense in your situation! + + Q: How can I use my own math types instead of ImVec2/ImVec4? + A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions. + This way you'll be able to use your own types everywhere, e.g. passsing glm::vec2 to ImGui functions instead of ImVec2. + + Q: How can I load a different font than the default? + A: Use the font atlas to load the TTF/OTF file you want: + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + Default is ProggyClean.ttf, rendered at size 13, embedded in dear imgui's source code. + (Read the 'misc/fonts/README.txt' file for more details about font loading.) + + New programmers: remember that in C/C++ and most programming languages if you want to use a + backslash \ within a string literal, you need to write it double backslash "\\": + io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!) + io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT + io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT + + Q: How can I easily use icons in my application? + A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you + main font. Then you can refer to icons within your strings. + (Read the 'misc/fonts/README.txt' file for more details about icons font loading.) + + Q: How can I load multiple fonts? + A: Use the font atlas to pack them into a single texture: + (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.) + + ImGuiIO& io = ImGui::GetIO(); + ImFont* font0 = io.Fonts->AddFontDefault(); + ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + // the first loaded font gets used by default + // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime + + // Options + ImFontConfig config; + config.OversampleH = 3; + config.OversampleV = 1; + config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up + config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config); + + // Combine multiple fonts into one (e.g. for icon fonts) + static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; + ImFontConfig config; + config.MergeMode = true; + io.Fonts->AddFontDefault(); + io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs + + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. + + // Add default Japanese ranges + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); + + // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need) + ImVector ranges; + ImFontAtlas::GlyphRangesBuilder builder; + builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) + builder.AddChar(0x7262); // Add a specific character + builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges + builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); + + All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 + by using the u8"hello" syntax. Specifying literal in your source code using a local code page + (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work! + Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. + + Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter(). + The applications in examples/ are doing that. + Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). + You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state. + Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for + the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly. + + Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags. + (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) + Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. + - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows. + - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, + and then call your rendered code with your own ImDrawList or ImDrawData data. + + Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. + A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). + Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. + + Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + A: You are probably mishandling the clipping rectangles in your render function. + Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). + + Q: How can I help? + A: - If you are experienced with Dear ImGui and C++, look at the github issues, or docs/TODO.txt and see how you want/can help! + - Convince your company to sponsor/fund development! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README. + - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. + You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers. + But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. + - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately). + + - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. + this is also useful to set yourself in the context of another window (to get/set other settings) + - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug". + - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle + of a deep nested inner loop in your code. + - tip: you can call Render() multiple times (e.g for VR renders). + - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui! + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +#include // toupper, isprint +#include // vsnprintf, sscanf, printf +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +// Debug options +#define IMGUI_DEBUG_NAV_SCORING 0 +#define IMGUI_DEBUG_NAV_RECTS 0 + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#endif + +// Clang/GCC warnings with -Weverything +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false +#if __GNUC__ >= 8 +#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif +#endif + +// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. +static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in +static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear + +// Window resizing from edges (when io.ConfigResizeWindowsFromEdges = true) +static const float RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow(). +static const float RESIZE_WINDOWS_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. + +//------------------------------------------------------------------------- +// [SECTION] FORWARD DECLARATIONS +//------------------------------------------------------------------------- + +static void SetCurrentWindow(ImGuiWindow* window); +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond); +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond); +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond); +static void FindHoveredWindow(); +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static void CheckStacksSize(ImGuiWindow* window, bool write); +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); + +static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list); +static void AddWindowToDrawData(ImVector* out_list, ImGuiWindow* window); +static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); + +static ImRect GetViewportRect(); + +// Settings +static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); +static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); +static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); + +// Platform Dependents default implementation for IO functions +static const char* GetClipboardTextFn_DefaultImpl(void* user_data); +static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); + +namespace ImGui +{ +static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); + +// Navigation +static void NavUpdate(); +static void NavUpdateWindowing(); +static void NavUpdateWindowingList(); +static void NavUpdateMoveResult(); +static float NavUpdatePageUpPageDown(int allowed_dir_flags); +static inline void NavUpdateAnyRequestFlag(); +static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id); +static ImVec2 NavCalcPreferredRefPos(); +static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window); +static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); + +// Misc +static void UpdateMouseInputs(); +static void UpdateMouseWheel(); +static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +} + +// Test engine hooks (imgui-test) +//#define IMGUI_ENABLE_TEST_ENGINE_HOOKS +#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS +extern void ImGuiTestEngineHook_PreNewFrame(); +extern void ImGuiTestEngineHook_PostNewFrame(); +extern void ImGuiTestEngineHook_ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg); +#endif + +//----------------------------------------------------------------------------- +// [SECTION] CONTEXT AND MEMORY ALLOCATORS +//----------------------------------------------------------------------------- + +// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL. +// CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext(). +// If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file. +// ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can: +// - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts) +#ifndef GImGui +ImGuiContext* GImGui = NULL; +#endif + +// Memory Allocator functions. Use SetAllocatorFunctions() to change them. +// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file. +// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. +#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS +static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); } +static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); } +#else +static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; } +static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); } +#endif + +static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper; +static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper; +static void* GImAllocatorUserData = NULL; + +//----------------------------------------------------------------------------- +// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) +//----------------------------------------------------------------------------- + +ImGuiStyle::ImGuiStyle() +{ + Alpha = 1.0f; // Global alpha applies to everything in ImGui + WindowPadding = ImVec2(8,8); // Padding within a window + WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. + WindowMinSize = ImVec2(32,32); // Minimum window size + WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text + ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows + ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. + PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows + PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested. + FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). + FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. + ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns + ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + DisplayWindowPadding = ImVec2(20,20); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. + DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. + AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + + // Default theme + ImGui::StyleColorsDark(this); +} + +// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. +// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. +void ImGuiStyle::ScaleAllSizes(float scale_factor) +{ + WindowPadding = ImFloor(WindowPadding * scale_factor); + WindowRounding = ImFloor(WindowRounding * scale_factor); + WindowMinSize = ImFloor(WindowMinSize * scale_factor); + ChildRounding = ImFloor(ChildRounding * scale_factor); + PopupRounding = ImFloor(PopupRounding * scale_factor); + FramePadding = ImFloor(FramePadding * scale_factor); + FrameRounding = ImFloor(FrameRounding * scale_factor); + ItemSpacing = ImFloor(ItemSpacing * scale_factor); + ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); + TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); + IndentSpacing = ImFloor(IndentSpacing * scale_factor); + ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor); + ScrollbarSize = ImFloor(ScrollbarSize * scale_factor); + ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); + GrabMinSize = ImFloor(GrabMinSize * scale_factor); + GrabRounding = ImFloor(GrabRounding * scale_factor); + DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); + DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); + MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); +} + +ImGuiIO::ImGuiIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); + + // Settings + ConfigFlags = ImGuiConfigFlags_None; + BackendFlags = ImGuiBackendFlags_None; + DisplaySize = ImVec2(-1.0f, -1.0f); + DeltaTime = 1.0f/60.0f; + IniSavingRate = 5.0f; + IniFilename = "imgui.ini"; + LogFilename = "imgui_log.txt"; + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; + for (int i = 0; i < ImGuiKey_COUNT; i++) + KeyMap[i] = -1; + KeyRepeatDelay = 0.250f; + KeyRepeatRate = 0.050f; + UserData = NULL; + + Fonts = NULL; + FontGlobalScale = 1.0f; + FontDefault = NULL; + FontAllowUserScaling = false; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); + DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f); + + // Miscellaneous configuration options +#ifdef __APPLE__ + ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag +#else + ConfigMacOSXBehaviors = false; +#endif + ConfigInputTextCursorBlink = true; + ConfigResizeWindowsFromEdges = false; + + // Platform Functions + BackendPlatformName = BackendRendererName = NULL; + GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations + SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; + ClipboardUserData = NULL; + ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; + ImeWindowHandle = NULL; + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + RenderDrawListsFn = NULL; +#endif + + // Input (NB: we already have memset zero the entire structure!) + MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); + MouseDragThreshold = 6.0f; + for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f; +} + +// Pass in translated ASCII characters for text input. +// - with glfw you can get those from the callback set in glfwSetCharCallback() +// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +void ImGuiIO::AddInputCharacter(ImWchar c) +{ + const int n = ImStrlenW(InputCharacters); + if (n + 1 < IM_ARRAYSIZE(InputCharacters)) + { + InputCharacters[n] = c; + InputCharacters[n+1] = '\0'; + } +} + +void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) +{ + // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more + const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); + ImWchar wchars[wchars_buf_len]; + ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); + for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) + AddInputCharacter(wchars[i]); +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions) +//----------------------------------------------------------------------------- + +ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) +{ + ImVec2 ap = p - a; + ImVec2 ab_dir = b - a; + float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; + if (dot < 0.0f) + return a; + float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y; + if (dot > ab_len_sqr) + return b; + return a + ab_dir * dot / ab_len_sqr; +} + +bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return ((b1 == b2) && (b2 == b3)); +} + +void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w) +{ + ImVec2 v0 = b - a; + ImVec2 v1 = c - a; + ImVec2 v2 = p - a; + const float denom = v0.x * v1.y - v1.x * v0.y; + out_v = (v2.x * v1.y - v1.x * v2.y) / denom; + out_w = (v0.x * v2.y - v2.x * v0.y) / denom; + out_u = 1.0f - out_v - out_w; +} + +ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) +{ + ImVec2 proj_ab = ImLineClosestPoint(a, b, p); + ImVec2 proj_bc = ImLineClosestPoint(b, c, p); + ImVec2 proj_ca = ImLineClosestPoint(c, a, p); + float dist2_ab = ImLengthSqr(p - proj_ab); + float dist2_bc = ImLengthSqr(p - proj_bc); + float dist2_ca = ImLengthSqr(p - proj_ca); + float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); + if (m == dist2_ab) + return proj_ab; + if (m == dist2_bc) + return proj_bc; + return proj_ca; +} + +int ImStricmp(const char* str1, const char* str2) +{ + int d; + while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } + return d; +} + +int ImStrnicmp(const char* str1, const char* str2, size_t count) +{ + int d = 0; + while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } + return d; +} + +void ImStrncpy(char* dst, const char* src, size_t count) +{ + if (count < 1) return; + strncpy(dst, src, count); + dst[count-1] = 0; +} + +char* ImStrdup(const char *str) +{ + size_t len = strlen(str) + 1; + void* buf = ImGui::MemAlloc(len); + return (char*)memcpy(buf, (const void*)str, len); +} + +const char* ImStrchrRange(const char* str, const char* str_end, char c) +{ + const char* p = (const char*)memchr(str, (int)c, str_end - str); + return p; +} + +int ImStrlenW(const ImWchar* str) +{ + //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits + int n = 0; + while (*str++) n++; + return n; +} + +// Find end-of-line. Return pointer will point to either first \n, either str_end. +const char* ImStreolRange(const char* str, const char* str_end) +{ + const char* p = (const char*)memchr(str, '\n', str_end - str); + return p ? p : str_end; +} + +const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line +{ + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) +{ + if (!needle_end) + needle_end = needle + strlen(needle); + + const char un0 = (char)toupper(*needle); + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) + { + if (toupper(*haystack) == un0) + { + const char* b = needle + 1; + for (const char* a = haystack + 1; b < needle_end; a++, b++) + if (toupper(*a) != toupper(*b)) + break; + if (b == needle_end) + return haystack; + } + haystack++; + } + return NULL; +} + +// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. +void ImStrTrimBlanks(char* buf) +{ + char* p = buf; + while (p[0] == ' ' || p[0] == '\t') // Leading blanks + p++; + char* p_start = p; + while (*p != 0) // Find end of string + p++; + while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks + p--; + if (p_start != buf) // Copy memory if we had leading blanks + memmove(buf, p_start, p - p_start); + buf[p - p_start] = 0; // Zero terminate +} + +// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). +// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. +// B) When buf==NULL vsnprintf() will return the output size. +#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS + +#if defined(_MSC_VER) && !defined(vsnprintf) +#define vsnprintf _vsnprintf +#endif + +int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + int w = vsnprintf(buf, buf_size, fmt, args); + va_end(args); + if (buf == NULL) + return w; + if (w == -1 || w >= (int)buf_size) + w = (int)buf_size - 1; + buf[w] = 0; + return w; +} + +int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) +{ + int w = vsnprintf(buf, buf_size, fmt, args); + if (buf == NULL) + return w; + if (w == -1 || w >= (int)buf_size) + w = (int)buf_size - 1; + buf[w] = 0; + return w; +} +#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS + +// Pass data_size==0 for zero-terminated strings +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImU32 ImHash(const void* data, int data_size, ImU32 seed) +{ + static ImU32 crc32_lut[256] = { 0 }; + if (!crc32_lut[1]) + { + const ImU32 polynomial = 0xEDB88320; + for (ImU32 i = 0; i < 256; i++) + { + ImU32 crc = i; + for (ImU32 j = 0; j < 8; j++) + crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); + crc32_lut[i] = crc; + } + } + + seed = ~seed; + ImU32 crc = seed; + const unsigned char* current = (const unsigned char*)data; + + if (data_size > 0) + { + // Known size + while (data_size--) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; + } + else + { + // Zero-terminated string + while (unsigned char c = *current++) + { + // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. + // Because this syntax is rarely used we are optimizing for the common case. + // - If we reach ### in the string we discard the hash so far and reset to the seed. + // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. + if (c == '#' && current[0] == '#' && current[1] == '#') + crc = seed; + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; + } + } + return ~crc; +} + +FILE* ImFileOpen(const char* filename, const char* mode) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__) + // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) + const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; + const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; + ImVector buf; + buf.resize(filename_wsize + mode_wsize); + ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); + ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); + return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); +#else + return fopen(filename, mode); +#endif +} + +// Load file content into memory +// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() +void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes) +{ + IM_ASSERT(filename && file_open_mode); + if (out_file_size) + *out_file_size = 0; + + FILE* f; + if ((f = ImFileOpen(filename, file_open_mode)) == NULL) + return NULL; + + long file_size_signed; + if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) + { + fclose(f); + return NULL; + } + + size_t file_size = (size_t)file_size_signed; + void* file_data = ImGui::MemAlloc(file_size + padding_bytes); + if (file_data == NULL) + { + fclose(f); + return NULL; + } + if (fread(file_data, 1, file_size, f) != file_size) + { + fclose(f); + ImGui::MemFree(file_data); + return NULL; + } + if (padding_bytes > 0) + memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes); + + fclose(f); + if (out_file_size) + *out_file_size = file_size; + + return file_data; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +//----------------------------------------------------------------------------- + +// Convert UTF-8 to 32-bits character, process single character input. +// Based on stb_from_utf8() from github.com/nothings/stb/ +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) +{ + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 2) return 1; + if (*str < 0xc2) return 2; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return 2; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 3) return 1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; + if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return 3; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 3; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 4) return 1; + if (*str > 0xf4) return 4; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; + if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 4; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return 4; + *out_char = c; + return 4; + } + *out_char = 0; + return 0; +} + +int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) +{ + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + if (c >= 0xd800 && c < 0xdc00) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } +} + +// Not optimal but we very rarely use this function. +int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) +{ + unsigned int dummy = 0; + return ImTextCharFromUtf8(&dummy, in_text, in_text_end); +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) return 1; + if (c < 0x800) return 2; + if (c >= 0xdc00 && c < 0xe000) return 0; + if (c >= 0xd800 && c < 0xdc00) return 4; + return 3; +} + +int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_out = buf; + const char* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_out++ = (char)c; + else + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + } + *buf_out = 0; + return (int)(buf_out - buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPER/UTILTIES (Color functions) +// Note: The Convert functions are early design which are not consistent with other API. +//----------------------------------------------------------------------------- + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f/255.0f; + return ImVec4( + ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); +} + +ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) +{ + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; + return out; +} + +// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv +void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) +{ + float K = 0.f; + if (g < b) + { + ImSwap(g, b); + K = -1.f; + } + if (r < g) + { + ImSwap(r, g); + K = -2.f / 6.f - K; + } + + const float chroma = r - (g < b ? g : b); + out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f)); + out_s = chroma / (r + 1e-20f); + out_v = r; +} + +// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +// also http://en.wikipedia.org/wiki/HSL_and_HSV +void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) +{ + if (s == 0.0f) + { + // gray + out_r = out_g = out_b = v; + return; + } + + h = ImFmod(h, 1.0f) / (60.0f/360.0f); + int i = (int)h; + float f = h - (float)i; + float p = v * (1.0f - s); + float q = v * (1.0f - s * f); + float t = v * (1.0f - s * (1.0f - f)); + + switch (i) + { + case 0: out_r = v; out_g = t; out_b = p; break; + case 1: out_r = q; out_g = v; out_b = p; break; + case 2: out_r = p; out_g = v; out_b = t; break; + case 3: out_r = p; out_g = q; out_b = v; break; + case 4: out_r = t; out_g = p; out_b = v; break; + case 5: default: out_r = v; out_g = p; out_b = q; break; + } +} + +ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) +{ + ImGuiStyle& style = GImGui->Style; + ImVec4 c = style.Colors[idx]; + c.w *= style.Alpha * alpha_mul; + return ColorConvertFloat4ToU32(c); +} + +ImU32 ImGui::GetColorU32(const ImVec4& col) +{ + ImGuiStyle& style = GImGui->Style; + ImVec4 c = col; + c.w *= style.Alpha; + return ColorConvertFloat4ToU32(c); +} + +const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx) +{ + ImGuiStyle& style = GImGui->Style; + return style.Colors[idx]; +} + +ImU32 ImGui::GetColorU32(ImU32 col) +{ + float style_alpha = GImGui->Style.Alpha; + if (style_alpha >= 1.0f) + return col; + ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; + a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range. + return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStorage +// Helper: Key->value storage +//----------------------------------------------------------------------------- + +// std::lower_bound but without the bullshit +static ImVector::iterator LowerBound(ImVector& data, ImGuiID key) +{ + ImVector::iterator first = data.begin(); + ImVector::iterator last = data.end(); + size_t count = (size_t)(last - first); + while (count > 0) + { + size_t count2 = count >> 1; + ImVector::iterator mid = first + count2; + if (mid->key < key) + { + first = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return first; +} + +// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. +void ImGuiStorage::BuildSortByKey() +{ + struct StaticFunc + { + static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs) + { + // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. + if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1; + if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1; + return 0; + } + }; + if (Data.Size > 1) + ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID); +} + +int ImGuiStorage::GetInt(ImGuiID key, int default_val) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_i; +} + +bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const +{ + return GetInt(key, default_val ? 1 : 0) != 0; +} + +float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_f; +} + +void* ImGuiStorage::GetVoidPtr(ImGuiID key) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return NULL; + return it->val_p; +} + +// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. +int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_i; +} + +bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool*)GetIntRef(key, default_val ? 1 : 0); +} + +float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_f; +} + +void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_p; +} + +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) +void ImGuiStorage::SetInt(ImGuiID key, int val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_i = val; +} + +void ImGuiStorage::SetBool(ImGuiID key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + +void ImGuiStorage::SetFloat(ImGuiID key, float val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_f = val; +} + +void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_p = val; +} + +void ImGuiStorage::SetAllInt(int v) +{ + for (int i = 0; i < Data.Size; i++) + Data[i].val_i = v; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiTextFilter +//----------------------------------------------------------------------------- + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) +{ + if (default_filter) + { + ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); + Build(); + } + else + { + InputBuf[0] = 0; + CountGrep = 0; + } +} + +bool ImGuiTextFilter::Draw(const char* label, float width) +{ + if (width != 0.0f) + ImGui::PushItemWidth(width); + bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + if (width != 0.0f) + ImGui::PopItemWidth(); + if (value_changed) + Build(); + return value_changed; +} + +void ImGuiTextFilter::TextRange::split(char separator, ImVector* out) const +{ + out->resize(0); + const char* wb = b; + const char* we = wb; + while (we < e) + { + if (*we == separator) + { + out->push_back(TextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out->push_back(TextRange(wb, we)); +} + +void ImGuiTextFilter::Build() +{ + Filters.resize(0); + TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); + input_range.split(',', &Filters); + + CountGrep = 0; + for (int i = 0; i != Filters.Size; i++) + { + TextRange& f = Filters[i]; + while (f.b < f.e && ImCharIsBlankA(f.b[0])) + f.b++; + while (f.e > f.b && ImCharIsBlankA(f.e[-1])) + f.e--; + if (f.empty()) + continue; + if (Filters[i].b[0] != '-') + CountGrep += 1; + } +} + +bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const +{ + if (Filters.empty()) + return true; + + if (text == NULL) + text = ""; + + for (int i = 0; i != Filters.Size; i++) + { + const TextRange& f = Filters[i]; + if (f.empty()) + continue; + if (f.b[0] == '-') + { + // Subtract + if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) + return true; + } + } + + // Implicit * grep + if (CountGrep == 0) + return true; + + return false; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiTextBuffer +//----------------------------------------------------------------------------- + +// On some platform vsnprintf() takes va_list by reference and modifies it. +// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. +#ifndef va_copy +#if defined(__GNUC__) || defined(__clang__) +#define va_copy(dest, src) __builtin_va_copy(dest, src) +#else +#define va_copy(dest, src) (dest = src) +#endif +#endif + +char ImGuiTextBuffer::EmptyString[1] = { 0 }; + +// Helper: Text buffer for logging/accumulating text +void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) +{ + va_list args_copy; + va_copy(args_copy, args); + + int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. + if (len <= 0) + { + va_end(args_copy); + return; + } + + // Add zero-terminator the first time + const int write_off = (Buf.Size != 0) ? Buf.Size : 1; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int double_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); + } + + Buf.resize(needed_sz); + ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy); + va_end(args_copy); +} + +void ImGuiTextBuffer::appendf(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + appendfv(fmt, args); + va_end(args); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiListClipper +// This is currently not as flexible/powerful as it should be, needs some rework (see TODO) +//----------------------------------------------------------------------------- + +static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +{ + // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. + // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. + // The clipper should probably have a 4th step to display the last item in a regular manner. + ImGui::SetCursorPosY(pos_y); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + if (window->DC.ColumnsSet) + window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 +// Use case B: Begin() called from constructor with items_height>0 +// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. +void ImGuiListClipper::Begin(int count, float items_height) +{ + StartPosY = ImGui::GetCursorPosY(); + ItemsHeight = items_height; + ItemsCount = count; + StepNo = 0; + DisplayEnd = DisplayStart = -1; + if (ItemsHeight > 0.0f) + { + ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display + if (DisplayStart > 0) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + StepNo = 2; + } +} + +void ImGuiListClipper::End() +{ + if (ItemsCount < 0) + return; + // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. + if (ItemsCount < INT_MAX) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + ItemsCount = -1; + StepNo = 3; +} + +bool ImGuiListClipper::Step() +{ + if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) + { + ItemsCount = -1; + return false; + } + if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. + { + DisplayStart = 0; + DisplayEnd = 1; + StartPosY = ImGui::GetCursorPosY(); + StepNo = 1; + return true; + } + if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. + { + if (ItemsCount == 1) { ItemsCount = -1; return false; } + float items_height = ImGui::GetCursorPosY() - StartPosY; + IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically + Begin(ItemsCount-1, items_height); + DisplayStart++; + DisplayEnd++; + StepNo = 3; + return true; + } + if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + { + IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); + StepNo = 3; + return true; + } + if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. + End(); + return false; +} + +//----------------------------------------------------------------------------- +// [SECTION] RENDER HELPERS +// Those (internal) functions are currently quite a legacy mess - their signature and behavior will change. +// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state. +//----------------------------------------------------------------------------- + +const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) +{ + const char* text_display_end = text; + if (!text_end) + text_end = (const char*)-1; + + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; + return text_display_end; +} + +// Internal ImGui functions to render text +// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() +void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Hide anything after a '##' string + const char* text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindRenderedTextEnd(text, text_end); + } + else + { + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + text_display_end = text_end; + } + + if (text != text_display_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); + } +} + +void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + + if (text != text_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_end); + } +} + +// Default clip_rect uses (pos_min,pos_max) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) +{ + // Hide anything after a '##' string + const char* text_display_end = FindRenderedTextEnd(text, text_end); + const int text_len = (int)(text_display_end - text); + if (text_len == 0) + return; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Perform CPU side clipping for single clipped element to avoid using scissor state + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + + const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; + const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min + need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); + + // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + + // Render + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + } + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); +} + +// Render a rectangle shaped with optional rounding and borders +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); + const float border_size = g.Style.FrameBorderSize; + if (border && border_size > 0.0f) + { + window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); + } +} + +void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const float border_size = g.Style.FrameBorderSize; + if (border_size > 0.0f) + { + window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); + } +} + +// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state +void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale) +{ + ImGuiContext& g = *GImGui; + + const float h = g.FontSize * 1.00f; + float r = h * 0.40f * scale; + ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale); + + ImVec2 a, b, c; + switch (dir) + { + case ImGuiDir_Up: + case ImGuiDir_Down: + if (dir == ImGuiDir_Up) r = -r; + a = ImVec2(+0.000f,+0.750f) * r; + b = ImVec2(-0.866f,-0.750f) * r; + c = ImVec2(+0.866f,-0.750f) * r; + break; + case ImGuiDir_Left: + case ImGuiDir_Right: + if (dir == ImGuiDir_Left) r = -r; + a = ImVec2(+0.750f,+0.000f) * r; + b = ImVec2(-0.750f,+0.866f) * r; + c = ImVec2(-0.750f,-0.866f) * r; + break; + case ImGuiDir_None: + case ImGuiDir_COUNT: + IM_ASSERT(0); + break; + } + + g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text)); +} + +void ImGui::RenderBullet(ImVec2 pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); +} + +void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + float thickness = ImMax(sz / 5.0f, 1.0f); + sz -= thickness*0.5f; + pos += ImVec2(thickness*0.25f, thickness*0.25f); + + float third = sz / 3.0f; + float bx = pos.x + third; + float by = pos.y + sz - third*0.5f; + window->DrawList->PathLineTo(ImVec2(bx - third, by - third)); + window->DrawList->PathLineTo(ImVec2(bx, by)); + window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2)); + window->DrawList->PathStroke(col, false, thickness); +} + +void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags) +{ + ImGuiContext& g = *GImGui; + if (id != g.NavId) + return; + if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw)) + return; + ImGuiWindow* window = g.CurrentWindow; + if (window->DC.NavHideHighlightOneFrame) + return; + + float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; + ImRect display_rect = bb; + display_rect.ClipWith(window->ClipRect); + if (flags & ImGuiNavHighlightFlags_TypeDefault) + { + const float THICKNESS = 2.0f; + const float DISTANCE = 3.0f + THICKNESS * 0.5f; + display_rect.Expand(ImVec2(DISTANCE,DISTANCE)); + bool fully_visible = window->ClipRect.Contains(display_rect); + if (!fully_visible) + window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); + window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); + if (!fully_visible) + window->DrawList->PopClipRect(); + } + if (flags & ImGuiNavHighlightFlags_TypeThin) + { + window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +//----------------------------------------------------------------------------- + +// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods +ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) + : DrawListInst(&context->DrawListSharedData) +{ + Name = ImStrdup(name); + ID = ImHash(name, 0); + IDStack.push_back(ID); + Flags = 0; + Pos = ImVec2(0.0f, 0.0f); + Size = SizeFull = ImVec2(0.0f, 0.0f); + SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); + WindowPadding = ImVec2(0.0f, 0.0f); + WindowRounding = 0.0f; + WindowBorderSize = 0.0f; + MoveId = GetID("#MOVE"); + ChildId = 0; + Scroll = ImVec2(0.0f, 0.0f); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + ScrollbarSizes = ImVec2(0.0f, 0.0f); + ScrollbarX = ScrollbarY = false; + Active = WasActive = false; + WriteAccessed = false; + Collapsed = false; + WantCollapseToggle = false; + SkipItems = false; + Appearing = false; + Hidden = false; + HasCloseButton = false; + BeginCount = 0; + BeginOrderWithinParent = -1; + BeginOrderWithinContext = -1; + PopupId = 0; + AutoFitFramesX = AutoFitFramesY = -1; + AutoFitOnlyGrows = false; + AutoFitChildAxises = 0x00; + AutoPosLastDirection = ImGuiDir_None; + HiddenFramesRegular = HiddenFramesForResize = 0; + SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; + SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); + + LastFrameActive = -1; + ItemWidthDefault = 0.0f; + FontWindowScale = 1.0f; + SettingsIdx = -1; + + DrawList = &DrawListInst; + DrawList->_OwnerName = Name; + ParentWindow = NULL; + RootWindow = NULL; + RootWindowForTitleBarHighlight = NULL; + RootWindowForNav = NULL; + + NavLastIds[0] = NavLastIds[1] = 0; + NavRectRel[0] = NavRectRel[1] = ImRect(); + NavLastChildNavWindow = NULL; + + FocusIdxAllCounter = FocusIdxTabCounter = -1; + FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; + FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; +} + +ImGuiWindow::~ImGuiWindow() +{ + IM_ASSERT(DrawList == &DrawListInst); + IM_DELETE(Name); + for (int i = 0; i != ColumnsStorage.Size; i++) + ColumnsStorage[i].~ImGuiColumnsSet(); +} + +ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); + ImGui::KeepAliveID(id); + return id; +} + +ImGuiID ImGuiWindow::GetID(const void* ptr) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHash(&ptr, sizeof(void*), seed); + ImGui::KeepAliveID(id); + return id; +} + +ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + return ImHash(str, str_end ? (int)(str_end - str) : 0, seed); +} + +ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr) +{ + ImGuiID seed = IDStack.back(); + return ImHash(&ptr, sizeof(void*), seed); +} + +// This is only used in rare/specific situations to manufacture an ID out of nowhere. +ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) +{ + ImGuiID seed = IDStack.back(); + const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) }; + ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed); + ImGui::KeepAliveID(id); + return id; +} + +static void SetCurrentWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow = window; + if (window) + g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); +} + +void ImGui::SetNavID(ImGuiID id, int nav_layer) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindow); + IM_ASSERT(nav_layer == 0 || nav_layer == 1); + g.NavId = id; + g.NavWindow->NavLastIds[nav_layer] = id; +} + +void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel) +{ + ImGuiContext& g = *GImGui; + SetNavID(id, nav_layer); + g.NavWindow->NavRectRel[nav_layer] = rect_rel; + g.NavMousePosDirty = true; + g.NavDisableHighlight = false; + g.NavDisableMouseHover = true; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.ActiveIdIsJustActivated = (g.ActiveId != id); + if (g.ActiveIdIsJustActivated) + { + g.ActiveIdTimer = 0.0f; + g.ActiveIdHasBeenEdited = false; + if (id != 0) + { + g.LastActiveId = id; + g.LastActiveIdTimer = 0.0f; + } + } + g.ActiveId = id; + g.ActiveIdAllowNavDirFlags = 0; + g.ActiveIdAllowOverlap = false; + g.ActiveIdWindow = window; + if (id) + { + g.ActiveIdIsAlive = id; + g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse; + } +} + +void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(id != 0); + + // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it. + const int nav_layer = window->DC.NavLayerCurrent; + if (g.NavWindow != window) + g.NavInitRequest = false; + g.NavId = id; + g.NavWindow = window; + g.NavLayer = nav_layer; + window->NavLastIds[nav_layer] = id; + if (window->DC.LastItemId == id) + window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos); + + if (g.ActiveIdSource == ImGuiInputSource_Nav) + g.NavDisableMouseHover = true; + else + g.NavDisableHighlight = true; +} + +void ImGui::ClearActiveID() +{ + SetActiveID(0, NULL); +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; + if (id != 0 && g.HoveredIdPreviousFrame != id) + g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; +} + +ImGuiID ImGui::GetHoveredID() +{ + ImGuiContext& g = *GImGui; + return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; +} + +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = id; + if (g.ActiveIdPreviousFrame == id) + g.ActiveIdPreviousFrameIsAlive = true; +} + +void ImGui::MarkItemEdited(ImGuiID id) +{ + // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit(). + // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data. + (void)id; // Avoid unused variable warnings when asserts are compiled out. + ImGuiContext& g = *GImGui; + IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive); + //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); + g.ActiveIdHasBeenEdited = true; + g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; +} + +static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags) +{ + // An active popup disable hovering on other windows (apart from its own children) + // FIXME-OPT: This could be cached/stored within the window. + ImGuiContext& g = *GImGui; + if (g.NavWindow) + if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow) + if (focused_root_window->WasActive && focused_root_window != window->RootWindow) + { + // For the purpose of those flags we differentiate "standard popup" from "modal popup" + // NB: The order of those two tests is important because Modal windows are also Popups. + if (focused_root_window->Flags & ImGuiWindowFlags_Modal) + return false; + if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + return false; + } + + return true; +} + +// Advance cursor given item size for layout. +void ImGui::ItemSize(const ImVec2& size, float text_offset_y) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + // Always align ourselves on pixel boundaries + const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y); + const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); + //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y); + //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG] + + window->DC.PrevLineSize.y = line_height; + window->DC.PrevLineTextBaseOffset = text_base_offset; + window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f; + + // Horizontal layout mode + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + SameLine(); +} + +void ImGui::ItemSize(const ImRect& bb, float text_offset_y) +{ + ItemSize(bb.GetSize(), text_offset_y); +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). +bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) +{ +#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS + ImGuiTestEngineHook_ItemAdd(bb, id, nav_bb_arg); +#endif + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (id != 0) + { + // Navigation processing runs prior to clipping early-out + // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget + // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window. + // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick) + window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask; + if (g.NavId == id || g.NavAnyRequest) + if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) + if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) + NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id); + } + + window->DC.LastItemId = id; + window->DC.LastItemRect = bb; + window->DC.LastItemStatusFlags = 0; + + // Clipping test + const bool is_clipped = IsClippedEx(bb, id, false); + if (is_clipped) + return false; + //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] + + // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) + if (IsMouseHoveringRect(bb.Min, bb.Max)) + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect; + return true; +} + +// This is roughly matching the behavior of internal-facing ItemHoverable() +// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() +// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId +bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.NavDisableMouseHover && !g.NavDisableHighlight) + return IsItemFocused(); + + // Test for bounding box overlap, as updated as ItemAdd() + if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) + return false; + IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function + + // Test if we are hovering the right window (our window could be behind another window) + // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself. + // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while. + //if (g.HoveredWindow != window) + // return false; + if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped)) + return false; + + // Test if another item is active (e.g. being dragged) + if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) + return false; + + // Test if interactions on this window are blocked by an active popup or modal + if (!IsWindowContentHoverable(window, flags)) + return false; + + // Test if the item is disabled + if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) + return false; + + // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case. + if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) + return false; + return true; +} + +// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). +bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) + return false; + + ImGuiWindow* window = g.CurrentWindow; + if (g.HoveredWindow != window) + return false; + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) + return false; + if (!IsMouseHoveringRect(bb.Min, bb.Max)) + return false; + if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) + return false; + if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) + return false; + + SetHoveredID(id); + return true; +} + +bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (!bb.Overlaps(window->ClipRect)) + if (id == 0 || id != g.ActiveId) + if (clip_even_when_logged || !g.LogEnabled) + return true; + return false; +} + +bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop) +{ + ImGuiContext& g = *GImGui; + + const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; + window->FocusIdxAllCounter++; + if (is_tab_stop) + window->FocusIdxTabCounter++; + + // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item. + // Note that we can always TAB out of a widget that doesn't allow tabbing in. + if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)) + window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. + + if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) + return true; + if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) + { + g.NavJustTabbedId = id; + return true; + } + + return false; +} + +void ImGui::FocusableItemUnregister(ImGuiWindow* window) +{ + window->FocusIdxAllCounter--; + window->FocusIdxTabCounter--; +} + +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) +{ + ImGuiContext& g = *GImGui; + ImVec2 content_max; + if (size.x < 0.0f || size.y < 0.0f) + content_max = g.CurrentWindow->Pos + GetContentRegionMax(); + if (size.x <= 0.0f) + size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; + if (size.y <= 0.0f) + size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; + return size; +} + +float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) +{ + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiWindow* window = GetCurrentWindowRead(); + if (wrap_pos_x == 0.0f) + wrap_pos_x = GetContentRegionMax().x + window->Pos.x; + else if (wrap_pos_x > 0.0f) + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + + return ImMax(wrap_pos_x - pos.x, 1.0f); +} + +void* ImGui::MemAlloc(size_t size) +{ + if (ImGuiContext* ctx = GImGui) + ctx->IO.MetricsActiveAllocations++; + return GImAllocatorAllocFunc(size, GImAllocatorUserData); +} + +void ImGui::MemFree(void* ptr) +{ + if (ptr) + if (ImGuiContext* ctx = GImGui) + ctx->IO.MetricsActiveAllocations--; + return GImAllocatorFreeFunc(ptr, GImAllocatorUserData); +} + +const char* ImGui::GetClipboardText() +{ + return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; +} + +void ImGui::SetClipboardText(const char* text) +{ + if (GImGui->IO.SetClipboardTextFn) + GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); +} + +const char* ImGui::GetVersion() +{ + return IMGUI_VERSION; +} + +// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself +// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module +ImGuiContext* ImGui::GetCurrentContext() +{ + return GImGui; +} + +void ImGui::SetCurrentContext(ImGuiContext* ctx) +{ +#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC + IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. +#else + GImGui = ctx; +#endif +} + +// Helper function to verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit +// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. you may see different structures from what imgui.cpp sees which is highly problematic. +bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert) +{ + bool error = false; + if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); } + if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); } + if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); } + if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); } + if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); } + if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); } + return !error; +} + +void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data) +{ + GImAllocatorAllocFunc = alloc_func; + GImAllocatorFreeFunc = free_func; + GImAllocatorUserData = user_data; +} + +ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) +{ + ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas); + if (GImGui == NULL) + SetCurrentContext(ctx); + Initialize(ctx); + return ctx; +} + +void ImGui::DestroyContext(ImGuiContext* ctx) +{ + if (ctx == NULL) + ctx = GImGui; + Shutdown(ctx); + if (GImGui == ctx) + SetCurrentContext(NULL); + IM_DELETE(ctx); +} + +ImGuiIO& ImGui::GetIO() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); + return GImGui->IO; +} + +ImGuiStyle& ImGui::GetStyle() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); + return GImGui->Style; +} + +// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame() +ImDrawData* ImGui::GetDrawData() +{ + ImGuiContext& g = *GImGui; + return g.DrawData.Valid ? &g.DrawData : NULL; +} + +double ImGui::GetTime() +{ + return GImGui->Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui->FrameCount; +} + +static ImDrawList* GetOverlayDrawList(ImGuiWindow*) +{ + // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'viewport' branches. + return &GImGui->OverlayDrawList; +} + +ImDrawList* ImGui::GetOverlayDrawList() +{ + return &GImGui->OverlayDrawList; +} + +ImDrawListSharedData* ImGui::GetDrawListSharedData() +{ + return &GImGui->DrawListSharedData; +} + +void ImGui::StartMouseMovingWindow(ImGuiWindow* window) +{ + // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. + ImGuiContext& g = *GImGui; + FocusWindow(window); + SetActiveID(window->MoveId, window); + g.NavDisableHighlight = true; + g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; + if (!(window->Flags & ImGuiWindowFlags_NoMove) && !(window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) + g.MovingWindow = window; +} + +// Handle mouse moving window +// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() +void ImGui::UpdateMouseMovingWindow() +{ + ImGuiContext& g = *GImGui; + if (g.MovingWindow != NULL) + { + // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. + KeepAliveID(g.ActiveId); + IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow); + ImGuiWindow* moving_window = g.MovingWindow->RootWindow; + if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos)) + { + ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; + if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) + { + MarkIniSettingsDirty(moving_window); + SetWindowPos(moving_window, pos, ImGuiCond_Always); + } + FocusWindow(g.MovingWindow); + } + else + { + ClearActiveID(); + g.MovingWindow = NULL; + } + } + else + { + // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. + if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId) + { + KeepAliveID(g.ActiveId); + if (!g.IO.MouseDown[0]) + ClearActiveID(); + } + } +} + +static bool IsWindowActiveAndVisible(ImGuiWindow* window) +{ + return (window->Active) && (!window->Hidden); +} + +static void ImGui::UpdateMouseInputs() +{ + ImGuiContext& g = *GImGui; + + // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) + if (IsMousePosValid(&g.IO.MousePos)) + g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos); + + // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta + if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev)) + g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; + else + g.IO.MouseDelta = ImVec2(0.0f, 0.0f); + if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f) + g.NavDisableMouseHover = false; + + g.IO.MousePosPrev = g.IO.MousePos; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; + g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; + g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; + g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; + g.IO.MouseDoubleClicked[i] = false; + if (g.IO.MouseClicked[i]) + { + if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime) + { + ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); + if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) + g.IO.MouseDoubleClicked[i] = true; + g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click + } + else + { + g.IO.MouseClickedTime[i] = g.Time; + } + g.IO.MouseClickedPos[i] = g.IO.MousePos; + g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); + g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; + } + else if (g.IO.MouseDown[i]) + { + // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold + ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); + g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos)); + g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); + g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); + } + if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation + g.NavDisableMouseHover = false; + } +} + +void ImGui::UpdateMouseWheel() +{ + ImGuiContext& g = *GImGui; + if (!g.HoveredWindow || g.HoveredWindow->Collapsed) + return; + if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) + return; + + // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set). + ImGuiWindow* window = g.HoveredWindow; + ImGuiWindow* scroll_window = window; + while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs) && scroll_window->ParentWindow) + scroll_window = scroll_window->ParentWindow; + const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs); + + if (g.IO.MouseWheel != 0.0f) + { + if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling) + { + // Zoom / Scale window + const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + const float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + + const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; + window->Pos += offset; + window->Size *= scale; + window->SizeFull *= scale; + } + else if (!g.IO.KeyCtrl && scroll_allowed) + { + // Mouse wheel vertical scrolling + float scroll_amount = 5 * scroll_window->CalcFontSize(); + scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f); + SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount); + } + } + if (g.IO.MouseWheelH != 0.0f && scroll_allowed && !g.IO.KeyCtrl) + { + // Mouse wheel horizontal scrolling (for hardware that supports it) + float scroll_amount = scroll_window->CalcFontSize(); + SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheelH * scroll_amount); + } +} + +// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) +void ImGui::UpdateHoveredWindowAndCaptureFlags() +{ + ImGuiContext& g = *GImGui; + + // Find the window hovered by mouse: + // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. + // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. + // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. + FindHoveredWindow(); + + // Modal windows prevents cursor from hovering behind them. + ImGuiWindow* modal_window = GetFrontMostPopupModal(); + if (modal_window) + if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) + g.HoveredRootWindow = g.HoveredWindow = NULL; + + // Disabled mouse? + if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) + g.HoveredWindow = g.HoveredRootWindow = NULL; + + // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. + int mouse_earliest_button_down = -1; + bool mouse_any_down = false; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + if (g.IO.MouseClicked[i]) + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + mouse_any_down |= g.IO.MouseDown[i]; + if (g.IO.MouseDown[i]) + if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down]) + mouse_earliest_button_down = i; + } + const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; + + // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) + const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; + if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) + g.HoveredWindow = g.HoveredRootWindow = NULL; + + // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app) + if (g.WantCaptureMouseNextFrame != -1) + g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0); + else + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty()); + + // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app) + if (g.WantCaptureKeyboardNextFrame != -1) + g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); + else + g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL); + if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)) + g.IO.WantCaptureKeyboard = true; + + // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible + g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; +} + +void ImGui::NewFrame() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); + ImGuiContext& g = *GImGui; + +#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS + ImGuiTestEngineHook_PreNewFrame(); +#endif + + // Check user data + // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) + IM_ASSERT(g.Initialized); + IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)"); + IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value"); + IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); + IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting"); + IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)"); + IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); + for (int n = 0; n < ImGuiKey_COUNT; n++) + IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); + + // Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP) + if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) + IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); + + // Perform simple check: the beta io.ConfigResizeWindowsFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. + if (g.IO.ConfigResizeWindowsFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) + g.IO.ConfigResizeWindowsFromEdges = false; + + // Load settings on first frame (if not explicitly loaded manually before) + if (!g.SettingsLoaded) + { + IM_ASSERT(g.SettingsWindows.empty()); + if (g.IO.IniFilename) + LoadIniSettingsFromDisk(g.IO.IniFilename); + g.SettingsLoaded = true; + } + + // Save settings (with a delay after the last modification, so we don't spam disk too much) + if (g.SettingsDirtyTimer > 0.0f) + { + g.SettingsDirtyTimer -= g.IO.DeltaTime; + if (g.SettingsDirtyTimer <= 0.0f) + { + if (g.IO.IniFilename != NULL) + SaveIniSettingsToDisk(g.IO.IniFilename); + else + g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. + g.SettingsDirtyTimer = 0.0f; + } + } + + g.Time += g.IO.DeltaTime; + g.FrameScopeActive = true; + g.FrameCount += 1; + g.TooltipOverrideCount = 0; + g.WindowsActiveCount = 0; + + // Setup current font and draw list + g.IO.Fonts->Locked = true; + SetCurrentFont(GetDefaultFont()); + IM_ASSERT(g.Font->IsLoaded()); + g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); + g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; + + g.OverlayDrawList.Clear(); + g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); + g.OverlayDrawList.PushClipRectFullScreen(); + g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it + g.DrawData.Clear(); + + // Drag and drop keep the source ID alive so even if the source disappear our state is consistent + if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId) + KeepAliveID(g.DragDropPayload.SourceId); + + // Clear reference to active widget if the widget isn't alive anymore + if (!g.HoveredIdPreviousFrame) + g.HoveredIdTimer = 0.0f; + if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId)) + g.HoveredIdNotActiveTimer = 0.0f; + if (g.HoveredId) + g.HoveredIdTimer += g.IO.DeltaTime; + if (g.HoveredId && g.ActiveId != g.HoveredId) + g.HoveredIdNotActiveTimer += g.IO.DeltaTime; + g.HoveredIdPreviousFrame = g.HoveredId; + g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; + if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) + ClearActiveID(); + if (g.ActiveId) + g.ActiveIdTimer += g.IO.DeltaTime; + g.LastActiveIdTimer += g.IO.DeltaTime; + g.ActiveIdPreviousFrame = g.ActiveId; + g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; + g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited; + g.ActiveIdIsAlive = 0; + g.ActiveIdPreviousFrameIsAlive = false; + g.ActiveIdIsJustActivated = false; + if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId) + g.ScalarAsInputTextId = 0; + + // Drag and drop + g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; + g.DragDropAcceptIdCurr = 0; + g.DragDropAcceptIdCurrRectSurface = FLT_MAX; + g.DragDropWithinSourceOrTarget = false; + + // Update keyboard input state + memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) + g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; + + // Update gamepad/keyboard directional navigation + NavUpdate(); + + // Update mouse input state + UpdateMouseInputs(); + + // Calculate frame-rate for the user, as a purely luxurious feature + g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; + g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; + g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); + g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX; + + // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) + UpdateMouseMovingWindow(); + UpdateHoveredWindowAndCaptureFlags(); + + // Background darkening/whitening + if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) + g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f); + else + g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f); + + g.MouseCursor = ImGuiMouseCursor_Arrow; + g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1; + g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default + + // Mouse wheel scrolling, scale + UpdateMouseWheel(); + + // Pressing TAB activate widget focus + if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false)) + { + if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) + g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); + else + g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0; + } + g.NavIdTabCounter = INT_MAX; + + // Mark all windows as not visible + IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + window->WasActive = window->Active; + window->Active = false; + window->WriteAccessed = false; + } + + // Closing the focused window restore focus to the first active root window in descending z-order + if (g.NavWindow && !g.NavWindow->WasActive) + FocusPreviousWindowIgnoringOne(NULL); + + // No window should be open at the beginning of the frame. + // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. + g.CurrentWindowStack.resize(0); + g.CurrentPopupStack.resize(0); + ClosePopupsOverWindow(g.NavWindow); + + // Create implicit window - we will only render it if the user has added something to it. + // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); + Begin("Debug##Default"); + +#ifdef IMGUI_ENABLE_TEST_ENGINE_HOOKS + ImGuiTestEngineHook_PostNewFrame(); +#endif +} + +void ImGui::Initialize(ImGuiContext* context) +{ + ImGuiContext& g = *context; + IM_ASSERT(!g.Initialized && !g.SettingsLoaded); + + // Add .ini handle for ImGuiWindow type + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Window"; + ini_handler.TypeHash = ImHash("Window", 0, 0); + ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen; + ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine; + ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll; + g.SettingsHandlers.push_front(ini_handler); + + g.Initialized = true; +} + +// This function is merely here to free heap allocations. +void ImGui::Shutdown(ImGuiContext* context) +{ + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + ImGuiContext& g = *context; + if (g.IO.Fonts && g.FontAtlasOwnedByContext) + { + g.IO.Fonts->Locked = false; + IM_DELETE(g.IO.Fonts); + } + g.IO.Fonts = NULL; + + // Cleanup of other data are conditional on actually having initialized ImGui. + if (!g.Initialized) + return; + + // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file) + if (g.SettingsLoaded && g.IO.IniFilename != NULL) + { + ImGuiContext* backup_context = GImGui; + SetCurrentContext(context); + SaveIniSettingsToDisk(g.IO.IniFilename); + SetCurrentContext(backup_context); + } + + // Clear everything else + for (int i = 0; i < g.Windows.Size; i++) + IM_DELETE(g.Windows[i]); + g.Windows.clear(); + g.WindowsFocusOrder.clear(); + g.WindowsSortBuffer.clear(); + g.CurrentWindow = NULL; + g.CurrentWindowStack.clear(); + g.WindowsById.Clear(); + g.NavWindow = NULL; + g.HoveredWindow = NULL; + g.HoveredRootWindow = NULL; + g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; + g.MovingWindow = NULL; + g.ColorModifiers.clear(); + g.StyleModifiers.clear(); + g.FontStack.clear(); + g.OpenPopupStack.clear(); + g.CurrentPopupStack.clear(); + g.DrawDataBuilder.ClearFreeMemory(); + g.OverlayDrawList.ClearFreeMemory(); + g.PrivateClipboard.clear(); + g.InputTextState.TextW.clear(); + g.InputTextState.InitialText.clear(); + g.InputTextState.TempBuffer.clear(); + + for (int i = 0; i < g.SettingsWindows.Size; i++) + IM_DELETE(g.SettingsWindows[i].Name); + g.SettingsWindows.clear(); + g.SettingsHandlers.clear(); + + if (g.LogFile && g.LogFile != stdout) + { + fclose(g.LogFile); + g.LogFile = NULL; + } + g.LogClipboard.clear(); + + g.Initialized = false; +} + +// FIXME: Add a more explicit sort order in the window structure. +static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs) +{ + const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs; + const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs; + if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) + return d; + return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); +} + +static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window) +{ + out_sorted_windows->push_back(window); + if (window->Active) + { + int count = window->DC.ChildWindows.Size; + if (count > 1) + ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + for (int i = 0; i < count; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (child->Active) + AddWindowToSortBuffer(out_sorted_windows, child); + } + } +} + +static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list) +{ + if (draw_list->CmdBuffer.empty()) + return; + + // Remove trailing command if unused + ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); + if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) + { + draw_list->CmdBuffer.pop_back(); + if (draw_list->CmdBuffer.empty()) + return; + } + + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly. + IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) + // If this assert triggers because you are drawing lots of stuff manually: + // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents. + // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes. + // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing: + // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API. + // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists. + if (sizeof(ImDrawIdx) == 2) + IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); + + out_list->push_back(draw_list); +} + +static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.IO.MetricsRenderWindows++; + AddDrawListToDrawData(out_render_list, window->DrawList); + for (int i = 0; i < window->DC.ChildWindows.Size; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active + AddWindowToDrawData(out_render_list, child); + } +} + +static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (window->Flags & ImGuiWindowFlags_Tooltip) + AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window); + else + AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window); +} + +void ImDrawDataBuilder::FlattenIntoSingleLayer() +{ + int n = Layers[0].Size; + int size = n; + for (int i = 1; i < IM_ARRAYSIZE(Layers); i++) + size += Layers[i].Size; + Layers[0].resize(size); + for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++) + { + ImVector& layer = Layers[layer_n]; + if (layer.empty()) + continue; + memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); + n += layer.Size; + layer.resize(0); + } +} + +static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_data) +{ + ImGuiIO& io = ImGui::GetIO(); + draw_data->Valid = true; + draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL; + draw_data->CmdListsCount = draw_lists->Size; + draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; + draw_data->DisplayPos = ImVec2(0.0f, 0.0f); + draw_data->DisplaySize = io.DisplaySize; + for (int n = 0; n < draw_lists->Size; n++) + { + draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size; + draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size; + } +} + +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +void ImGui::PopClipRect() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times. + return; + IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()"); + + // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f) + { + g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y); + g.PlatformImeLastPos = g.PlatformImePos; + } + + // Hide implicit "Debug" window if it hasn't been used + IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls, did you forget to call end on g.CurrentWindow->Name? + if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed) + g.CurrentWindow->Active = false; + End(); + + // Show CTRL+TAB list + if (g.NavWindowingTarget) + NavUpdateWindowingList(); + + // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) + if (g.DragDropActive) + { + bool is_delivered = g.DragDropPayload.Delivery; + bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); + if (is_delivered || is_elapsed) + ClearDragDrop(); + } + + // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. + if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount) + { + g.DragDropWithinSourceOrTarget = true; + SetTooltip("..."); + g.DragDropWithinSourceOrTarget = false; + } + + // Initiate moving window + if (g.ActiveId == 0 && g.HoveredId == 0) + { + if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear + { + // Click to focus window and start moving (after we're done with all our widgets) + if (g.IO.MouseClicked[0]) + { + if (g.HoveredRootWindow != NULL) + StartMouseMovingWindow(g.HoveredWindow); + else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL) + FocusWindow(NULL); // Clicking on void disable focus + } + + // With right mouse button we close popups without changing focus + // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger) + if (g.IO.MouseClicked[1]) + { + // Find the top-most window between HoveredWindow and the front most Modal Window. + // This is where we can trim the popup stack. + ImGuiWindow* modal = GetFrontMostPopupModal(); + bool hovered_window_above_modal = false; + if (modal == NULL) + hovered_window_above_modal = true; + for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) + { + ImGuiWindow* window = g.Windows[i]; + if (window == modal) + break; + if (window == g.HoveredWindow) + hovered_window_above_modal = true; + } + ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal); + } + } + } + + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because childs may not exist yet + g.WindowsSortBuffer.resize(0); + g.WindowsSortBuffer.reserve(g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortBuffer(&g.WindowsSortBuffer, window); + } + + IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong + g.Windows.swap(g.WindowsSortBuffer); + g.IO.MetricsActiveWindows = g.WindowsActiveCount; + + // Unlock font atlas + g.IO.Fonts->Locked = false; + + // Clear Input data for next frame + g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f; + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs)); + + g.FrameScopeActive = false; + g.FrameCountEnded = g.FrameCount; +} + +void ImGui::Render() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + + if (g.FrameCountEnded != g.FrameCount) + EndFrame(); + g.FrameCountRendered = g.FrameCount; + + // Gather ImDrawList to render (for each active window) + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0; + g.DrawDataBuilder.Clear(); + ImGuiWindow* windows_to_render_front_most[2]; + windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; + windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL; + for (int n = 0; n != g.Windows.Size; n++) + { + ImGuiWindow* window = g.Windows[n]; + if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1]) + AddWindowToDrawDataSelectLayer(window); + } + for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++) + if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window + AddWindowToDrawDataSelectLayer(windows_to_render_front_most[n]); + g.DrawDataBuilder.FlattenIntoSingleLayer(); + + // Draw software mouse cursor if requested + if (g.IO.MouseDrawCursor) + RenderMouseCursor(&g.OverlayDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor); + + if (!g.OverlayDrawList.VtxBuffer.empty()) + AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList); + + // Setup ImDrawData structure for end-user + SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData); + g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount; + g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount; + + // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) + g.IO.RenderDrawListsFn(&g.DrawData); +#endif +} + +// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) +ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) +{ + ImGuiContext& g = *GImGui; + + const char* text_display_end; + if (hide_text_after_double_hash) + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string + else + text_display_end = text_end; + + ImFont* font = g.Font; + const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); + ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); + + // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field) + const float font_scale = font_size / font->FontSize; + const float character_spacing_x = 1.0f * font_scale; + if (text_size.x > 0.0f) + text_size.x -= character_spacing_x; + text_size.x = (float)(int)(text_size.x + 0.95f); + + return text_size; +} + +// Helper to calculate coarse clipping of large list of evenly sized items. +// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. +// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX +void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + *out_items_display_start = 0; + *out_items_display_end = items_count; + return; + } + if (window->SkipItems) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } + + // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect + ImRect unclipped_rect = window->ClipRect; + if (g.NavMoveRequest) + unclipped_rect.Add(g.NavScoringRectScreen); + + const ImVec2 pos = window->DC.CursorPos; + int start = (int)((unclipped_rect.Min.y - pos.y) / items_height); + int end = (int)((unclipped_rect.Max.y - pos.y) / items_height); + + // When performing a navigation request, ensure we have one item extra in the direction we are moving to + if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up) + start--; + if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down) + end++; + + start = ImClamp(start, 0, items_count); + end = ImClamp(end + 1, start, items_count); + *out_items_display_start = start; + *out_items_display_end = end; +} + +// Find window given position, search front-to-back +// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically +// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is +// called, aka before the next Begin(). Moving window isn't affected. +static void FindHoveredWindow() +{ + ImGuiContext& g = *GImGui; + + ImGuiWindow* hovered_window = NULL; + if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) + hovered_window = g.MovingWindow; + + ImVec2 padding_regular = g.Style.TouchExtraPadding; + ImVec2 padding_for_resize_from_edges = g.IO.ConfigResizeWindowsFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS, RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS)) : padding_regular; + for (int i = g.Windows.Size - 1; i >= 0 && hovered_window == NULL; i--) + { + ImGuiWindow* window = g.Windows[i]; + if (!window->Active || window->Hidden) + continue; + if (window->Flags & ImGuiWindowFlags_NoMouseInputs) + continue; + + // Using the clipped AABB, a child window will typically be clipped by its parent (not always) + ImRect bb(window->OuterRectClipped); + if ((window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_NoResize)) + bb.Expand(padding_regular); + else + bb.Expand(padding_for_resize_from_edges); + if (!bb.Contains(g.IO.MousePos)) + continue; + + // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. + if (hovered_window == NULL) + hovered_window = window; + if (hovered_window) + break; + } + + g.HoveredWindow = hovered_window; + g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; + +} + +// Test if mouse cursor is hovering given rectangle +// NB- Rectangle is clipped by our current clip setting +// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) +bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) +{ + ImGuiContext& g = *GImGui; + + // Clip + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.ClipWith(g.CurrentWindow->ClipRect); + + // Expand for touch input + const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); + if (!rect_for_touch.Contains(g.IO.MousePos)) + return false; + return true; +} + +int ImGui::GetKeyIndex(ImGuiKey imgui_key) +{ + IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); + return GImGui->IO.KeyMap[imgui_key]; +} + +// Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]! +bool ImGui::IsKeyDown(int user_key_index) +{ + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); + return GImGui->IO.KeysDown[user_key_index]; +} + +int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate) +{ + if (t == 0.0f) + return 1; + if (t <= repeat_delay || repeat_rate <= 0.0f) + return 0; + const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate); + return (count > 0) ? count : 0; +} + +int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate) +{ + ImGuiContext& g = *GImGui; + if (key_index < 0) return false; + IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + const float t = g.IO.KeysDownDuration[key_index]; + return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate); +} + +bool ImGui::IsKeyPressed(int user_key_index, bool repeat) +{ + ImGuiContext& g = *GImGui; + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + const float t = g.IO.KeysDownDuration[user_key_index]; + if (t == 0.0f) + return true; + if (repeat && t > g.IO.KeyRepeatDelay) + return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; + return false; +} + +bool ImGui::IsKeyReleased(int user_key_index) +{ + ImGuiContext& g = *GImGui; + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]; +} + +bool ImGui::IsMouseDown(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDown[button]; +} + +bool ImGui::IsAnyMouseDown() +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) + if (g.IO.MouseDown[n]) + return true; + return false; +} + +bool ImGui::IsMouseClicked(int button, bool repeat) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + const float t = g.IO.MouseDownDuration[button]; + if (t == 0.0f) + return true; + + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((ImFmod(t - delay, rate) > rate*0.5f) != (ImFmod(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) + return true; + } + + return false; +} + +bool ImGui::IsMouseReleased(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseReleased[button]; +} + +bool ImGui::IsMouseDoubleClicked(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDoubleClicked[button]; +} + +bool ImGui::IsMouseDragging(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; +} + +ImVec2 ImGui::GetMousePos() +{ + return GImGui->IO.MousePos; +} + +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext& g = *GImGui; + if (g.CurrentPopupStack.Size > 0) + return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos; + return g.IO.MousePos; +} + +// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position +bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) +{ + if (mouse_pos == NULL) + mouse_pos = &GImGui->IO.MousePos; + const float MOUSE_INVALID = -256000.0f; + return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID; +} + +// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. +ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + if (g.IO.MouseDown[button]) + if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) + return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). + return ImVec2(0.0f, 0.0f); +} + +void ImGui::ResetMouseDragDelta(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr + g.IO.MouseClickedPos[button] = g.IO.MousePos; +} + +ImGuiMouseCursor ImGui::GetMouseCursor() +{ + return GImGui->MouseCursor; +} + +void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) +{ + GImGui->MouseCursor = cursor_type; +} + +void ImGui::CaptureKeyboardFromApp(bool capture) +{ + GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0; +} + +void ImGui::CaptureMouseFromApp(bool capture) +{ + GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0; +} + +bool ImGui::IsItemActive() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId) + { + ImGuiWindow* window = g.CurrentWindow; + return g.ActiveId == window->DC.LastItemId; + } + return false; +} + +bool ImGui::IsItemDeactivated() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId); +} + +bool ImGui::IsItemDeactivatedAfterEdit() +{ + ImGuiContext& g = *GImGui; + return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited)); +} + +bool ImGui::IsItemFocused() +{ + ImGuiContext& g = *GImGui; + return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId; +} + +bool ImGui::IsItemClicked(int mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); +} + +bool ImGui::IsAnyItemHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; +} + +bool ImGui::IsAnyItemActive() +{ + ImGuiContext& g = *GImGui; + return g.ActiveId != 0; +} + +bool ImGui::IsAnyItemFocused() +{ + ImGuiContext& g = *GImGui; + return g.NavId != 0 && !g.NavDisableHighlight; +} + +bool ImGui::IsItemVisible() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(window->DC.LastItemRect); +} + +bool ImGui::IsItemEdited() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0; +} + +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +void ImGui::SetItemAllowOverlap() +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == g.CurrentWindow->DC.LastItemId) + g.HoveredIdAllowOverlap = true; + if (g.ActiveId == g.CurrentWindow->DC.LastItemId) + g.ActiveIdAllowOverlap = true; +} + +ImVec2 ImGui::GetItemRectMin() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.Min; +} + +ImVec2 ImGui::GetItemRectMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.Max; +} + +ImVec2 ImGui::GetItemRectSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.GetSize(); +} + +static ImRect GetViewportRect() +{ + ImGuiContext& g = *GImGui; + if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) + return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); + return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); +} + +static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* parent_window = g.CurrentWindow; + + flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; + flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag + + // Size + const ImVec2 content_avail = GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); + const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00); + if (size.x <= 0.0f) + size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) + if (size.y <= 0.0f) + size.y = ImMax(content_avail.y + size.y, 4.0f); + SetNextWindowSize(size); + + // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value. + char title[256]; + if (name) + ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id); + else + ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id); + + const float backup_border_size = g.Style.ChildBorderSize; + if (!border) + g.Style.ChildBorderSize = 0.0f; + bool ret = Begin(title, NULL, flags); + g.Style.ChildBorderSize = backup_border_size; + + ImGuiWindow* child_window = g.CurrentWindow; + child_window->ChildId = id; + child_window->AutoFitChildAxises = auto_fit_axises; + + // Process navigation-in immediately so NavInit can run on first frame + if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll)) + { + FocusWindow(child_window); + NavInitWindow(child_window, false); + SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item + g.ActiveIdSource = ImGuiInputSource_Nav; + } + return ret; +} + +bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); +} + +bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + IM_ASSERT(id != 0); + return BeginChildEx(NULL, id, size_arg, border, extra_flags); +} + +void ImGui::EndChild() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss + if (window->BeginCount > 1) + { + End(); + } + else + { + ImVec2 sz = window->Size; + if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f + sz.x = ImMax(4.0f, sz.x); + if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y)) + sz.y = ImMax(4.0f, sz.y); + End(); + + ImGuiWindow* parent_window = g.CurrentWindow; + ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz); + ItemSize(sz); + if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened)) + { + ItemAdd(bb, window->ChildId); + RenderNavHighlight(bb, window->ChildId); + + // When browsing a window that has no activable items (scroll only) we keep a highlight on the child + if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) + RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); + } + else + { + // Not navigable into + ItemAdd(bb, 0); + } + } +} + +// Helper to create a child window / scrolling region that looks like a normal widget frame. +bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); + PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); + PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); + PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); + PopStyleVar(3); + PopStyleColor(); + return ret; +} + +void ImGui::EndChildFrame() +{ + EndChild(); +} + +// Save and compare stack sizes on Begin()/End() to detect usage errors +static void CheckStacksSize(ImGuiWindow* window, bool write) +{ + // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + ImGuiContext& g = *GImGui; + int* p_backup = &window->DC.StackSizesBackup[0]; + { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() + { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() + { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() + // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. + { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() + { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() + { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() + IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); +} + +static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled) +{ + window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); + window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); + window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); +} + +ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); +} + +ImGuiWindow* ImGui::FindWindowByName(const char* name) +{ + ImGuiID id = ImHash(name, 0); + return FindWindowByID(id); +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + + // Create window the first time + ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); + window->Flags = flags; + g.WindowsById.SetVoidPtr(window->ID, window); + + // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. + window->Pos = ImVec2(60, 60); + + // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID)) + { + // Retrieve settings from .ini file + window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings); + SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); + window->Pos = ImFloor(settings->Pos); + window->Collapsed = settings->Collapsed; + if (ImLengthSqr(settings->Size) > 0.00001f) + size = ImFloor(settings->Size); + } + window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size); + window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values + + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) + { + window->AutoFitFramesX = window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } + else + { + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); + } + + g.WindowsFocusOrder.push_back(window); + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.push_front(window); // Quite slow but rare and only once + else + g.Windows.push_back(window); + return window; +} + +static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) +{ + ImGuiContext& g = *GImGui; + if (g.NextWindowData.SizeConstraintCond != 0) + { + // Using -1,-1 on either X/Y axis to preserve the current size. + ImRect cr = g.NextWindowData.SizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.NextWindowData.SizeCallback) + { + ImGuiSizeCallbackData data; + data.UserData = g.NextWindowData.SizeCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.NextWindowData.SizeCallback(&data); + new_size = data.DesiredSize; + } + } + + // Minimum size + if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) + { + new_size = ImMax(new_size, g.Style.WindowMinSize); + new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows + } + return new_size; +} + +static ImVec2 CalcSizeContents(ImGuiWindow* window) +{ + ImVec2 sz; + sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x)); + sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y)); + return sz + window->WindowPadding; +} + +static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + if (window->Flags & ImGuiWindowFlags_Tooltip) + { + // Tooltip always resize + return size_contents; + } + else + { + // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. + const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0; + const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0; + ImVec2 size_min = style.WindowMinSize; + if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) + size_min = ImMin(size_min, ImVec2(4.0f, 4.0f)); + ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f)); + ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); + if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) + size_auto_fit.y += style.ScrollbarSize; + if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) + size_auto_fit.x += style.ScrollbarSize; + return size_auto_fit; + } +} + +ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) +{ + ImVec2 size_contents = CalcSizeContents(window); + return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); +} + +float ImGui::GetWindowScrollMaxX(ImGuiWindow* window) +{ + return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x)); +} + +float ImGui::GetWindowScrollMaxY(ImGuiWindow* window) +{ + return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y)); +} + +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) +{ + ImGuiContext& g = *GImGui; + ImVec2 scroll = window->Scroll; + if (window->ScrollTarget.x < FLT_MAX) + { + float cr_x = window->ScrollTargetCenterRatio.x; + scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); + } + if (window->ScrollTarget.y < FLT_MAX) + { + // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. + float cr_y = window->ScrollTargetCenterRatio.y; + float target_y = window->ScrollTarget.y; + if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) + target_y = 0.0f; + if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y) + target_y = window->SizeContents.y; + scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y); + } + scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); + if (!window->Collapsed && !window->SkipItems) + { + scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window)); + scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window)); + } + return scroll; +} + +static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) +{ + if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + return ImGuiCol_PopupBg; + if (flags & ImGuiWindowFlags_ChildWindow) + return ImGuiCol_ChildBg; + return ImGuiCol_WindowBg; +} + +static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) +{ + ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left + ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right + ImVec2 size_expected = pos_max - pos_min; + ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected); + *out_pos = pos_min; + if (corner_norm.x == 0.0f) + out_pos->x -= (size_constrained.x - size_expected.x); + if (corner_norm.y == 0.0f) + out_pos->y -= (size_constrained.y - size_expected.y); + *out_size = size_constrained; +} + +struct ImGuiResizeGripDef +{ + ImVec2 CornerPos; + ImVec2 InnerDir; + int AngleMin12, AngleMax12; +}; + +const ImGuiResizeGripDef resize_grip_def[4] = +{ + { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right + { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left + { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left + { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right +}; + +static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) +{ + ImRect rect = window->Rect(); + if (thickness == 0.0f) rect.Max -= ImVec2(1,1); + if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); + if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); + if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); + if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); + IM_ASSERT(0); + return ImRect(); +} + +// Handle resize for: Resize Grips, Borders, Gamepad +static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) +{ + ImGuiContext& g = *GImGui; + ImGuiWindowFlags flags = window->Flags; + if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + return; + if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit Debug window. + return; + + const int resize_border_count = g.IO.ConfigResizeWindowsFromEdges ? 4 : 0; + const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); + const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f); + const float grip_hover_outer_size = g.IO.ConfigResizeWindowsFromEdges ? RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS : 0.0f; + + ImVec2 pos_target(FLT_MAX, FLT_MAX); + ImVec2 size_target(FLT_MAX, FLT_MAX); + + // Manual resize grips + PushID("#RESIZE"); + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos); + + // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window + ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size); + if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x); + if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y); + bool hovered, held; + ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); + //GetOverlayDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); + if (hovered || held) + g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE; + + if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0) + { + // Manual auto-fit when double-clicking + size_target = CalcSizeAfterConstraint(window, size_auto_fit); + ClearActiveID(); + } + else if (held) + { + // Resize from any of the four corners + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPos); // Corner of the window corresponding to our corner grip + CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target); + } + if (resize_grip_n == 0 || held || hovered) + resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + } + for (int border_n = 0; border_n < resize_border_count; border_n++) + { + bool hovered, held; + ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); + ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren); + //GetOverlayDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); + if ((hovered && g.HoveredIdTimer > RESIZE_WINDOWS_FROM_EDGES_FEEDBACK_TIMER) || held) + { + g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; + if (held) *border_held = border_n; + } + if (held) + { + ImVec2 border_target = window->Pos; + ImVec2 border_posn; + if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); } + if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); } + if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); } + if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + RESIZE_WINDOWS_FROM_EDGES_HALF_THICKNESS); } + CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); + } + } + PopID(); + + // Navigation resize (keyboard/gamepad) + if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window) + { + ImVec2 nav_resize_delta; + if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift) + nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); + if (g.NavInputSource == ImGuiInputSource_NavGamepad) + nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down); + if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f) + { + const float NAV_RESIZE_SPEED = 600.0f; + nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); + g.NavWindowingToggleLayer = false; + g.NavDisableMouseHover = true; + resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); + // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. + size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); + } + } + + // Apply back modified position/size to window + if (size_target.x != FLT_MAX) + { + window->SizeFull = size_target; + MarkIniSettingsDirty(window); + } + if (pos_target.x != FLT_MAX) + { + window->Pos = ImFloor(pos_target); + MarkIniSettingsDirty(window); + } + + window->Size = window->SizeFull; +} + +void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) +{ + window->ParentWindow = parent_window; + window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; + if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) + window->RootWindow = parent_window->RootWindow; + if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; + while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened) + window->RootWindowForNav = window->RootWindowForNav->ParentWindow; +} + +// Push a new ImGui window to add widgets to. +// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +// - Begin/End can be called multiple times during the frame with the same window name to append content. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + IM_ASSERT(name != NULL); // Window name required + IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + // Find or create + ImGuiWindow* window = FindWindowByName(name); + const bool window_just_created = (window == NULL); + if (window_just_created) + { + ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. + window = CreateNewWindow(name, size_on_first_use, flags); + } + + // Automatically disable manual moving/resizing when NoInputs is set + if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; + + if (flags & ImGuiWindowFlags_NavFlattened) + IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow); + + const int current_frame = g.FrameCount; + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + if (first_begin_of_the_frame) + window->Flags = (ImGuiWindowFlags)flags; + else + flags = window->Flags; + + // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack + ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back(); + ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + window->HasCloseButton = (p_open != NULL); + + // Update the Appearing flag + bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesForResize > 0); + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; + window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed + window_just_activated_by_user |= (window != popup_ref.Window); + } + window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize); + if (window->Appearing) + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); + + // Add to stack + g.CurrentWindowStack.push_back(window); + SetCurrentWindow(window); + CheckStacksSize(window, true); + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; + popup_ref.Window = window; + g.CurrentPopupStack.push_back(popup_ref); + window->PopupId = popup_ref.PopupId; + } + + if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow)) + window->NavLastIds[0] = 0; + + // Process SetNextWindow***() calls + bool window_pos_set_by_api = false; + bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; + if (g.NextWindowData.PosCond) + { + window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; + if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) + { + // May be processed on the next frame if this is our first frame and we are measuring size + // FIXME: Look into removing the branch so everything can go through this same code path for consistency. + window->SetWindowPosVal = g.NextWindowData.PosVal; + window->SetWindowPosPivot = g.NextWindowData.PosPivotVal; + window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + } + else + { + SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); + } + } + if (g.NextWindowData.SizeCond) + { + window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); + window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); + SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); + } + if (g.NextWindowData.ContentSizeCond) + { + // Adjust passed "client size" to become a "window size" + window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal; + if (window->SizeContentsExplicit.y != 0.0f) + window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight(); + } + else if (first_begin_of_the_frame) + { + window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); + } + if (g.NextWindowData.CollapsedCond) + SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); + if (g.NextWindowData.FocusCond) + FocusWindow(window); + if (window->Appearing) + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); + + // When reusing window again multiple times a frame, just append content (don't need to setup again) + if (first_begin_of_the_frame) + { + // Initialize + const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) + UpdateWindowParentAndRootLinks(window, flags, parent_window); + + window->Active = true; + window->BeginOrderWithinParent = 0; + window->BeginOrderWithinContext = g.WindowsActiveCount++; + window->BeginCount = 0; + window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->LastFrameActive = current_frame; + window->IDStack.resize(1); + + // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS + + // Update contents size from last frame for auto-fitting (or use explicit size) + window->SizeContents = CalcSizeContents(window); + if (window->HiddenFramesRegular > 0) + window->HiddenFramesRegular--; + if (window->HiddenFramesForResize > 0) + window->HiddenFramesForResize--; + + // Hide new windows for one frame until they calculate their size + if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api)) + window->HiddenFramesForResize = 1; + + // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) + // We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. + if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) + { + window->HiddenFramesForResize = 1; + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_x_set_by_api) + window->Size.x = window->SizeFull.x = 0.f; + if (!window_size_y_set_by_api) + window->Size.y = window->SizeFull.y = 0.f; + window->SizeContents = ImVec2(0.f, 0.f); + } + } + + SetCurrentWindow(window); + + // Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies) + window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; + window->WindowPadding = style.WindowPadding; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) + window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); + window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); + window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) + { + // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar. + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) + window->WantCollapseToggle = true; + if (window->WantCollapseToggle) + { + window->Collapsed = !window->Collapsed; + MarkIniSettingsDirty(window); + FocusWindow(window); + } + } + else + { + window->Collapsed = false; + } + window->WantCollapseToggle = false; + + // SIZE + + // Calculate auto-fit size, handle automatic resize + const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents); + ImVec2 size_full_modified(FLT_MAX, FLT_MAX); + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) + { + // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. + if (!window_size_x_set_by_api) + window->SizeFull.x = size_full_modified.x = size_auto_fit.x; + if (!window_size_y_set_by_api) + window->SizeFull.y = size_full_modified.y = size_auto_fit.y; + } + else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + { + // Auto-fit may only grow window during the first few frames + // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) + window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) + window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + if (!window->Collapsed) + MarkIniSettingsDirty(window); + } + + // Apply minimum/maximum window size constraints and final size + window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull); + window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; + + // SCROLLBAR STATUS + + // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size). + if (!window->Collapsed) + { + // When reading the current size we need to read it after size constraints have been applied + float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x; + float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y; + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + if (window->ScrollbarX && !window->ScrollbarY) + window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + } + + // POSITION + + // Popup latch its initial position, will position itself when it appears next frame + if (window_just_activated_by_user) + { + window->AutoPosLastDirection = ImGuiDir_None; + if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + window->Pos = g.CurrentPopupStack.back().OpenPopupPos; + } + + // Position child window + if (flags & ImGuiWindowFlags_ChildWindow) + { + window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size; + parent_window->DC.ChildWindows.push_back(window); + if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = parent_window->DC.CursorPos; + } + + const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesForResize == 0); + if (window_pos_with_pivot) + SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering) + else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) + window->Pos = FindBestWindowPosForPopup(window); + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) + window->Pos = FindBestWindowPosForPopup(window); + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = FindBestWindowPosForPopup(window); + + // Clamp position so it stays visible + if (!(flags & ImGuiWindowFlags_ChildWindow)) + { + if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + { + ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + window->Pos = ImMax(window->Pos + window->Size, padding) - window->Size; + window->Pos = ImMin(window->Pos, g.IO.DisplaySize - padding); + } + } + window->Pos = ImFloor(window->Pos); + + // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; + + // Prepare for item focus requests + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; + window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; + + // Apply scrolling + window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true); + window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + + // Apply window focus (new and reactivated windows are moved to front) + bool want_focus = false; + if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) + want_focus = true; + + // Handle manual resize: Resize Grips, Borders, Gamepad + int border_held = -1; + ImU32 resize_grip_col[4] = { 0 }; + const int resize_grip_count = g.IO.ConfigResizeWindowsFromEdges ? 2 : 1; // 4 + const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); + if (!window->Collapsed) + UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); + + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); + else + window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); + + // DRAWING + + // Setup draw list and outer clipping rectangle + window->DrawList->Clear(); + window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); + window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + ImRect viewport_rect(GetViewportRect()); + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) + PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); + else + PushClipRect(viewport_rect.Min, viewport_rect.Max, true); + + // Draw modal window background (darkens what is behind them, all viewports) + const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesForResize <= 0; + const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow); + if (dim_bg_for_modal || dim_bg_for_window_list) + { + const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); + window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col); + } + + // Draw navigation selection/windowing rectangle background + if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim) + { + ImRect bb = window->Rect(); + bb.Expand(g.FontSize); + if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); + } + + // Draw window + handle manual resize + const float window_rounding = window->WindowRounding; + const float window_border_size = window->WindowBorderSize; + const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; + const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); + const ImRect title_bar_rect = window->TitleBarRect(); + if (window->Collapsed) + { + // Title bar only + float backup_border_size = style.FrameBorderSize; + g.Style.FrameBorderSize = window->WindowBorderSize; + ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); + RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); + g.Style.FrameBorderSize = backup_border_size; + } + else + { + // Window background + if (!(flags & ImGuiWindowFlags_NoBackground)) + { + ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); + if (g.NextWindowData.BgAlphaCond != 0) + bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT); + window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); + } + g.NextWindowData.BgAlphaCond = 0; + + // Title bar + ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top); + + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) + { + ImRect menu_bar_rect = window->MenuBarRect(); + menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. + window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); + if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) + window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } + + // Scrollbars + if (window->ScrollbarX) + Scrollbar(ImGuiLayoutType_Horizontal); + if (window->ScrollbarY) + Scrollbar(ImGuiLayoutType_Vertical); + + // Render resize grips (after their input handling so we don't have a frame of latency) + if (!(flags & ImGuiWindowFlags_NoResize)) + { + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size))); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size))); + window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); + window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); + } + } + + // Borders + if (window_border_size > 0.0f && !(flags & ImGuiWindowFlags_NoBackground)) + window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size); + if (border_held != -1) + { + ImRect border = GetResizeBorderRect(window, border_held, grip_draw_size, 0.0f); + window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size)); + } + if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize, -1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } + + // Draw navigation selection/windowing rectangle border + if (g.NavWindowingTargetAnim == window) + { + float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding); + ImRect bb = window->Rect(); + bb.Expand(g.FontSize); + if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward + { + bb.Expand(-g.FontSize - 1.0f); + rounding = window->WindowRounding; + } + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); + } + + // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. + window->SizeFullAtLastBegin = window->SizeFull; + + // Update various regions. Variables they depends on are set above in this function. + // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); + window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); + + // Setup drawing context + // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) + window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; + window->DC.GroupOffset.x = 0.0f; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); + window->DC.CursorPos = window->DC.CursorStartPos; + window->DC.CursorPosPrevLine = window->DC.CursorPos; + window->DC.CursorMaxPos = window->DC.CursorStartPos; + window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.NavHideHighlightOneFrame = false; + window->DC.NavHasScroll = (GetScrollMaxY() > 0.0f); + window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; + window->DC.NavLayerActiveMaskNext = 0x00; + window->DC.MenuBarAppending = false; + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; + window->DC.ChildWindows.resize(0); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; + window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_; + window->DC.ItemWidth = window->ItemWidthDefault; + window->DC.TextWrapPos = -1.0f; // disabled + window->DC.ItemFlagsStack.resize(0); + window->DC.ItemWidthStack.resize(0); + window->DC.TextWrapPosStack.resize(0); + window->DC.ColumnsSet = NULL; + window->DC.TreeDepth = 0; + window->DC.TreeDepthMayJumpToParentOnPop = 0x00; + window->DC.StateStorage = &window->StateStorage; + window->DC.GroupStack.resize(0); + window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); + + if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags)) + { + window->DC.ItemFlags = parent_window->DC.ItemFlags; + window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); + } + + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; + + // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + if (want_focus) + { + FocusWindow(window); + NavInitWindow(window, false); + } + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + { + // Close & collapse button are on layer 1 (same as menus) and don't default focus + const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; + window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; + window->DC.NavLayerCurrent++; + window->DC.NavLayerCurrentMask <<= 1; + + // Collapse button + if (!(flags & ImGuiWindowFlags_NoCollapse)) + if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos)) + window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function + + // Close button + if (p_open != NULL) + { + const float pad = style.FramePadding.y; + const float rad = g.FontSize * 0.5f; + if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad + 1)) + *p_open = false; + } + + window->DC.NavLayerCurrent--; + window->DC.NavLayerCurrentMask >>= 1; + window->DC.ItemFlags = item_flags_backup; + + // Title text (FIXME: refactor text alignment facilities along with RenderText helpers, this is too much code for what it does.) + ImVec2 text_size = CalcTextSize(name, NULL, true); + ImRect text_r = title_bar_rect; + float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); + float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); + if (style.WindowTitleAlign.x > 0.0f) + pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); + text_r.Min.x += pad_left; + text_r.Max.x -= pad_right; + ImRect clip_rect = text_r; + clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton() + RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); + } + + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->OuterRectClipped = window->Rect(); + window->OuterRectClipped.ClipWith(window->ClipRect); + + // Pressing CTRL+C while holding on a window copy its content to the clipboard + // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. + // Maybe we can support CTRL+C on every element? + /* + if (g.ActiveId == move_id) + if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) + LogToClipboard(); + */ + + // Inner rectangle + // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame + // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; + window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize; + window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize; + //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE); + + // Inner clipping rectangle + // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize))); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); + window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize))); + window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); + + // After Begin() we fill the last item / hovered data based on title bar data. It is a standard behavior (to allow creation of context menus on title bar only, etc.). + window->DC.LastItemId = window->MoveId; + window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; + window->DC.LastItemRect = title_bar_rect; + } + + PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); + + // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) + if (first_begin_of_the_frame) + window->WriteAccessed = false; + + window->BeginCount++; + g.NextWindowData.Clear(); + + if (flags & ImGuiWindowFlags_ChildWindow) + { + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); + + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + window->HiddenFramesRegular = 1; + + // Completely hide along with parent or if parent is collapsed + if (parent_window && (parent_window->Collapsed || parent_window->Hidden)) + window->HiddenFramesRegular = 1; + } + + // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) + if (style.Alpha <= 0.0f) + window->HiddenFramesRegular = 1; + + // Update the Hidden flag + window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize); + + // Return false if we don't intend to display anything to allow user to perform an early out optimization + window->SkipItems = (window->Collapsed || !window->Active || window->Hidden) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesForResize <= 0; + + return !window->SkipItems; +} + +// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags) +{ + // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file. + if (size_first_use.x != 0.0f || size_first_use.y != 0.0f) + SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver); + + // Old API feature: override the window background alpha with a parameter. + if (bg_alpha_override >= 0.0f) + SetNextWindowBgAlpha(bg_alpha_override); + + return Begin(name, p_open, flags); +} +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +void ImGui::End() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (window->DC.ColumnsSet != NULL) + EndColumns(); + PopClipRect(); // Inner window clip rectangle + + // Stop logging + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging + LogFinish(); + + // Pop from window stack + g.CurrentWindowStack.pop_back(); + if (window->Flags & ImGuiWindowFlags_Popup) + g.CurrentPopupStack.pop_back(); + CheckStacksSize(window, false); + SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); +} + +void ImGui::BringWindowToFocusFront(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.WindowsFocusOrder.back() == window) + return; + for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window + if (g.WindowsFocusOrder[i] == window) + { + memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*)); + g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window; + break; + } +} + +void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* current_front_window = g.Windows.back(); + if (current_front_window == window || current_front_window->RootWindow == window) + return; + for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window + if (g.Windows[i] == window) + { + memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); + g.Windows[g.Windows.Size - 1] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBack(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.Windows[0] == window) + return; + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i] == window) + { + memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); + g.Windows[0] = window; + break; + } +} + +// Moving window to front of display and set focus (which happens to be back of our sorted list) +void ImGui::FocusWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + if (g.NavWindow != window) + { + g.NavWindow = window; + if (window && g.NavDisableMouseHover) + g.NavMousePosDirty = true; + g.NavInitRequest = false; + g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId + g.NavIdIsAlive = false; + g.NavLayer = 0; + //printf("[%05d] FocusWindow(\"%s\")\n", g.FrameCount, window ? window->Name : NULL); + } + + // Passing NULL allow to disable keyboard focus + if (!window) + return; + + // Move the root window to the top of the pile + if (window->RootWindow) + window = window->RootWindow; + + // Steal focus on active widgets + if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) + ClearActiveID(); + + // Bring to front + BringWindowToFocusFront(window); + if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) + BringWindowToDisplayFront(window); +} + +void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window) +{ + ImGuiContext& g = *GImGui; + for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) + { + // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. + ImGuiWindow* window = g.WindowsFocusOrder[i]; + if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow)) + if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) + { + ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window); + FocusWindow(focus_window); + return; + } + } +} + +void ImGui::PushItemWidth(float item_width) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); +} + +void ImGui::PushMultiItemsWidths(int components, float w_full) +{ + ImGuiWindow* window = GetCurrentWindow(); + const ImGuiStyle& style = GImGui->Style; + if (w_full <= 0.0f) + w_full = CalcItemWidth(); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + window->DC.ItemWidthStack.push_back(w_item_last); + for (int i = 0; i < components-1; i++) + window->DC.ItemWidthStack.push_back(w_item_one); + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); +} + +void ImGui::PopItemWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidthStack.pop_back(); + window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); +} + +float ImGui::CalcItemWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + float w = window->DC.ItemWidth; + if (w < 0.0f) + { + // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. + float width_to_right_edge = GetContentRegionAvail().x; + w = ImMax(1.0f, width_to_right_edge + w); + } + w = (float)(int)w; + return w; +} + +void ImGui::SetCurrentFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(font->Scale > 0.0f); + g.Font = font; + g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; + g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + + ImFontAtlas* atlas = g.Font->ContainerAtlas; + g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; + g.DrawListSharedData.Font = g.Font; + g.DrawListSharedData.FontSize = g.FontSize; +} + +void ImGui::PushFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + if (!font) + font = GetDefaultFont(); + SetCurrentFont(font); + g.FontStack.push_back(font); + g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); +} + +void ImGui::PopFont() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DrawList->PopTextureID(); + g.FontStack.pop_back(); + SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); +} + +void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (enabled) + window->DC.ItemFlags |= option; + else + window->DC.ItemFlags &= ~option; + window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); +} + +void ImGui::PopItemFlag() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemFlagsStack.pop_back(); + window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back(); +} + +// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system. +void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) +{ + PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus); +} + +void ImGui::PopAllowKeyboardFocus() +{ + PopItemFlag(); +} + +void ImGui::PushButtonRepeat(bool repeat) +{ + PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); +} + +void ImGui::PopButtonRepeat() +{ + PopItemFlag(); +} + +void ImGui::PushTextWrapPos(float wrap_pos_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos = wrap_pos_x; + window->DC.TextWrapPosStack.push_back(wrap_pos_x); +} + +void ImGui::PopTextWrapPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPosStack.pop_back(); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); +} + +// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 +void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorModifiers.push_back(backup); + g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); +} + +void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) +{ + ImGuiContext& g = *GImGui; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorModifiers.push_back(backup); + g.Style.Colors[idx] = col; +} + +void ImGui::PopStyleColor(int count) +{ + ImGuiContext& g = *GImGui; + while (count > 0) + { + ImGuiColorMod& backup = g.ColorModifiers.back(); + g.Style.Colors[backup.Col] = backup.BackupValue; + g.ColorModifiers.pop_back(); + count--; + } +} + +struct ImGuiStyleVarInfo +{ + ImGuiDataType Type; + ImU32 Count; + ImU32 Offset; + void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); } +}; + +static const ImGuiStyleVarInfo GStyleVarInfo[] = +{ + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign +}; + +static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) +{ + IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); + IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT); + return &GStyleVarInfo[idx]; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) +{ + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) + { + ImGuiContext& g = *GImGui; + float* pvar = (float*)var_info->GetVarPtr(&g.Style); + g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) +{ + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) + { + ImGuiContext& g = *GImGui; + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. +} + +void ImGui::PopStyleVar(int count) +{ + ImGuiContext& g = *GImGui; + while (count > 0) + { + // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. + ImGuiStyleMod& backup = g.StyleModifiers.back(); + const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); + void* data = info->GetVarPtr(&g.Style); + if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } + else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } + g.StyleModifiers.pop_back(); + count--; + } +} + +const char* ImGui::GetStyleColorName(ImGuiCol idx) +{ + // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; + switch (idx) + { + case ImGuiCol_Text: return "Text"; + case ImGuiCol_TextDisabled: return "TextDisabled"; + case ImGuiCol_WindowBg: return "WindowBg"; + case ImGuiCol_ChildBg: return "ChildBg"; + case ImGuiCol_PopupBg: return "PopupBg"; + case ImGuiCol_Border: return "Border"; + case ImGuiCol_BorderShadow: return "BorderShadow"; + case ImGuiCol_FrameBg: return "FrameBg"; + case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; + case ImGuiCol_FrameBgActive: return "FrameBgActive"; + case ImGuiCol_TitleBg: return "TitleBg"; + case ImGuiCol_TitleBgActive: return "TitleBgActive"; + case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_MenuBarBg: return "MenuBarBg"; + case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; + case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; + case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; + case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; + case ImGuiCol_CheckMark: return "CheckMark"; + case ImGuiCol_SliderGrab: return "SliderGrab"; + case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; + case ImGuiCol_Button: return "Button"; + case ImGuiCol_ButtonHovered: return "ButtonHovered"; + case ImGuiCol_ButtonActive: return "ButtonActive"; + case ImGuiCol_Header: return "Header"; + case ImGuiCol_HeaderHovered: return "HeaderHovered"; + case ImGuiCol_HeaderActive: return "HeaderActive"; + case ImGuiCol_Separator: return "Separator"; + case ImGuiCol_SeparatorHovered: return "SeparatorHovered"; + case ImGuiCol_SeparatorActive: return "SeparatorActive"; + case ImGuiCol_ResizeGrip: return "ResizeGrip"; + case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; + case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_PlotLines: return "PlotLines"; + case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: return "PlotHistogram"; + case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; + case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_DragDropTarget: return "DragDropTarget"; + case ImGuiCol_NavHighlight: return "NavHighlight"; + case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; + case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; + case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg"; + } + IM_ASSERT(0); + return "Unknown"; +} + +bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) +{ + if (window->RootWindow == potential_parent) + return true; + while (window != NULL) + { + if (window == potential_parent) + return true; + window = window->ParentWindow; + } + return false; +} + +bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) +{ + IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function + ImGuiContext& g = *GImGui; + + if (flags & ImGuiHoveredFlags_AnyWindow) + { + if (g.HoveredWindow == NULL) + return false; + } + else + { + switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) + { + case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows: + if (g.HoveredRootWindow != g.CurrentWindow->RootWindow) + return false; + break; + case ImGuiHoveredFlags_RootWindow: + if (g.HoveredWindow != g.CurrentWindow->RootWindow) + return false; + break; + case ImGuiHoveredFlags_ChildWindows: + if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow)) + return false; + break; + default: + if (g.HoveredWindow != g.CurrentWindow) + return false; + break; + } + } + + if (!IsWindowContentHoverable(g.HoveredRootWindow, flags)) + return false; + if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId) + return false; + return true; +} + +bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) +{ + ImGuiContext& g = *GImGui; + + if (flags & ImGuiFocusedFlags_AnyWindow) + return g.NavWindow != NULL; + + IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End() + switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows)) + { + case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows: + return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow; + case ImGuiFocusedFlags_RootWindow: + return g.NavWindow == g.CurrentWindow->RootWindow; + case ImGuiFocusedFlags_ChildWindows: + return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow); + default: + return g.NavWindow == g.CurrentWindow; + } +} + +// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) +// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly. +// If you want a window to never be focused, you may use the e.g. NoInputs flag. +bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) +{ + return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); +} + +float ImGui::GetWindowWidth() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.x; +} + +float ImGui::GetWindowHeight() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.y; +} + +ImVec2 ImGui::GetWindowPos() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return window->Pos; +} + +void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x) +{ + window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. + window->Scroll.x = new_scroll_x; + window->DC.CursorMaxPos.x -= window->Scroll.x; +} + +void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. + window->Scroll.y = new_scroll_y; + window->DC.CursorMaxPos.y -= window->Scroll.y; +} + +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowPosAllowFlags & cond) == 0) + return; + + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX); + + // Set + const ImVec2 old_pos = window->Pos; + window->Pos = ImFloor(pos); + window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. +} + +void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + SetWindowPos(window, pos, cond); +} + +void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowPos(window, pos, cond); +} + +ImVec2 ImGui::GetWindowSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Size; +} + +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) + return; + + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + // Set + if (size.x > 0.0f) + { + window->AutoFitFramesX = 0; + window->SizeFull.x = ImFloor(size.x); + } + else + { + window->AutoFitFramesX = 2; + window->AutoFitOnlyGrows = false; + } + if (size.y > 0.0f) + { + window->AutoFitFramesY = 0; + window->SizeFull.y = ImFloor(size.y); + } + else + { + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } +} + +void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond) +{ + SetWindowSize(GImGui->CurrentWindow, size, cond); +} + +void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowSize(window, size, cond); +} + +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) + return; + window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + // Set + window->Collapsed = collapsed; +} + +void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) +{ + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); +} + +bool ImGui::IsWindowCollapsed() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Collapsed; +} + +bool ImGui::IsWindowAppearing() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Appearing; +} + +void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowCollapsed(window, collapsed, cond); +} + +void ImGui::SetWindowFocus() +{ + FocusWindow(GImGui->CurrentWindow); +} + +void ImGui::SetWindowFocus(const char* name) +{ + if (name) + { + if (ImGuiWindow* window = FindWindowByName(name)) + FocusWindow(window); + } + else + { + FocusWindow(NULL); + } +} + +void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.PosVal = pos; + g.NextWindowData.PosPivotVal = pivot; + g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; +} + +void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.SizeVal = size; + g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; +} + +void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.SizeConstraintCond = ImGuiCond_Always; + g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); + g.NextWindowData.SizeCallback = custom_callback; + g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; +} + +void ImGui::SetNextWindowContentSize(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value. + g.NextWindowData.ContentSizeCond = ImGuiCond_Always; +} + +void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.CollapsedVal = collapsed; + g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; +} + +void ImGui::SetNextWindowFocus() +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) +} + +void ImGui::SetNextWindowBgAlpha(float alpha) +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.BgAlphaVal = alpha; + g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) +} + +// In window space (not screen space!) +ImVec2 ImGui::GetContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImVec2 mx = window->ContentsRegionRect.Max - window->Pos; + if (window->DC.ColumnsSet) + mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x; + return mx; +} + +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); +} + +float ImGui::GetContentRegionAvailWidth() +{ + return GetContentRegionAvail().x; +} + +// In window space (not screen space!) +ImVec2 ImGui::GetWindowContentRegionMin() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Min - window->Pos; +} + +ImVec2 ImGui::GetWindowContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max - window->Pos; +} + +float ImGui::GetWindowContentRegionWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.GetWidth(); +} + +float ImGui::GetTextLineHeight() +{ + ImGuiContext& g = *GImGui; + return g.FontSize; +} + +float ImGui::GetTextLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.ItemSpacing.y; +} + +float ImGui::GetFrameHeight() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f; +} + +float ImGui::GetFrameHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + +ImDrawList* ImGui::GetWindowDrawList() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DrawList; +} + +ImFont* ImGui::GetFont() +{ + return GImGui->Font; +} + +float ImGui::GetFontSize() +{ + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->DrawListSharedData.TexUvWhitePixel; +} + +void ImGui::SetWindowFontScale(float scale) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->FontWindowScale = scale; + g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); +} + +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. +ImVec2 ImGui::GetCursorPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; +} + +float ImGui::GetCursorPosX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; +} + +float ImGui::GetCursorPosY() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; +} + +void ImGui::SetCursorPos(const ImVec2& local_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +void ImGui::SetCursorPosX(float x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); +} + +void ImGui::SetCursorPosY(float y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); +} + +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + +ImVec2 ImGui::GetCursorScreenPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos; +} + +void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = screen_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +float ImGui::GetScrollX() +{ + return GImGui->CurrentWindow->Scroll.x; +} + +float ImGui::GetScrollY() +{ + return GImGui->CurrentWindow->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + return GetWindowScrollMaxX(GImGui->CurrentWindow); +} + +float ImGui::GetScrollMaxY() +{ + return GetWindowScrollMaxY(GImGui->CurrentWindow); +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); + window->ScrollTargetCenterRatio.y = center_y_ratio; +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHereY(float center_y_ratio) +{ + ImGuiWindow* window = GetCurrentWindow(); + float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space + target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + SetScrollFromPosY(target_y, center_y_ratio); +} + +void ImGui::ActivateItem(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.NavNextActivateId = id; +} + +void ImGui::SetKeyboardFocusHere(int offset) +{ + IM_ASSERT(offset >= -1); // -1 is allowed but not below + ImGuiWindow* window = GetCurrentWindow(); + window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; + window->FocusIdxTabRequestNext = INT_MAX; +} + +void ImGui::SetItemDefaultFocus() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (!window->Appearing) + return; + if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent) + { + g.NavInitRequest = false; + g.NavInitResultId = g.NavWindow->DC.LastItemId; + g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos); + NavUpdateAnyRequestFlag(); + if (!IsItemVisible()) + SetScrollHereY(); + } +} + +void ImGui::SetStateStorage(ImGuiStorage* tree) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.StateStorage = tree ? tree : &window->StateStorage; +} + +ImGuiStorage* ImGui::GetStateStorage() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.StateStorage; +} + +void ImGui::PushID(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + window->IDStack.push_back(window->GetIDNoKeepAlive(str_id)); +} + +void ImGui::PushID(const char* str_id_begin, const char* str_id_end) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end)); +} + +void ImGui::PushID(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); +} + +void ImGui::PushID(int int_id) +{ + const void* ptr_id = (void*)(intptr_t)int_id; + ImGuiWindow* window = GetCurrentWindowRead(); + window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); +} + +void ImGui::PopID() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + window->IDStack.pop_back(); +} + +ImGuiID ImGui::GetID(const char* str_id) +{ + return GImGui->CurrentWindow->GetID(str_id); +} + +ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) +{ + return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); +} + +ImGuiID ImGui::GetID(const void* ptr_id) +{ + return GImGui->CurrentWindow->GetID(ptr_id); +} + +bool ImGui::IsRectVisible(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); +} + +bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); +} + +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +void ImGui::BeginGroup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); + ImGuiGroupData& group_data = window->DC.GroupStack.back(); + group_data.BackupCursorPos = window->DC.CursorPos; + group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; + group_data.BackupIndent = window->DC.Indent; + group_data.BackupGroupOffset = window->DC.GroupOffset; + group_data.BackupCurrentLineSize = window->DC.CurrentLineSize; + group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; + group_data.BackupLogLinePosY = window->DC.LogLinePosY; + group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; + group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; + group_data.AdvanceCursor = true; + + window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; + window->DC.Indent = window->DC.GroupOffset; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return +} + +void ImGui::EndGroup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls + + ImGuiGroupData& group_data = window->DC.GroupStack.back(); + + ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); + group_bb.Max = ImMax(group_bb.Min, group_bb.Max); + + window->DC.CursorPos = group_data.BackupCursorPos; + window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); + window->DC.Indent = group_data.BackupIndent; + window->DC.GroupOffset = group_data.BackupGroupOffset; + window->DC.CurrentLineSize = group_data.BackupCurrentLineSize; + window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return + + if (group_data.AdvanceCursor) + { + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); + ItemAdd(group_bb, 0); + } + + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. + // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. + // (and if you grep for LastItemId you'll notice it is only used in that context. + if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow) + window->DC.LastItemId = g.ActiveId; + else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow) + window->DC.LastItemId = g.ActiveIdPreviousFrame; + window->DC.LastItemRect = group_bb; + + window->DC.GroupStack.pop_back(); + + //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] +} + +// Gets back to previous line and continue with horizontal layout +// pos_x == 0 : follow right after previous item +// pos_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float pos_x, float spacing_w) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + if (pos_x != 0.0f) + { + if (spacing_w < 0.0f) spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + else + { + if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + window->DC.CurrentLineSize = window->DC.PrevLineSize; + window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; +} + +void ImGui::Indent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; +} + +void ImGui::Unindent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; +} + +//----------------------------------------------------------------------------- +// [SECTION] TOOLTIPS +//----------------------------------------------------------------------------- + +void ImGui::BeginTooltip() +{ + ImGuiContext& g = *GImGui; + if (g.DragDropWithinSourceOrTarget) + { + // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor) + // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor. + // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do. + //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; + ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale); + SetNextWindowPos(tooltip_pos); + SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); + //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :( + BeginTooltipEx(0, true); + } + else + { + BeginTooltipEx(0, false); + } +} + +// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first. +void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip) +{ + ImGuiContext& g = *GImGui; + char window_name[16]; + ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount); + if (override_previous_tooltip) + if (ImGuiWindow* window = FindWindowByName(window_name)) + if (window->Active) + { + // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. + window->Hidden = true; + window->HiddenFramesRegular = 1; + ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); + } + ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + Begin(window_name, NULL, flags | extra_flags); +} + +void ImGui::EndTooltip() +{ + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls + End(); +} + +void ImGui::SetTooltipV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + if (g.DragDropWithinSourceOrTarget) + BeginTooltip(); + else + BeginTooltipEx(0, true); + TextV(fmt, args); + EndTooltip(); +} + +void ImGui::SetTooltip(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + SetTooltipV(fmt, args); + va_end(args); +} + +//----------------------------------------------------------------------------- +// [SECTION] POPUPS +//----------------------------------------------------------------------------- + +bool ImGui::IsPopupOpen(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; +} + +bool ImGui::IsPopupOpen(const char* str_id) +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); +} + +ImGuiWindow* ImGui::GetFrontMostPopupModal() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) + if (popup->Flags & ImGuiWindowFlags_Modal) + return popup; + return NULL; +} + +void ImGui::OpenPopup(const char* str_id) +{ + ImGuiContext& g = *GImGui; + OpenPopupEx(g.CurrentWindow->GetID(str_id)); +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* parent_window = g.CurrentWindow; + int current_stack_size = g.CurrentPopupStack.Size; + ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. + popup_ref.PopupId = id; + popup_ref.Window = NULL; + popup_ref.ParentWindow = parent_window; + popup_ref.OpenFrameCount = g.FrameCount; + popup_ref.OpenParentId = parent_window->IDStack.back(); + popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); + popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; + + //printf("[%05d] OpenPopupEx(0x%08X)\n", g.FrameCount, id); + if (g.OpenPopupStack.Size < current_stack_size + 1) + { + g.OpenPopupStack.push_back(popup_ref); + } + else + { + // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui + // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing + // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand. + if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) + { + g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount; + } + else + { + // Close child popups if any, then flag popup for open/reopen + g.OpenPopupStack.resize(current_stack_size + 1); + g.OpenPopupStack[current_stack_size] = popup_ref; + } + + // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). + // This is equivalent to what ClosePopupToLevel() does. + //if (g.OpenPopupStack[current_stack_size].PopupId == id) + // FocusWindow(parent_window); + } +} + +bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + { + ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + OpenPopupEx(id); + return true; + } + return false; +} + +void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window) +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.empty()) + return; + + // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. + // Don't close our own child popup windows. + int n = 0; + if (ref_window) + { + for (n = 0; n < g.OpenPopupStack.Size; n++) + { + ImGuiPopupRef& popup = g.OpenPopupStack[n]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + + // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow) + bool has_focus = false; + for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) + has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow); + if (!has_focus) + break; + } + } + if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below + ClosePopupToLevel(n); +} + +void ImGui::ClosePopupToLevel(int remaining) +{ + IM_ASSERT(remaining >= 0); + ImGuiContext& g = *GImGui; + ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow; + if (g.NavLayer == 0) + focus_window = NavRestoreLastChildNavWindow(focus_window); + FocusWindow(focus_window); + focus_window->DC.NavHideHighlightOneFrame = true; + g.OpenPopupStack.resize(remaining); +} + +void ImGui::ClosePopup(ImGuiID id) +{ + if (!IsPopupOpen(id)) + return; + ImGuiContext& g = *GImGui; + ClosePopupToLevel(g.OpenPopupStack.Size - 1); +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext& g = *GImGui; + int popup_idx = g.CurrentPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) + return; + while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) + popup_idx--; + ClosePopupToLevel(popup_idx); +} + +bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + if (!IsPopupOpen(id)) + { + g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values + return false; + } + + char name[20]; + if (extra_flags & ImGuiWindowFlags_ChildMenu) + ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth + else + ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame + + bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); + if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) + EndPopup(); + + return is_open; +} + +bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance + { + g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values + return false; + } + return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id)) + { + g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values + return false; + } + + // Center modal windows by default + // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. + if (g.NextWindowData.PosCond == 0) + SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + EndPopup(); + if (is_open) + ClosePopup(id); + return false; + } + return is_open; +} + +void ImGui::EndPopup() +{ + ImGuiContext& g = *GImGui; (void)g; + IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls + IM_ASSERT(g.CurrentPopupStack.Size > 0); + + // Make all menus and popups wrap around for now, may need to expose that policy. + NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY); + + End(); +} + +// This is a helper to handle the simplest case of associating one named popup to one given widget. +// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +// You can pass a NULL str_id to use the identifier of the last item. +bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + OpenPopupEx(id); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items) +{ + if (!str_id) + str_id = "window_context"; + ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + if (also_over_items || !IsAnyItemHovered()) + OpenPopupEx(id); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) +{ + if (!str_id) + str_id = "void_context"; + ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) + OpenPopupEx(id); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); +} + +ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow*) +{ + ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding; + ImRect r_screen = GetViewportRect(); + r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f)); + return r_screen; +} + +// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) +// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. +ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy) +{ + ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); + //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); + //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); + + // Combo Box policy (we want a connecting edge) + if (policy == ImGuiPopupPositionPolicy_ComboBox) + { + const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; + ImVec2 pos; + if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default) + if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right + if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left + if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left + if (!r_outer.Contains(ImRect(pos, pos + size))) + continue; + *last_dir = dir; + return pos; + } + } + + // Default popup policy + const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; + float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); + float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); + if (avail_w < size.x || avail_h < size.y) + continue; + ImVec2 pos; + pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; + pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; + *last_dir = dir; + return pos; + } + + // Fallback, try to keep within display + *last_dir = ImGuiDir_None; + ImVec2 pos = ref_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; +} + +ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + ImRect r_outer = GetWindowAllowedExtentRect(window); + if (window->Flags & ImGuiWindowFlags_ChildMenu) + { + // Child menus typically request _any_ position within the parent menu item, and then our FindBestWindowPosForPopup() function will move the new menu outside the parent bounds. + // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. + IM_ASSERT(g.CurrentWindow == window); + ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2]; + float horizontal_overlap = g.Style.ItemSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). + ImRect r_avoid; + if (parent_window->DC.MenuBarAppending) + r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); + else + r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); + } + if (window->Flags & ImGuiWindowFlags_Popup) + { + ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1); + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); + } + if (window->Flags & ImGuiWindowFlags_Tooltip) + { + // Position tooltip (always follows mouse) + float sc = g.Style.MouseCursorScale; + ImVec2 ref_pos = NavCalcPreferredRefPos(); + ImRect r_avoid; + if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)) + r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); + else + r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. + ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); + if (window->AutoPosLastDirection == ImGuiDir_None) + pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. + return pos; + } + IM_ASSERT(0); + return window->Pos; +} + +//----------------------------------------------------------------------------- +// [SECTION] KEYBOARD/GAMEPAD NAVIGATION +//----------------------------------------------------------------------------- + +ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy) +{ + if (ImFabs(dx) > ImFabs(dy)) + return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left; + return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up; +} + +static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1) +{ + if (a1 < b0) + return a1 - b0; + if (b1 < a0) + return a0 - b1; + return 0.0f; +} + +static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect) +{ + if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) + { + r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y); + r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y); + } + else + { + r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x); + r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x); + } +} + +// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057 +static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.NavLayer != window->DC.NavLayerCurrent) + return false; + + const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) + g.NavScoringCount++; + + // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring + if (window->ParentWindow == g.NavWindow) + { + IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened); + if (!window->ClipRect.Contains(cand)) + return false; + cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window + } + + // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items) + // For example, this ensure that items in one column are not reached when moving vertically from items in another column. + NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect); + + // Compute distance between boxes + // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. + float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); + float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items + if (dby != 0.0f && dbx != 0.0f) + dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); + float dist_box = ImFabs(dbx) + ImFabs(dby); + + // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) + float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); + float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); + float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee) + + // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance + ImGuiDir quadrant; + float dax = 0.0f, day = 0.0f, dist_axial = 0.0f; + if (dbx != 0.0f || dby != 0.0f) + { + // For non-overlapping boxes, use distance between boxes + dax = dbx; + day = dby; + dist_axial = dist_box; + quadrant = ImGetDirQuadrantFromDelta(dbx, dby); + } + else if (dcx != 0.0f || dcy != 0.0f) + { + // For overlapping boxes with different centers, use distance between centers + dax = dcx; + day = dcy; + dist_axial = dist_center; + quadrant = ImGetDirQuadrantFromDelta(dcx, dcy); + } + else + { + // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) + quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right; + } + +#if IMGUI_DEBUG_NAV_SCORING + char buf[128]; + if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max)) + { + ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]); + ImDrawList* draw_list = GetOverlayDrawList(window); + draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100)); + draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200)); + draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150)); + draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf); + } + else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. + { + if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; } + if (quadrant == g.NavMoveDir) + { + ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); + ImDrawList* draw_list = GetOverlayDrawList(window); + draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200)); + draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); + } + } + #endif + + // Is it in the quadrant we're interesting in moving to? + bool new_best = false; + if (quadrant == g.NavMoveDir) + { + // Does it beat the current best candidate? + if (dist_box < result->DistBox) + { + result->DistBox = dist_box; + result->DistCenter = dist_center; + return true; + } + if (dist_box == result->DistBox) + { + // Try using distance between center points to break ties + if (dist_center < result->DistCenter) + { + result->DistCenter = dist_center; + new_best = true; + } + else if (dist_center == result->DistCenter) + { + // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items + // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), + // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. + if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance + new_best = true; + } + } + } + + // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches + // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) + // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. + // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. + // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? + if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match + if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) + if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f)) + { + result->DistAxial = dist_axial; + new_best = true; + } + + return new_best; +} + +// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) +static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id) +{ + ImGuiContext& g = *GImGui; + //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag. + // return; + + const ImGuiItemFlags item_flags = window->DC.ItemFlags; + const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos); + + // Process Init Request + if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent) + { + // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback + if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0) + { + g.NavInitResultId = id; + g.NavInitResultRectRel = nav_bb_rel; + } + if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus)) + { + g.NavInitRequest = false; // Found a match, clear request + NavUpdateAnyRequestFlag(); + } + } + + // Process Move Request (scoring for navigation) + // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy) + if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_NoNav)) + { + ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; +#if IMGUI_DEBUG_NAV_SCORING + // [DEBUG] Score all items in NavWindow at all times + if (!g.NavMoveRequest) + g.NavMoveDir = g.NavMoveDirLast; + bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest; +#else + bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); +#endif + if (new_best) + { + result->ID = id; + result->Window = window; + result->RectRel = nav_bb_rel; + } + + const float VISIBLE_RATIO = 0.70f; + if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) + if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) + if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb)) + { + result = &g.NavMoveResultLocalVisibleSet; + result->ID = id; + result->Window = window; + result->RectRel = nav_bb_rel; + } + } + + // Update window-relative bounding box of navigated item + if (g.NavId == id) + { + g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window. + g.NavLayer = window->DC.NavLayerCurrent; + g.NavIdIsAlive = true; + g.NavIdTabCounter = window->FocusIdxTabCounter; + window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position) + } +} + +bool ImGui::NavMoveRequestButNoResultYet() +{ + ImGuiContext& g = *GImGui; + return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; +} + +void ImGui::NavMoveRequestCancel() +{ + ImGuiContext& g = *GImGui; + g.NavMoveRequest = false; + NavUpdateAnyRequestFlag(); +} + +void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None); + ImGui::NavMoveRequestCancel(); + g.NavMoveDir = move_dir; + g.NavMoveClipDir = clip_dir; + g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; + g.NavMoveRequestFlags = move_flags; + g.NavWindow->NavRectRel[g.NavLayer] = bb_rel; +} + +void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags) +{ + ImGuiContext& g = *GImGui; + if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0) + return; + IM_ASSERT(move_flags != 0); // No points calling this with no wrapping + ImRect bb_rel = window->NavRectRel[0]; + + ImGuiDir clip_dir = g.NavMoveDir; + if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } +} + +static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window) +{ + ImGuiWindow* parent_window = nav_window; + while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + parent_window = parent_window->ParentWindow; + if (parent_window && parent_window != nav_window) + parent_window->NavLastChildNavWindow = nav_window; +} + +// Call when we are expected to land on Layer 0 after FocusWindow() +static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) +{ + return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window; +} + +static void NavRestoreLayer(int layer) +{ + ImGuiContext& g = *GImGui; + g.NavLayer = layer; + if (layer == 0) + g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow); + if (layer == 0 && g.NavWindow->NavLastIds[0] != 0) + ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]); + else + ImGui::NavInitWindow(g.NavWindow, true); +} + +static inline void ImGui::NavUpdateAnyRequestFlag() +{ + ImGuiContext& g = *GImGui; + g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL); + if (g.NavAnyRequest) + IM_ASSERT(g.NavWindow != NULL); +} + +// This needs to be called before we submit any widget (aka in or before Begin) +void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(window == g.NavWindow); + bool init_for_nav = false; + if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) + if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) + init_for_nav = true; + if (init_for_nav) + { + SetNavID(0, g.NavLayer); + g.NavInitRequest = true; + g.NavInitRequestFromMove = false; + g.NavInitResultId = 0; + g.NavInitResultRectRel = ImRect(); + NavUpdateAnyRequestFlag(); + } + else + { + g.NavId = window->NavLastIds[0]; + } +} + +static ImVec2 ImGui::NavCalcPreferredRefPos() +{ + ImGuiContext& g = *GImGui; + if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow) + { + // Mouse (we need a fallback in case the mouse becomes invalid after being used) + if (IsMousePosValid(&g.IO.MousePos)) + return g.IO.MousePos; + return g.LastValidMousePos; + } + else + { + // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item. + const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer]; + ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); + ImRect visible_rect = GetViewportRect(); + return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta. + } +} + +float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode) +{ + ImGuiContext& g = *GImGui; + if (mode == ImGuiInputReadMode_Down) + return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user) + + const float t = g.IO.NavInputsDownDuration[n]; + if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input. + return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f); + if (t < 0.0f) + return 0.0f; + if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input. + return (t == 0.0f) ? 1.0f : 0.0f; + if (mode == ImGuiInputReadMode_Repeat) + return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f); + if (mode == ImGuiInputReadMode_RepeatSlow) + return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f); + if (mode == ImGuiInputReadMode_RepeatFast) + return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f); + return 0.0f; +} + +ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor) +{ + ImVec2 delta(0.0f, 0.0f); + if (dir_sources & ImGuiNavDirSourceFlags_Keyboard) + delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode)); + if (dir_sources & ImGuiNavDirSourceFlags_PadDPad) + delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode)); + if (dir_sources & ImGuiNavDirSourceFlags_PadLStick) + delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode)); + if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow)) + delta *= slow_factor; + if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast)) + delta *= fast_factor; + return delta; +} + +// Scroll to keep newly navigated item fully into view +// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. +static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) +{ + ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1)); + //g.OverlayDrawList.AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] + if (window_rect.Contains(item_rect)) + return; + + ImGuiContext& g = *GImGui; + if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) + { + window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x; + window->ScrollTargetCenterRatio.x = 0.0f; + } + else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) + { + window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x; + window->ScrollTargetCenterRatio.x = 1.0f; + } + if (item_rect.Min.y < window_rect.Min.y) + { + window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y; + window->ScrollTargetCenterRatio.y = 0.0f; + } + else if (item_rect.Max.y >= window_rect.Max.y) + { + window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y; + window->ScrollTargetCenterRatio.y = 1.0f; + } +} + +static void ImGui::NavUpdate() +{ + ImGuiContext& g = *GImGui; + g.IO.WantSetMousePos = false; +#if 0 + if (g.NavScoringCount > 0) printf("[%05d] NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); +#endif + + // Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard) + bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + if (nav_gamepad_active) + if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f) + g.NavInputSource = ImGuiInputSource_NavGamepad; + + // Update Keyboard->Nav inputs mapping + if (nav_keyboard_active) + { + #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } + NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate ); + NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input ); + NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel ); + NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ ); + NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); + NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); + NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); + if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; + if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; + if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; + #undef NAV_MAP_KEY + } + memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++) + g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f; + + // Process navigation init request (select first/default focus) + if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) + { + // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + IM_ASSERT(g.NavWindow); + if (g.NavInitRequestFromMove) + SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel); + else + SetNavID(g.NavInitResultId, g.NavLayer); + g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; + } + g.NavInitRequest = false; + g.NavInitRequestFromMove = false; + g.NavInitResultId = 0; + g.NavJustMovedToId = 0; + + // Process navigation move request + if (g.NavMoveRequest) + NavUpdateMoveResult(); + + // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame + if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive) + { + IM_ASSERT(g.NavMoveRequest); + if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) + g.NavDisableHighlight = false; + g.NavMoveRequestForward = ImGuiNavForward_None; + } + + // Apply application mouse position movement, after we had a chance to process move request result. + if (g.NavMousePosDirty && g.NavIdIsAlive) + { + // Set mouse position given our knowledge of the navigated item position from last frame + if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) + { + if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow) + { + g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos(); + g.IO.WantSetMousePos = true; + } + } + g.NavMousePosDirty = false; + } + g.NavIdIsAlive = false; + g.NavJustTabbedId = 0; + IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1); + + // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0 + if (g.NavWindow) + NavSaveLastChildNavWindow(g.NavWindow); + if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0) + g.NavWindow->NavLastChildNavWindow = NULL; + + // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.) + NavUpdateWindowing(); + + // Set output flags for user application + g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); + g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest; + + // Process NavCancel input (to close a popup, get back to parent, clear focus) + if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) + { + if (g.ActiveId != 0) + { + ClearActiveID(); + } + else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow) + { + // Exit child window + ImGuiWindow* child_window = g.NavWindow; + ImGuiWindow* parent_window = g.NavWindow->ParentWindow; + IM_ASSERT(child_window->ChildId != 0); + FocusWindow(parent_window); + SetNavID(child_window->ChildId, 0); + g.NavIdIsAlive = false; + if (g.NavDisableMouseHover) + g.NavMousePosDirty = true; + } + else if (g.OpenPopupStack.Size > 0) + { + // Close open popup/menu + if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) + ClosePopupToLevel(g.OpenPopupStack.Size - 1); + } + else if (g.NavLayer != 0) + { + // Leave the "menu" layer + NavRestoreLayer(0); + } + else + { + // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were + if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow))) + g.NavWindow->NavLastIds[0] = 0; + g.NavId = 0; + } + } + + // Process manual activation request + g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0; + if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + { + bool activate_down = IsNavInputDown(ImGuiNavInput_Activate); + bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); + if (g.ActiveId == 0 && activate_pressed) + g.NavActivateId = g.NavId; + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) + g.NavActivateDownId = g.NavId; + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed) + g.NavActivatePressedId = g.NavId; + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed)) + g.NavInputId = g.NavId; + } + if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + g.NavDisableHighlight = true; + if (g.NavActivateId != 0) + IM_ASSERT(g.NavActivateDownId == g.NavActivateId); + g.NavMoveRequest = false; + + // Process programmatic activation request + if (g.NavNextActivateId != 0) + g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId; + g.NavNextActivateId = 0; + + // Initiate directional inputs request + const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags; + if (g.NavMoveRequestForward == ImGuiNavForward_None) + { + g.NavMoveDir = ImGuiDir_None; + g.NavMoveRequestFlags = 0; + if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + { + if ((allowed_dir_flags & (1<Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget) + { + // *Fallback* manual-scroll with Nav directional keys when window has no navigable item + ImGuiWindow* window = g.NavWindow; + const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. + if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest) + { + if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) + SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); + if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) + SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); + } + + // *Normal* Manual scroll with NavScrollXXX keys + // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. + ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); + if (scroll_dir.x != 0.0f && window->ScrollbarX) + { + SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); + g.NavMoveFromClampedRefRect = true; + } + if (scroll_dir.y != 0.0f) + { + SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); + g.NavMoveFromClampedRefRect = true; + } + } + + // Reset search results + g.NavMoveResultLocal.Clear(); + g.NavMoveResultLocalVisibleSet.Clear(); + g.NavMoveResultOther.Clear(); + + // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items + if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0) + { + ImGuiWindow* window = g.NavWindow; + ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1)); + if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) + { + float pad = window->CalcFontSize() * 0.5f; + window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item + window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); + g.NavId = 0; + } + g.NavMoveFromClampedRefRect = false; + } + + // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) + ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); + g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); + g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y); + g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x); + g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x; + IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem(). + //g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG] + g.NavScoringCount = 0; +#if IMGUI_DEBUG_NAV_RECTS + if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) GetOverlayDrawList(g.NavWindow)->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] + if (g.NavWindow) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); GetOverlayDrawList(g.NavWindow)->AddCircleFilled(p, 3.0f, col); GetOverlayDrawList(g.NavWindow)->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } +#endif +} + +// Apply result from previous frame navigation directional move request +static void ImGui::NavUpdateMoveResult() +{ + ImGuiContext& g = *GImGui; + if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) + { + // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) + if (g.NavId != 0) + { + g.NavDisableHighlight = false; + g.NavDisableMouseHover = true; + } + return; + } + + // Select which result to use + ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; + + // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. + if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) + if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId) + result = &g.NavMoveResultLocalVisibleSet; + + // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. + if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) + if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter)) + result = &g.NavMoveResultOther; + IM_ASSERT(g.NavWindow && result->Window); + + // Scroll to keep newly navigated item fully into view. + if (g.NavLayer == 0) + { + ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); + NavScrollToBringItemIntoView(result->Window, rect_abs); + + // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate() + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false); + ImVec2 delta_scroll = result->Window->Scroll - next_scroll; + result->RectRel.Translate(delta_scroll); + + // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy). + if (result->Window->Flags & ImGuiWindowFlags_ChildWindow) + NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); + } + + ClearActiveID(); + g.NavWindow = result->Window; + SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel); + g.NavJustMovedToId = result->ID; + g.NavMoveFromClampedRefRect = false; +} + +static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) +{ + ImGuiContext& g = *GImGui; + if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0) + { + ImGuiWindow* window = g.NavWindow; + bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up)); + bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down)); + if ((page_up_held && !page_down_held) || (page_down_held && !page_up_held)) + { + if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll) + { + // Fallback manual-scroll when window has no navigable item + if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) + SetWindowScrollY(window, window->Scroll.y - window->InnerClipRect.GetHeight()); + else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) + SetWindowScrollY(window, window->Scroll.y + window->InnerClipRect.GetHeight()); + } + else + { + const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; + const float page_offset_y = ImMax(0.0f, window->InnerClipRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + float nav_scoring_rect_offset_y = 0.0f; + if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) + { + nav_scoring_rect_offset_y = -page_offset_y; + g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Up; + g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; + } + else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) + { + nav_scoring_rect_offset_y = +page_offset_y; + g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Down; + g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; + } + return nav_scoring_rect_offset_y; + } + } + } + return 0.0f; +} + +static int FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) +{ + ImGuiContext& g = *GImGui; + for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--) + if (g.WindowsFocusOrder[i] == window) + return i; + return -1; +} + +static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) +{ + ImGuiContext& g = *GImGui; + for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir) + if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i])) + return g.WindowsFocusOrder[i]; + return NULL; +} + +static void NavUpdateWindowingHighlightWindow(int focus_change_dir) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindowingTarget); + if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) + return; + + const int i_current = FindWindowFocusIndex(g.NavWindowingTarget); + ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); + if (!window_target) + window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir); + if (window_target) // Don't reset windowing target if there's a single window in the list + g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target; + g.NavWindowingToggleLayer = false; +} + +// Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer) +static void ImGui::NavUpdateWindowing() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* apply_focus_window = NULL; + bool apply_toggle_layer = false; + + ImGuiWindow* modal_window = GetFrontMostPopupModal(); + if (modal_window != NULL) + { + g.NavWindowingTarget = NULL; + return; + } + + // Fade out + if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL) + { + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f); + if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) + g.NavWindowingTargetAnim = NULL; + } + + // Start CTRL-TAB or Square+L/R window selection + bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); + bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); + if (start_windowing_with_gamepad || start_windowing_with_keyboard) + if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) + { + g.NavWindowingTarget = g.NavWindowingTargetAnim = window; + g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; + g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true; + g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad; + } + + // Gamepad update + g.NavWindowingTimer += g.IO.DeltaTime; + if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad) + { + // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); + + // Select window to focus + const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow); + if (focus_change_dir != 0) + { + NavUpdateWindowingHighlightWindow(focus_change_dir); + g.NavWindowingHighlightAlpha = 1.0f; + } + + // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most) + if (!IsNavInputDown(ImGuiNavInput_Menu)) + { + g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. + if (g.NavWindowingToggleLayer && g.NavWindow) + apply_toggle_layer = true; + else if (!g.NavWindowingToggleLayer) + apply_focus_window = g.NavWindowingTarget; + g.NavWindowingTarget = NULL; + } + } + + // Keyboard: Focus + if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard) + { + // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f + if (IsKeyPressedMap(ImGuiKey_Tab, true)) + NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1); + if (!g.IO.KeyCtrl) + apply_focus_window = g.NavWindowingTarget; + } + + // Keyboard: Press and Release ALT to toggle menu layer + // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB + if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released)) + if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev)) + apply_toggle_layer = true; + + // Move window + if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove)) + { + ImVec2 move_delta; + if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift) + move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); + if (g.NavInputSource == ImGuiInputSource_NavGamepad) + move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down); + if (move_delta.x != 0.0f || move_delta.y != 0.0f) + { + const float NAV_MOVE_SPEED = 800.0f; + const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well + g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed; + g.NavDisableMouseHover = true; + MarkIniSettingsDirty(g.NavWindowingTarget); + } + } + + // Apply final focus + if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) + { + g.NavDisableHighlight = false; + g.NavDisableMouseHover = true; + apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); + ClosePopupsOverWindow(apply_focus_window); + FocusWindow(apply_focus_window); + if (apply_focus_window->NavLastIds[0] == 0) + NavInitWindow(apply_focus_window, false); + + // If the window only has a menu layer, select it directly + if (apply_focus_window->DC.NavLayerActiveMask == (1 << 1)) + g.NavLayer = 1; + } + if (apply_focus_window) + g.NavWindowingTarget = NULL; + + // Apply menu/layer toggle + if (apply_toggle_layer && g.NavWindow) + { + // Move to parent menu if necessary + ImGuiWindow* new_nav_window = g.NavWindow; + while ((new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + new_nav_window = new_nav_window->ParentWindow; + if (new_nav_window != g.NavWindow) + { + ImGuiWindow* old_nav_window = g.NavWindow; + FocusWindow(new_nav_window); + new_nav_window->NavLastChildNavWindow = old_nav_window; + } + g.NavDisableHighlight = false; + g.NavDisableMouseHover = true; + NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0); + } +} + +// Window has already passed the IsWindowNavFocusable() +static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window) +{ + if (window->Flags & ImGuiWindowFlags_Popup) + return "(Popup)"; + if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0) + return "(Main menu bar)"; + return "(Untitled)"; +} + +// Overlay displayed when using CTRL+TAB. Called by EndFrame(). +void ImGui::NavUpdateWindowingList() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.NavWindowingTarget != NULL); + + if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) + return; + + if (g.NavWindowingList == NULL) + g.NavWindowingList = FindWindowByName("###NavWindowingList"); + SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); + SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); + Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); + for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) + { + ImGuiWindow* window = g.WindowsFocusOrder[n]; + if (!IsWindowNavFocusable(window)) + continue; + const char* label = window->Name; + if (label == FindRenderedTextEnd(label)) + label = GetFallbackWindowNameForWindowingList(window); + Selectable(label, g.NavWindowingTarget == window); + } + End(); + PopStyleVar(); +} + +//----------------------------------------------------------------------------- +// [SECTION] COLUMNS +// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. +//----------------------------------------------------------------------------- + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.ColumnsSet == NULL) + return; + + ImGuiContext& g = *GImGui; + PopItemWidth(); + PopClipRect(); + + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + if (++columns->Current < columns->Count) + { + // Columns 1+ cancel out IndentX + window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; + window->DrawList->ChannelsSetCurrent(columns->Current); + } + else + { + window->DC.ColumnsOffset.x = 0.0f; + window->DrawList->ChannelsSetCurrent(0); + columns->Current = 0; + columns->LineMinY = columns->LineMaxY; + } + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->DC.CursorPos.y = columns->LineMinY; + window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrentLineTextBaseOffset = 0.0f; + + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup +} + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1; +} + +static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm) +{ + return offset_norm * (columns->MaxX - columns->MinX); +} + +static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset) +{ + return offset / (columns->MaxX - columns->MinX); +} + +static inline float GetColumnsRectHalfWidth() { return 4.0f; } + +static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. + IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x; + x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); + if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) + x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); + + return x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const float t = columns->Columns[column_index].OffsetNorm; + const float x_offset = ImLerp(columns->MinX, columns->MaxX, t); + return x_offset; +} + +static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false) +{ + if (column_index < 0) + column_index = columns->Current; + + float offset_norm; + if (before_resize) + offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; + else + offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; + return OffsetNormToPixels(columns, offset_norm); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); + const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; + + if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) + offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); + columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX); + + if (preserve_width) + SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); +} + +void ImGui::SetColumnWidth(int column_index, float width) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); +} + +void ImGui::PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + if (column_index < 0) + column_index = columns->Current; + + PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false); +} + +static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id) +{ + for (int n = 0; n < window->ColumnsStorage.Size; n++) + if (window->ColumnsStorage[n].ID == id) + return &window->ColumnsStorage[n]; + + window->ColumnsStorage.push_back(ImGuiColumnsSet()); + ImGuiColumnsSet* columns = &window->ColumnsStorage.back(); + columns->ID = id; + return columns; +} + +void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(columns_count > 1); + IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (str_id ? 0 : columns_count)); + ImGuiID id = window->GetID(str_id ? str_id : "columns"); + PopID(); + + // Acquire storage for the columns set + ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id); + IM_ASSERT(columns->ID == id); + columns->Current = 0; + columns->Count = columns_count; + columns->Flags = flags; + window->DC.ColumnsSet = columns; + + // Set state for first column + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x); + columns->MinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range + columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f); + columns->StartPosY = window->DC.CursorPos.y; + columns->StartMaxPosX = window->DC.CursorMaxPos.x; + columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + + // Clear data if columns count changed + if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) + columns->Columns.resize(0); + + // Initialize defaults + columns->IsFirstFrame = (columns->Columns.Size == 0); + if (columns->Columns.Size == 0) + { + columns->Columns.reserve(columns_count + 1); + for (int n = 0; n < columns_count + 1; n++) + { + ImGuiColumnData column; + column.OffsetNorm = n / (float)columns_count; + columns->Columns.push_back(column); + } + } + + for (int n = 0; n < columns_count; n++) + { + // Compute clipping rectangle + ImGuiColumnData* column = &columns->Columns[n]; + float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f); + float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); + column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); + column->ClipRect.ClipWith(window->ClipRect); + } + + window->DrawList->ChannelsSplit(columns->Count); + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); +} + +void ImGui::EndColumns() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + IM_ASSERT(columns != NULL); + + PopItemWidth(); + PopClipRect(); + window->DrawList->ChannelsMerge(); + + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = columns->LineMaxY; + if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize)) + window->DC.CursorMaxPos.x = columns->StartMaxPosX; // Restore cursor max pos, as columns don't grow parent + + // Draw columns borders and handle resize + bool is_being_resized = false; + if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) + { + const float y1 = columns->StartPosY; + const float y2 = window->DC.CursorPos.y; + int dragging_column = -1; + for (int n = 1; n < columns->Count; n++) + { + float x = window->Pos.x + GetColumnOffset(n); + const ImGuiID column_id = columns->ID + ImGuiID(n); + const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction + const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2)); + KeepAliveID(column_id); + if (IsClippedEx(column_rect, column_id, false)) + continue; + + bool hovered = false, held = false; + if (!(columns->Flags & ImGuiColumnsFlags_NoResize)) + { + ButtonBehavior(column_rect, column_id, &hovered, &held); + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeEW; + if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize)) + dragging_column = n; + } + + // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.) + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + const float xi = (float)(int)x; + window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col); + } + + // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. + if (dragging_column != -1) + { + if (!columns->IsBeingResized) + for (int n = 0; n < columns->Count + 1; n++) + columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; + columns->IsBeingResized = is_being_resized = true; + float x = GetDraggedColumnOffset(columns, dragging_column); + SetColumnOffset(dragging_column, x); + } + } + columns->IsBeingResized = is_being_resized; + + window->DC.ColumnsSet = NULL; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); +} + +// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); + //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior + if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count == columns_count && window->DC.ColumnsSet->Flags == flags) + return; + + if (window->DC.ColumnsSet != NULL) + EndColumns(); + + if (columns_count != 1) + BeginColumns(id, columns_count, flags); +} + +//----------------------------------------------------------------------------- +// [SECTION] DRAG AND DROP +//----------------------------------------------------------------------------- + +void ImGui::ClearDragDrop() +{ + ImGuiContext& g = *GImGui; + g.DragDropActive = false; + g.DragDropPayload.Clear(); + g.DragDropAcceptFlags = 0; + g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; + g.DragDropAcceptIdCurrRectSurface = FLT_MAX; + g.DragDropAcceptFrameCount = -1; + + g.DragDropPayloadBufHeap.clear(); + memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); +} + +// Call when current ID is active. +// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() +bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + bool source_drag_active = false; + ImGuiID source_id = 0; + ImGuiID source_parent_id = 0; + int mouse_button = 0; + if (!(flags & ImGuiDragDropFlags_SourceExtern)) + { + source_id = window->DC.LastItemId; + if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case + return false; + if (g.IO.MouseDown[mouse_button] == false) + return false; + + if (source_id == 0) + { + // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: + // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride. + if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) + { + IM_ASSERT(0); + return false; + } + + // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image() + // We build a throwaway ID based on current ID stack + relative AABB of items in window. + // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. + // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. + bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0; + if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window)) + return false; + source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect); + if (is_hovered) + SetHoveredID(source_id); + if (is_hovered && g.IO.MouseClicked[mouse_button]) + { + SetActiveID(source_id, window); + FocusWindow(window); + } + if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. + g.ActiveIdAllowOverlap = is_hovered; + } + else + { + g.ActiveIdAllowOverlap = false; + } + if (g.ActiveId != source_id) + return false; + source_parent_id = window->IDStack.back(); + source_drag_active = IsMouseDragging(mouse_button); + } + else + { + window = NULL; + source_id = ImHash("#SourceExtern", 0); + source_drag_active = true; + } + + if (source_drag_active) + { + if (!g.DragDropActive) + { + IM_ASSERT(source_id != 0); + ClearDragDrop(); + ImGuiPayload& payload = g.DragDropPayload; + payload.SourceId = source_id; + payload.SourceParentId = source_parent_id; + g.DragDropActive = true; + g.DragDropSourceFlags = flags; + g.DragDropMouseButton = mouse_button; + } + g.DragDropSourceFrameCount = g.FrameCount; + g.DragDropWithinSourceOrTarget = true; + + if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + { + // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) + // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. + BeginTooltip(); + if (g.DragDropActive && g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) + { + ImGuiWindow* tooltip_window = g.CurrentWindow; + tooltip_window->SkipItems = true; + tooltip_window->HiddenFramesRegular = 1; + } + } + + if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern)) + window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect; + + return true; + } + return false; +} + +void ImGui::EndDragDropSource() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.DragDropActive); + IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?"); + + if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + EndTooltip(); + + // Discard the drag if have not called SetDragDropPayload() + if (g.DragDropPayload.DataFrameCount == -1) + ClearDragDrop(); + g.DragDropWithinSourceOrTarget = false; +} + +// Use 'cond' to choose to submit payload on drag start or every frame +bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + ImGuiPayload& payload = g.DragDropPayload; + if (cond == 0) + cond = ImGuiCond_Always; + + IM_ASSERT(type != NULL); + IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long"); + IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); + IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); + IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() + + if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) + { + // Copy payload + ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType)); + g.DragDropPayloadBufHeap.resize(0); + if (data_size > sizeof(g.DragDropPayloadBufLocal)) + { + // Store in heap + g.DragDropPayloadBufHeap.resize((int)data_size); + payload.Data = g.DragDropPayloadBufHeap.Data; + memcpy(payload.Data, data, data_size); + } + else if (data_size > 0) + { + // Store locally + memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); + payload.Data = g.DragDropPayloadBufLocal; + memcpy(payload.Data, data, data_size); + } + else + { + payload.Data = NULL; + } + payload.DataSize = (int)data_size; + } + payload.DataFrameCount = g.FrameCount; + + return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1); +} + +bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (!g.DragDropActive) + return false; + + ImGuiWindow* window = g.CurrentWindow; + if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) + return false; + IM_ASSERT(id != 0); + if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) + return false; + if (window->SkipItems) + return false; + + IM_ASSERT(g.DragDropWithinSourceOrTarget == false); + g.DragDropTargetRect = bb; + g.DragDropTargetId = id; + g.DragDropWithinSourceOrTarget = true; + return true; +} + +// We don't use BeginDragDropTargetCustom() and duplicate its code because: +// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. +// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. +// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) +bool ImGui::BeginDragDropTarget() +{ + ImGuiContext& g = *GImGui; + if (!g.DragDropActive) + return false; + + ImGuiWindow* window = g.CurrentWindow; + if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) + return false; + if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) + return false; + + const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect; + ImGuiID id = window->DC.LastItemId; + if (id == 0) + id = window->GetIDFromRectangle(display_rect); + if (g.DragDropPayload.SourceId == id) + return false; + + IM_ASSERT(g.DragDropWithinSourceOrTarget == false); + g.DragDropTargetRect = display_rect; + g.DragDropTargetId = id; + g.DragDropWithinSourceOrTarget = true; + return true; +} + +bool ImGui::IsDragDropPayloadBeingAccepted() +{ + ImGuiContext& g = *GImGui; + return g.DragDropActive && g.DragDropAcceptIdPrev != 0; +} + +const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiPayload& payload = g.DragDropPayload; + IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? + IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? + if (type != NULL && !payload.IsDataType(type)) + return NULL; + + // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. + // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function! + const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); + ImRect r = g.DragDropTargetRect; + float r_surface = r.GetWidth() * r.GetHeight(); + if (r_surface < g.DragDropAcceptIdCurrRectSurface) + { + g.DragDropAcceptFlags = flags; + g.DragDropAcceptIdCurr = g.DragDropTargetId; + g.DragDropAcceptIdCurrRectSurface = r_surface; + } + + // Render default drop visuals + payload.Preview = was_accepted_previously; + flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame) + if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) + { + // FIXME-DRAG: Settle on a proper default visuals for drop target. + r.Expand(3.5f); + bool push_clip_rect = !window->ClipRect.Contains(r); + if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1)); + window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f); + if (push_clip_rect) window->DrawList->PopClipRect(); + } + + g.DragDropAcceptFrameCount = g.FrameCount; + payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() + if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) + return NULL; + + return &payload; +} + +const ImGuiPayload* ImGui::GetDragDropPayload() +{ + ImGuiContext& g = *GImGui; + return g.DragDropActive ? &g.DragDropPayload : NULL; +} + +// We don't really use/need this now, but added it for the sake of consistency and because we might need it later. +void ImGui::EndDragDropTarget() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.DragDropActive); + IM_ASSERT(g.DragDropWithinSourceOrTarget); + g.DragDropWithinSourceOrTarget = false; +} + +//----------------------------------------------------------------------------- +// [SECTION] LOGGING/CAPTURING +//----------------------------------------------------------------------------- + +// Pass text data straight to log (without being displayed) +void ImGui::LogText(const char* fmt, ...) +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + va_list args; + va_start(args, fmt); + if (g.LogFile) + vfprintf(g.LogFile, fmt, args); + else + g.LogClipboard.appendfv(fmt, args); + va_end(args); +} + +// Internal version that takes a position to decide on newline placement and pad items according to their depth. +// We split text into individual lines to add current tree level padding +void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (!text_end) + text_end = FindRenderedTextEnd(text, text_end); + + const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1); + if (ref_pos) + window->DC.LogLinePosY = ref_pos->y; + + const char* text_remaining = text; + if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth + g.LogStartDepth = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); + for (;;) + { + // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. + const char* line_start = text_remaining; + const char* line_end = ImStreolRange(line_start, text_end); + const bool is_first_line = (line_start == text); + const bool is_last_line = (line_end == text_end); + if (!is_last_line || (line_start != line_end)) + { + const int char_count = (int)(line_end - line_start); + if (log_new_line || !is_first_line) + LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, line_start); + else + LogText(" %.*s", char_count, line_start); + } + + if (is_last_line) + break; + text_remaining = line_end + 1; + } +} + +// Start logging ImGui output to TTY +void ImGui::LogToTTY(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = g.CurrentWindow; + + IM_ASSERT(g.LogFile == NULL); + g.LogFile = stdout; + g.LogEnabled = true; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to given file +void ImGui::LogToFile(int max_depth, const char* filename) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = g.CurrentWindow; + + if (!filename) + { + filename = g.IO.LogFilename; + if (!filename) + return; + } + + IM_ASSERT(g.LogFile == NULL); + g.LogFile = ImFileOpen(filename, "ab"); + if (!g.LogFile) + { + IM_ASSERT(g.LogFile != NULL); // Consider this an error + return; + } + g.LogEnabled = true; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to clipboard +void ImGui::LogToClipboard(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = g.CurrentWindow; + + IM_ASSERT(g.LogFile == NULL); + g.LogFile = NULL; + g.LogEnabled = true; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +void ImGui::LogFinish() +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + LogText(IM_NEWLINE); + if (g.LogFile != NULL) + { + if (g.LogFile == stdout) + fflush(g.LogFile); + else + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.LogClipboard.size() > 1) + { + SetClipboardText(g.LogClipboard.begin()); + g.LogClipboard.clear(); + } + g.LogEnabled = false; +} + +// Helper to display logging buttons +void ImGui::LogButtons() +{ + ImGuiContext& g = *GImGui; + + PushID("LogButtons"); + const bool log_to_tty = Button("Log To TTY"); SameLine(); + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemWidth(80.0f); + PushAllowKeyboardFocus(false); + SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopItemWidth(); + PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(g.LogAutoExpandMaxDepth); + if (log_to_file) + LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); + if (log_to_clipboard) + LogToClipboard(g.LogAutoExpandMaxDepth); +} + +//----------------------------------------------------------------------------- +// [SECTION] SETTINGS +//----------------------------------------------------------------------------- + +void ImGui::MarkIniSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +void ImGui::MarkIniSettingsDirty(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + g.SettingsWindows.push_back(ImGuiWindowSettings()); + ImGuiWindowSettings* settings = &g.SettingsWindows.back(); + settings->Name = ImStrdup(name); + settings->ID = ImHash(name, 0); + return settings; +} + +ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + for (int i = 0; i != g.SettingsWindows.Size; i++) + if (g.SettingsWindows[i].ID == id) + return &g.SettingsWindows[i]; + return NULL; +} + +void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) +{ + size_t file_data_size = 0; + char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); + if (!file_data) + return; + LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); + ImGui::MemFree(file_data); +} + +ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) +{ + ImGuiContext& g = *GImGui; + const ImGuiID type_hash = ImHash(type_name, 0, 0); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].TypeHash == type_hash) + return &g.SettingsHandlers[handler_n]; + return NULL; +} + +// Zero-tolerance, no error reporting, cheap .ini parsing +void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); + + // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). + // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. + if (ini_size == 0) + ini_size = strlen(ini_data); + char* buf = (char*)ImGui::MemAlloc(ini_size + 1); + char* buf_end = buf + ini_size; + memcpy(buf, ini_data, ini_size); + buf[ini_size] = 0; + + void* entry_data = NULL; + ImGuiSettingsHandler* entry_handler = NULL; + + char* line_end = NULL; + for (char* line = buf; line < buf_end; line = line_end + 1) + { + // Skip new lines markers, then find end of the line + while (*line == '\n' || *line == '\r') + line++; + line_end = line; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + line_end[0] = 0; + if (line[0] == ';') + continue; + if (line[0] == '[' && line_end > line && line_end[-1] == ']') + { + // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. + line_end[-1] = 0; + const char* name_end = line_end - 1; + const char* type_start = line + 1; + char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); + const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; + if (!type_end || !name_start) + { + name_start = type_start; // Import legacy entries that have no type + type_start = "Window"; + } + else + { + *type_end = 0; // Overwrite first ']' + name_start++; // Skip second '[' + } + entry_handler = FindSettingsHandler(type_start); + entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; + } + else if (entry_handler != NULL && entry_data != NULL) + { + // Let type handler parse the line + entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); + } + } + ImGui::MemFree(buf); + g.SettingsLoaded = true; +} + +void ImGui::SaveIniSettingsToDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + if (!ini_filename) + return; + + size_t ini_data_size = 0; + const char* ini_data = SaveIniSettingsToMemory(&ini_data_size); + FILE* f = ImFileOpen(ini_filename, "wt"); + if (!f) + return; + fwrite(ini_data, sizeof(char), ini_data_size, f); + fclose(f); +} + +// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer +const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + g.SettingsIniData.Buf.resize(0); + g.SettingsIniData.Buf.push_back(0); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + { + ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n]; + handler->WriteAllFn(&g, handler, &g.SettingsIniData); + } + if (out_size) + *out_size = (size_t)g.SettingsIniData.size(); + return g.SettingsIniData.c_str(); +} + +static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0)); + if (!settings) + settings = ImGui::CreateNewWindowSettings(name); + return (void*)settings; +} + +static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +{ + ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; + float x, y; + int i; + if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); + else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); + else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); +} + +static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + // Gather data from windows that were active during this session + // (if a window wasn't opened in this session we preserve its settings) + ImGuiContext& g = *imgui_ctx; + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + + ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID); + if (!settings) + { + settings = ImGui::CreateNewWindowSettings(window->Name); + window->SettingsIdx = g.SettingsWindows.index_from_pointer(settings); + } + IM_ASSERT(settings->ID == window->ID); + settings->Pos = window->Pos; + settings->Size = window->SizeFull; + settings->Collapsed = window->Collapsed; + } + + // Write to text buffer + buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve + for (int i = 0; i != g.SettingsWindows.Size; i++) + { + const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; + if (settings->Pos.x == FLT_MAX) + continue; + const char* name = settings->Name; + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; + buf->appendf("[%s][%s]\n", handler->TypeName, name); + buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + buf->appendf("Collapsed=%d\n", settings->Collapsed); + buf->appendf("\n"); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] PLATFORM DEPENDENT HELPERS +//----------------------------------------------------------------------------- + +#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef __MINGW32__ +#include +#else +#include +#endif +#endif + +// Win32 API clipboard implementation +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) + +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#endif + +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + static ImVector buf_local; + buf_local.clear(); + if (!::OpenClipboard(NULL)) + return NULL; + HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); + if (wbuf_handle == NULL) + { + ::CloseClipboard(); + return NULL; + } + if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle)) + { + int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; + buf_local.resize(buf_len); + ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); + } + ::GlobalUnlock(wbuf_handle); + ::CloseClipboard(); + return buf_local.Data; +} + +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + if (!::OpenClipboard(NULL)) + return; + const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; + HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); + if (wbuf_handle == NULL) + { + ::CloseClipboard(); + return; + } + ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle); + ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); + ::GlobalUnlock(wbuf_handle); + ::EmptyClipboard(); + if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL) + ::GlobalFree(wbuf_handle); + ::CloseClipboard(); +} + +#else + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + ImGuiContext& g = *GImGui; + return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin(); +} + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + ImGuiContext& g = *GImGui; + g.PrivateClipboard.clear(); + const char* text_end = text + strlen(text); + g.PrivateClipboard.resize((int)(text_end - text) + 1); + memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text)); + g.PrivateClipboard[(int)(text_end - text)] = 0; +} + +#endif + +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) + +#include +#ifdef _MSC_VER +#pragma comment(lib, "imm32") +#endif + +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) +{ + // Notify OS Input Method Editor of text input position + if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) + if (HIMC himc = ::ImmGetContext(hwnd)) + { + COMPOSITIONFORM cf; + cf.ptCurrentPos.x = x; + cf.ptCurrentPos.y = y; + cf.dwStyle = CFS_FORCE_POSITION; + ::ImmSetCompositionWindow(himc, &cf); + ::ImmReleaseContext(hwnd, himc); + } +} + +#else + +static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} + +#endif + +//----------------------------------------------------------------------------- +// [SECTION] METRICS/DEBUG WINDOW +//----------------------------------------------------------------------------- + +void ImGui::ShowMetricsWindow(bool* p_open) +{ + if (!ImGui::Begin("ImGui Metrics", p_open)) + { + ImGui::End(); + return; + } + static bool show_draw_cmd_clip_rects = true; + static bool show_window_begin_order = false; + ImGuiIO& io = ImGui::GetIO(); + ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); + ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); + ImGui::Text("%d allocations", io.MetricsActiveAllocations); + ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_draw_cmd_clip_rects); + ImGui::Checkbox("Ctrl shows window begin order", &show_window_begin_order); + + ImGui::Separator(); + + struct Funcs + { + static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) + { + bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); + if (draw_list == ImGui::GetWindowDrawList()) + { + ImGui::SameLine(); + ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) ImGui::TreePop(); + return; + } + + ImDrawList* overlay_draw_list = GetOverlayDrawList(window); // Render additional visuals into the top-most draw list + if (window && IsItemHovered()) + overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!node_open) + return; + + int elem_offset = 0; + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) + { + if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0) + continue; + if (pcmd->UserCallback) + { + ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + if (show_draw_cmd_clip_rects && ImGui::IsItemHovered()) + { + ImRect clip_rect = pcmd->ClipRect; + ImRect vtxs_rect; + for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) + vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); + clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); + vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + } + if (!pcmd_node_open) + continue; + + // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. + ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + { + char buf[300]; + char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); + ImVec2 triangles_pos[3]; + for (int n = 0; n < 3; n++, vtx_i++) + { + ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; + triangles_pos[n] = v.pos; + buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + ImGui::Selectable(buf, false); + if (ImGui::IsItemHovered()) + { + ImDrawListFlags backup_flags = overlay_draw_list->Flags; + overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. + overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); + overlay_draw_list->Flags = backup_flags; + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + static void NodeWindows(ImVector& windows, const char* label) + { + if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) + return; + for (int i = 0; i < windows.Size; i++) + Funcs::NodeWindow(windows[i], "Window"); + ImGui::TreePop(); + } + + static void NodeWindow(ImGuiWindow* window, const char* label) + { + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) + return; + ImGuiWindowFlags flags = window->Flags; + NodeDrawList(window, window->DrawList, "DrawList"); + ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); + ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, + (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", + (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", + (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); + ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window)); + ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); + ImGui::BulletText("Appearing: %d, Hidden: %d (Reg %d Resize %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesRegular, window->HiddenFramesForResize, window->SkipItems); + ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); + ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); + if (!window->NavRectRel[0].IsInverted()) + ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); + else + ImGui::BulletText("NavRectRel[0]: "); + if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); + if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow"); + if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); + if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) + { + for (int n = 0; n < window->ColumnsStorage.Size; n++) + { + const ImGuiColumnsSet* columns = &window->ColumnsStorage[n]; + if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) + { + ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX); + for (int column_n = 0; column_n < columns->Columns.Size; column_n++) + ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm)); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); + ImGui::TreePop(); + } + }; + + // Access private state, we are going to display the draw lists from last frame + ImGuiContext& g = *GImGui; + Funcs::NodeWindows(g.Windows, "Windows"); + if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) + { + for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++) + Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) + { + for (int i = 0; i < g.OpenPopupStack.Size; i++) + { + ImGuiWindow* window = g.OpenPopupStack[i].Window; + ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); + } + ImGui::TreePop(); + } + if (ImGui::TreeNode("Internal state")) + { + const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); + ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); + ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); + ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); + ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); + ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]); + ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); + ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); + ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); + ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); + ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + ImGui::TreePop(); + } + + + if (g.IO.KeyCtrl && show_window_begin_order) + { + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow* window = g.Windows[n]; + if ((window->Flags & ImGuiWindowFlags_ChildWindow) || !window->WasActive) + continue; + char buf[32]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); + float font_size = ImGui::GetFontSize() * 2; + ImDrawList* overlay_draw_list = GetOverlayDrawList(window); + overlay_draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); + overlay_draw_list->AddText(NULL, font_size, window->Pos, IM_COL32(255, 255, 255, 255), buf); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- + +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. +#ifdef IMGUI_INCLUDE_IMGUI_USER_INL +#include "imgui_user.inl" +#endif + +//----------------------------------------------------------------------------- diff --git a/src/3rdparty/imgui/imgui.h b/src/3rdparty/imgui/imgui.h new file mode 100644 index 000000000..1ee65d309 --- /dev/null +++ b/src/3rdparty/imgui/imgui.h @@ -0,0 +1,2050 @@ +// dear imgui, v1.66b +// (headers) + +// See imgui.cpp file for documentation. +// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. +// Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui + +/* + +Index of this file: +// Header mess +// Forward declarations and basic types +// ImGui API (Dear ImGui end-user API) +// Flags & Enumerations +// ImGuiStyle +// ImGuiIO +// Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +// Obsolete functions +// Helpers (ImVector, ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) +// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) +// Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFont) + +*/ + +#pragma once + +// Configuration file (edit imconfig.h or define IMGUI_USER_CONFIG to your own filename) +#ifdef IMGUI_USER_CONFIG +#include IMGUI_USER_CONFIG +#endif +#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) +#include "imconfig.h" +#endif + +//----------------------------------------------------------------------------- +// Header mess +//----------------------------------------------------------------------------- + +#include // FLT_MAX +#include // va_list +#include // ptrdiff_t, NULL +#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +// Version +// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY00 then bounced up to XYY01 when release tagging happens) +#define IMGUI_VERSION "1.66b" +#define IMGUI_VERSION_NUM 16602 +#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) + +// Define attributes of all API symbols declarations (e.g. for DLL under Windows) +// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h) +#ifndef IMGUI_API +#define IMGUI_API +#endif +#ifndef IMGUI_IMPL_API +#define IMGUI_IMPL_API IMGUI_API +#endif + +// Helper Macros +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h +#endif +#if defined(__clang__) || defined(__GNUC__) +#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // Apply printf-style warnings to user functions. +#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) +#else +#define IM_FMTARGS(FMT) +#define IM_FMTLIST(FMT) +#endif +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers! +#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++. + +// Warnings +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#elif defined(__GNUC__) && __GNUC__ >= 8 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wclass-memaccess" +#endif + +//----------------------------------------------------------------------------- +// Forward declarations and basic types +//----------------------------------------------------------------------------- + +struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) +struct ImDrawData; // All draw command lists required to render the frame +struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) +struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) +struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*obsolete* please avoid using) +#ifndef ImTextureID +typedef void* ImTextureID; // User data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) +#endif +struct ImGuiContext; // ImGui context (opaque) +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro +struct ImGuiPayload; // User data payload for drag and drop operations +struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) +struct ImGuiStorage; // Helper for key->value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbb][,ccccc]") +struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) + +// Typedefs and Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file) +// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. +typedef unsigned int ImGuiID; // Unique ID used by widgets (typically hashed from a stack of string) +typedef unsigned short ImWchar; // Character for keyboard input/display +typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling +typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for Set*() +typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type +typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction +typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum) +typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation +typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier +typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling +typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect*() etc. +typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas +typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit*(), ColorPicker*() +typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: for Columns(), BeginColumns() +typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags +typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for *DragDrop*() +typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() +typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. +typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText*() +typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode*(),CollapsingHeader() +typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin*() +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); +typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); + +// Scalar data types +typedef signed int ImS32; // 32-bit signed integer == int +typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) +#if defined(_MSC_VER) && !defined(__clang__) +typedef signed __int64 ImS64; // 64-bit signed integer (pre and post C++11 with Visual Studio) +typedef unsigned __int64 ImU64; // 64-bit unsigned integer (pre and post C++11 with Visual Studio) +#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100) +#include +typedef int64_t ImS64; // 64-bit signed integer (pre C++11) +typedef uint64_t ImU64; // 64-bit unsigned integer (pre C++11) +#else +typedef signed long long ImS64; // 64-bit signed integer (post C++11) +typedef unsigned long long ImU64; // 64-bit unsigned integer (post C++11) +#endif + +// 2D vector (often used to store positions, sizes, etc.) +struct ImVec2 +{ + float x, y; + ImVec2() { x = y = 0.0f; } + ImVec2(float _x, float _y) { x = _x; y = _y; } + float operator[] (size_t i) const { IM_ASSERT(i <= 1); return (&x)[i]; } // We very rarely use this [] operator, the assert overhead is fine. +#ifdef IM_VEC2_CLASS_EXTRA + IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. +#endif +}; + +// 4D vector (often used to store floating-point colors) +struct ImVec4 +{ + float x, y, z, w; + ImVec4() { x = y = z = w = 0.0f; } + ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } +#ifdef IM_VEC4_CLASS_EXTRA + IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. +#endif +}; + +//----------------------------------------------------------------------------- +// ImGui: Dear ImGui end-user API +// (Inside a namespace so you can add extra functions in your own separate file. Please don't modify imgui.cpp/.h!) +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Context creation and access + // Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between imgui contexts. + // All those functions are not reliant on the current context. + IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert); + + // Main + IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame. + IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Render()/EndFrame(). + IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Render(), you likely don't need to call that yourself directly. If you don't need to render data (skipping rendering) you may call EndFrame() but you'll have wasted CPU already! If you don't need to render, better to not create any imgui windows and not call NewFrame() at all! + IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data. (Obsolete: optionally call io.RenderDrawListsFn if set. Nowadays, prefer calling your render function yourself.) + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. (Obsolete: this used to be passed to your io.RenderDrawListsFn() function.) + + // Demo, Debug, Information + IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create about window. display Dear ImGui version, credits and build/system information. + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. + IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. + IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). + IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.23" + + // Styles + IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) + IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style + IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font + + // Windows + // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. + // - You may append multiple times to the same window during the same frame. + // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, which clicking will set the boolean to false when clicked. + // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. + // Always call a matching End() for each Begin() call, regardless of its return value [this is due to legacy reason and is inconsistent with most other functions such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function returned true.] + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); + IMGUI_API void End(); + + // Child Windows + // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. + // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). + // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. + // Always call a matching EndChild() for each BeginChild() call, regardless of its return value [this is due to legacy reason and is inconsistent with most other functions such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function returned true.] + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API void EndChild(); + + // Windows Utilities + IMGUI_API bool IsWindowAppearing(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. + IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the window, to append your own drawing primitives + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) + IMGUI_API ImVec2 GetWindowSize(); // get current window size + IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) + IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API float GetContentRegionAvailWidth(); // + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates + IMGUI_API float GetWindowContentRegionWidth(); // + + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() + IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. + + // Windows Scrolling + IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] + IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. + + // Parameters stacks (shared) + IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + IMGUI_API void PopFont(); + IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied + IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) + IMGUI_API void PopItemWidth(); + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position + IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); + + // Cursor / Layout + IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. + IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally + IMGUI_API void NewLine(); // undo a SameLine() + IMGUI_API void Spacing(); // add vertical spacing + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API void EndGroup(); + IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position + IMGUI_API float GetCursorPosX(); // " + IMGUI_API float GetCursorPosY(); // " + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // " + IMGUI_API void SetCursorPosX(float x); // " + IMGUI_API void SetCursorPosY(float y); // " + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) + IMGUI_API void SetCursorScreenPos(const ImVec2& screen_pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] + IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) + IMGUI_API float GetTextLineHeight(); // ~ FontSize + IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) + IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 + IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) + + // ID stack/scopes + // Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most + // likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. + // You can also use the "##foobar" syntax within widget label to distinguish them from each others. + // In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID, + // whereas "str_id" denote a string that is only used as an ID and not aimed to be displayed. + IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the entire stack! + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); + IMGUI_API void PushID(const void* ptr_id); + IMGUI_API void PushID(int int_id); + IMGUI_API void PopID(); + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + + // Widgets: Text + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. + IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text + IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Widgets: Main + // Most widgets return true when the value has been changed or when pressed/selected + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); + IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + + // Widgets: Combo Box + // The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. + // The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. + IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); + IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! + IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" + IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); + + // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) + // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + // Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f); + + // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) + // Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg"); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d"); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d"); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d"); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d"); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d"); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f); + + // Widgets: Input with Keyboard + // If you want to use InputText() with a dynamic string type such as std::string or your own, see misc/cpp/imgui_stdlib.h + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0f, double step_fast = 0.0f, const char* format = "%.6f", ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* v, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags extra_flags = 0); + + // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) + // Note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x + IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed. + IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. + + // Widgets: Trees + // TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. + IMGUI_API bool TreeNode(const char* label); + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to completely decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(const void* ptr_id = NULL); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header + + // Widgets: Selectables + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + + // Widgets: List Boxes + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards. + IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " + IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true! + + // Widgets: Data Plotting + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + + // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + + // Widgets: Menus + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. + IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). + IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Tooltips + IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items). + IMGUI_API void EndTooltip(); + IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip(). + IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Popups + IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, int mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, int mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. + IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open + IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. + + // Columns + // You can also use SameLine(pos_x) for simplified columns. The columns API is work-in-progress and rather lacking (columns are arguably the worst part of dear imgui at the moment!) + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); + IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column + IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API int GetColumnsCount(); + + // Logging/Capture: all text output from interface is captured to tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty + IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) + + // Drag and Drop + // [BETA API] Missing Demo code. API may evolve. + IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource() + IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. + IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! + IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() + IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. + IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! + IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type. + + // Clipping + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Focus, Activation + // (Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item") + IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. + + // Item/Widgets Utilities + // See Demo Window under "Widgets->Querying Status" for an interactive visualization of many of those functions. + IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. + IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) + IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? + IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered() + IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) + IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. + IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing. + IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). + IMGUI_API bool IsAnyItemHovered(); + IMGUI_API bool IsAnyItemActive(); + IMGUI_API bool IsAnyItemFocused(); + IMGUI_API ImVec2 GetItemRectMin(); // get bounding rectangle of last item, in screen space + IMGUI_API ImVec2 GetItemRectMax(); // " + IMGUI_API ImVec2 GetItemRectSize(); // get size of last item, in screen space + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. + + // Miscellaneous Utilities + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API double GetTime(); + IMGUI_API int GetFrameCount(); + IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text + IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); + IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window) + + // Color Utilities + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs Utilities + IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] + IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]! + IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down).. + IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate + IMGUI_API bool IsMouseDown(int button); // is mouse button held (0=left, 1=right, 2=middle) + IMGUI_API bool IsAnyMouseDown(); // is any mouse button held + IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) (0=left, 1=right, 2=middle) + IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. + IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) + IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. + IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse position at the time of opening popup we have BeginPopup() into + IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API void ResetMouseDragDelta(int button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type + IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. + IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). + + // Clipboard Utilities (also see the LogToClipboard() function to capture or output text data to the clipboard) + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Settings/.Ini Utilities + // The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). + // Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. + IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). + IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); + IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. + + // Memory Utilities + // All those functions are not reliant on the current context. + // If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again. + IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data = NULL); + IMGUI_API void* MemAlloc(size_t size); + IMGUI_API void MemFree(void* ptr); + +} // namespace ImGui + +//----------------------------------------------------------------------------- +// Flags & Enumerations +//----------------------------------------------------------------------------- + +// Flags for ImGui::Begin() +enum ImGuiWindowFlags_ +{ + ImGuiWindowFlags_None = 0, + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) + ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window + ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + + // [Internal] + ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) + ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu() + + // [Obsolete] + //ImGuiWindowFlags_ShowBorders = 1 << 7, // --> Set style.FrameBorderSize=1.0f / style.WindowBorderSize=1.0f to enable borders around windows and items + //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigResizeWindowsFromEdges and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) +}; + +// Flags for ImGui::InputText() +enum ImGuiInputTextFlags_ +{ + ImGuiInputTextFlags_None = 0, + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs + ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) + ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). + ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) + ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) + // [Internal] + ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_None = 0, + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). + //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap +#endif +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + ImGuiSelectableFlags_None = 0, + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too + ImGuiSelectableFlags_Disabled = 1 << 3 // Cannot be selected, display greyed out text +}; + +// Flags for ImGui::BeginCombo() +enum ImGuiComboFlags_ +{ + ImGuiComboFlags_None = 0, + ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default + ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) + ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible + ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible + ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button + ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button + ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest +}; + +// Flags for ImGui::IsWindowFocused() +enum ImGuiFocusedFlags_ +{ + ImGuiFocusedFlags_None = 0, + ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused + ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy) + ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use ImGui::GetIO().WantCaptureMouse instead. + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows +}; + +// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() +// Note: if you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that. Please read the FAQ! +// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. +enum ImGuiHoveredFlags_ +{ + ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered + ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window + //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window + ImGuiHoveredFlags_AllowWhenDisabled = 1 << 7, // Return true even if the item is disabled + ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, + ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows +}; + +// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() +enum ImGuiDragDropFlags_ +{ + ImGuiDragDropFlags_None = 0, + // BeginDragDropSource() flags + ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior. + ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item. + ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + // AcceptDragDropPayload() flags + ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. + ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery. +}; + +// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. +#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. + +// A primary data type +enum ImGuiDataType_ +{ + ImGuiDataType_S32, // int + ImGuiDataType_U32, // unsigned int + ImGuiDataType_S64, // long long, __int64 + ImGuiDataType_U64, // unsigned long long, unsigned __int64 + ImGuiDataType_Float, // float + ImGuiDataType_Double, // double + ImGuiDataType_COUNT +}; + +// A cardinal direction +enum ImGuiDir_ +{ + ImGuiDir_None = -1, + ImGuiDir_Left = 0, + ImGuiDir_Right = 1, + ImGuiDir_Up = 2, + ImGuiDir_Down = 3, + ImGuiDir_COUNT +}; + +// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array +enum ImGuiKey_ +{ + ImGuiKey_Tab, + ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, + ImGuiKey_UpArrow, + ImGuiKey_DownArrow, + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, + ImGuiKey_End, + ImGuiKey_Insert, + ImGuiKey_Delete, + ImGuiKey_Backspace, + ImGuiKey_Space, + ImGuiKey_Enter, + ImGuiKey_Escape, + ImGuiKey_A, // for text edit CTRL+A: select all + ImGuiKey_C, // for text edit CTRL+C: copy + ImGuiKey_V, // for text edit CTRL+V: paste + ImGuiKey_X, // for text edit CTRL+X: cut + ImGuiKey_Y, // for text edit CTRL+Y: redo + ImGuiKey_Z, // for text edit CTRL+Z: undo + ImGuiKey_COUNT +}; + +// Gamepad/Keyboard directional navigation +// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays. +// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Back-end: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). +// Read instructions in imgui.cpp for more details. Download PNG/PSD at http://goo.gl/9LgVZW. +enum ImGuiNavInput_ +{ + // Gamepad Mapping + ImGuiNavInput_Activate, // activate / open / toggle / tweak value // e.g. Cross (PS4), A (Xbox), A (Switch), Space (Keyboard) + ImGuiNavInput_Cancel, // cancel / close / exit // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard) + ImGuiNavInput_Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard) + ImGuiNavInput_Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard) + ImGuiNavInput_DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard) + ImGuiNavInput_DpadRight, // + ImGuiNavInput_DpadUp, // + ImGuiNavInput_DpadDown, // + ImGuiNavInput_LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down + ImGuiNavInput_LStickRight, // + ImGuiNavInput_LStickUp, // + ImGuiNavInput_LStickDown, // + ImGuiNavInput_FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) + ImGuiNavInput_FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) + ImGuiNavInput_TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) + ImGuiNavInput_TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) + + // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them. + // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from io.KeysDown[] instead of io.NavInputs[]. + ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt + ImGuiNavInput_KeyLeft_, // move left // = Arrow keys + ImGuiNavInput_KeyRight_, // move right + ImGuiNavInput_KeyUp_, // move up + ImGuiNavInput_KeyDown_, // move down + ImGuiNavInput_COUNT, + ImGuiNavInput_InternalStart_ = ImGuiNavInput_KeyMenu_ +}; + +// Configuration flags stored in io.ConfigFlags. Set by user/application. +enum ImGuiConfigFlags_ +{ + ImGuiConfigFlags_None = 0, + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeysDown[]. + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. Back-end also needs to set ImGuiBackendFlags_HasGamepad. + ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth. + ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end. + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + + // User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core ImGui) + ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. + ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse. +}; + +// Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end. +enum ImGuiBackendFlags_ +{ + ImGuiBackendFlags_None = 0, + ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2 // Back-end supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgActive, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Separator, + ImGuiCol_SeparatorHovered, + ImGuiCol_SeparatorActive, + ImGuiCol_ResizeGrip, + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TextSelectedBg, + ImGuiCol_DragDropTarget, + ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item + ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB + ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active + ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_COUNT + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg, ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive + , ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg + //ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered, // [unused since 1.60+] the close button now uses regular button colors. + //ImGuiCol_ComboBg, // [unused since 1.53+] ComboBg has been merged with PopupBg, so a redirect isn't accurate. +#endif +}; + +// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +// NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly. +// NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. +enum ImGuiStyleVar_ +{ + // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + ImGuiStyleVar_Alpha, // float Alpha + ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding + ImGuiStyleVar_WindowRounding, // float WindowRounding + ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize + ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize + ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign + ImGuiStyleVar_ChildRounding, // float ChildRounding + ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize + ImGuiStyleVar_PopupRounding, // float PopupRounding + ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize + ImGuiStyleVar_FramePadding, // ImVec2 FramePadding + ImGuiStyleVar_FrameRounding, // float FrameRounding + ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize + ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing + ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize + ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding + ImGuiStyleVar_GrabMinSize, // float GrabMinSize + ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_COUNT + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT, ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding +#endif +}; + +// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() +enum ImGuiColorEditFlags_ +{ + ImGuiColorEditFlags_None = 0, + ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer). + ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square. + ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs) + ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square). + ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. + + // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup. + ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. + ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). + ImGuiColorEditFlags_RGB = 1 << 20, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. + ImGuiColorEditFlags_HSV = 1 << 21, // [Inputs] // " + ImGuiColorEditFlags_HEX = 1 << 22, // [Inputs] // " + ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. + + // [Internal] Masks + ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX, + ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, + ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() +}; + +// Enumeration for GetMouseCursor() +// User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_ResizeAll, // (Unused by imgui functions) + ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border + ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column + ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Hand, // (Unused by imgui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_COUNT + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT +#endif +}; + +// Enumateration for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions +// Represent a condition. +// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. +enum ImGuiCond_ +{ + ImGuiCond_Always = 1 << 0, // Set the variable + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) + ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) + ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing +#endif +}; + +//----------------------------------------------------------------------------- +// ImGuiStyle +// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). +// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, +// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. +//----------------------------------------------------------------------------- + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in ImGui. + ImVec2 WindowPadding; // Padding within a window. + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. + float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. + float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) + float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. + float ScrollbarRounding; // Radius of grab corners for scrollbar. + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. + ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. + ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! + float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. + bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + ImVec4 Colors[ImGuiCol_COUNT]; + + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); +}; + +//----------------------------------------------------------------------------- +// ImGuiIO +// Communicate most settings and inputs/outputs to Dear ImGui using this structure. +// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +//----------------------------------------------------------------------------- + +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Configuration (fill once) // Default value: + //------------------------------------------------------------------ + + ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. + ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end. + ImVec2 DisplaySize; // // Main display size, in pixels. For clamping windows positions. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. + float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file. Set NULL to disable automatic .ini loading/saving, if e.g. you want to manually load/save from memory. + const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. + int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. + float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. + void* UserData; // = NULL // Store your own data for retrieval by callbacks. + + ImFontAtlas* Fonts; // // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + ImVec2 DisplayVisibleMin; // (0.0f,0.0f) // [OBSOLETE] If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. + ImVec2 DisplayVisibleMax; // (0.0f,0.0f) // [OBSOLETE: just use io.DisplaySize!] If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize + + // Miscellaneous configuration options + bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. + bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63) + bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) + bool ConfigResizeWindowsFromEdges; // = false // [BETA] Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the ImGuiWindowFlags_ResizeFromAnySide flag) + + //------------------------------------------------------------------ + // Platform Functions + // (the imgui_impl_xxxx back-end files are setting those up for you) + //------------------------------------------------------------------ + + // Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + const char* BackendPlatformName; + const char* BackendRendererName; + + // Optional: Access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; + + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) + // (default to use native imm32 api on Windows) + void (*ImeSetInputScreenPosFn)(int x, int y); + void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // [OBSOLETE since 1.60+] Rendering function, will be automatically called in Render(). Please call your rendering function yourself now! + // You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Render(). See example applications if you are unsure of how to implement this. + void (*RenderDrawListsFn)(ImDrawData* data); +#else + // This is only here to keep ImGuiIO the same size, so that IMGUI_DISABLE_OBSOLETE_FUNCTIONS can exceptionally be used outside of imconfig.h. + void* RenderDrawListsFnUnused; +#endif + + //------------------------------------------------------------------ + // Input - Fill before calling NewFrame() + //------------------------------------------------------------------ + + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. + float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. + bool KeyCtrl; // Keyboard modifier pressed: Control + bool KeyShift; // Keyboard modifier pressed: Shift + bool KeyAlt; // Keyboard modifier pressed: Alt + bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows + bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). + ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. + float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame, all values will be cleared back to zero in ImGui::EndFrame) + + // Functions + IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[] + IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string + inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually + + //------------------------------------------------------------------ + // Output - Retrieve after calling NewFrame() + //------------------------------------------------------------------ + + bool WantCaptureMouse; // When io.WantCaptureMouse is true, imgui will use the mouse inputs, do not dispatch them to your main game/application (in both cases, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, imgui will use the keyboard inputs, do not dispatch them to your main game/application (in both cases, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). + bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. + bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. IMPORTANT: You need to clear io.WantSaveIniSettings yourself. + bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. + bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events). + float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsRenderWindows; // Number of visible windows + int MetricsActiveWindows; // Number of active windows + int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts. + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. + + //------------------------------------------------------------------ + // [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed! + //------------------------------------------------------------------ + + ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) + ImVec2 MouseClickedPos[5]; // Position at time of clicking + double MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseClicked[5]; // Mouse button went from !Down to Down + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? + bool MouseReleased[5]; // Mouse button went from Down to !Down + bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point + float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) + float KeysDownDurationPrev[512]; // Previous duration the key has been down + float NavInputsDownDuration[ImGuiNavInput_COUNT]; + float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// Misc data structures +//----------------------------------------------------------------------------- + +// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. +// The callback function should return 0 by default. +// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB +// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration +// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. +struct ImGuiInputTextCallbackData +{ + ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + + // Arguments for the different callback events + // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. + // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. + ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] + char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! + int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() + int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 + bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] + int CursorPos; // // Read-write // [Completion,History,Always] + int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) + int SelectionEnd; // // Read-write // [Completion,History,Always] + + // Helper functions for text manipulation. + // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. + IMGUI_API ImGuiInputTextCallbackData(); + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() +struct ImGuiPayload +{ + // Members + void* Data; // Data (copied and owned by dear imgui) + int DataSize; // Data size + + // [Internal] + ImGuiID SourceId; // Source item id + ImGuiID SourceParentId; // Source parent id (if available) + int DataFrameCount; // Data timestamp + char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max) + bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) + bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. + + ImGuiPayload() { Clear(); } + void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } + bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } + bool IsPreview() const { return Preview; } + bool IsDelivery() const { return Delivery; } +}; + +//----------------------------------------------------------------------------- +// Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +namespace ImGui +{ + // OBSOLETED in 1.66 (from Sep 2018) + static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); } + // OBSOLETED in 1.63 (from Aug 2018) + static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } + // OBSOLETED in 1.61 (from Apr 2018) + IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags = 0); // Use the 'const char* format' version instead of 'decimal_precision'! + IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags = 0); + // OBSOLETED in 1.60 (from Dec 2017) + static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } + static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } + static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { (void)on_edge; (void)outward; IM_ASSERT(0); return pos; } + // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + static inline void ShowTestWindow() { return ShowDemoWindow(); } + static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } + static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } + static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } + static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } + // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead. + static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } + static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } + static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); } + // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } + static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead. + static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } + static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } +} +typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETE in 1.63 (from Aug 2018): made the names consistent +typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; +#endif + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +// Helper: Lightweight std::vector<> like class to avoid dragging dependencies (also: Windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). +// *Important* Our implementation does NOT call C++ constructors/destructors. This is intentional, we do not require it but you have to be mindful of that. Do _not_ use this class as a std::vector replacement in your code! +template +class ImVector +{ +public: + int Size; + int Capacity; + T* Data; + + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + inline ImVector() { Size = Capacity = 0; Data = NULL; } + inline ~ImVector() { if (Data) ImGui::MemFree(Data); } + inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } + inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(value_type)); return *this; } + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int capacity() const { return Capacity; } + inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } + inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } + + inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } + inline iterator begin() { return Data; } + inline const_iterator begin() const { return Data; } + inline iterator end() { return Data + Size; } + inline const_iterator end() const { return Data + Size; } + inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void resize(int new_size,const value_type& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } + inline void reserve(int new_capacity) + { + if (new_capacity <= Capacity) + return; + value_type* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); + if (Data) + { + memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); + ImGui::MemFree(Data); + } + Data = new_data; + Capacity = new_capacity; + } + + // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. + inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); } + inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } + inline iterator erase(const_iterator it, const_iterator it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(value_type)); Size -= (int)count; return Data + off; } + inline iterator erase_unsorted(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(value_type)); Size--; return Data + off; } + inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } + inline int index_from_pointer(const_iterator it) const { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; return (int)off; } +}; + +// Helper: IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() macros to call MemAlloc + Placement New, Placement Delete + MemFree +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +struct ImNewDummy {}; +inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symetrical new() +#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) +#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + +// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. +// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete +#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf) +#endif + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + IMGUI_API ImGuiTextFilter(const char* default_filter = ""); + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; + IMGUI_API void Build(); + void Clear() { InputBuf[0] = 0; Build(); } + bool IsActive() const { return !Filters.empty(); } + + // [Internal] + struct TextRange + { + const char* b; + const char* e; + + TextRange() { b = e = NULL; } + TextRange(const char* _b, const char* _e) { b = _b; e = _e; } + const char* begin() const { return b; } + const char* end () const { return e; } + bool empty() const { return b == e; } + IMGUI_API void split(char separator, ImVector* out) const; + }; + char InputBuf[256]; + ImVector Filters; + int CountGrep; +}; + +// Helper: Growable text buffer for logging/accumulating text +// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') +struct ImGuiTextBuffer +{ + ImVector Buf; + static char EmptyString[1]; + + ImGuiTextBuffer() { } + inline char operator[](int i) { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } + const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } + const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Data ? Buf.Size - 1 : 0; } + bool empty() { return Buf.Size <= 1; } + void clear() { Buf.clear(); } + void reserve(int capacity) { Buf.reserve(capacity); } + const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } + IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); + IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); +}; + +// Helper: Key->Value storage +// Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1) +// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) +// You can use it as custom user storage for temporary values. Declare your own storage if, for example: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + struct Pair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + }; + ImVector Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + void Clear() { Data.clear(); } + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); + + // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. + IMGUI_API void BuildSortByKey(); +}; + +// Helper: Manually clip large list of items. +// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. +// Usage: +// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). +// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. +// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. +struct ImGuiListClipper +{ + float StartPosY; + float ItemsHeight; + int ItemsCount, StepNo, DisplayStart, DisplayEnd; + + // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). + // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). + ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). + ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. + + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. +}; + +// Helpers macros to generate 32-bits encoded colors +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } + ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } + ImColor(const ImVec4& col) { Value = col; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } +}; + +//----------------------------------------------------------------------------- +// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// Draw callbacks for advanced uses. +// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +// you can poke into the draw list for that! Draw callback may be useful for example to: A) Change your GPU render state, +// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); + +// Typically, 1 command = 1 GPU draw call (unless command is a callback) +struct ImDrawCmd +{ + unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // The draw callback code can access this. + + ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = (ImTextureID)NULL; UserCallback = NULL; UserCallbackData = NULL; } +}; + +// Vertex index (override with '#define ImDrawIdx unsigned int' in imconfig.h) +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; +#endif + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef) +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. +// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. +struct ImDrawChannel +{ + ImVector CmdBuffer; + ImVector IdxBuffer; +}; + +enum ImDrawCornerFlags_ +{ + ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1 + ImDrawCornerFlags_TopRight = 1 << 1, // 0x2 + ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4 + ImDrawCornerFlags_BotRight = 1 << 3, // 0x8 + ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // 0x3 + ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // 0xC + ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // 0x5 + ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, // 0xA + ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience +}; + +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedFill = 1 << 1 // Filled shapes have anti-aliased edges (*2 the number of vertices) +}; + +// Draw command list +// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well) +// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. +struct ImDrawList +{ + // This is what you have to render + ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. + ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + + // [Internal, used while building lists] + const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) + const char* _OwnerName; // Pointer to owner window's name for debugging + unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureIdStack; // [Internal] + ImVector _Path; // [Internal] current path building + int _ChannelsCurrent; // [Internal] current channel number (0) + int _ChannelsCount; // [Internal] number of active channels (1+) + ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) + + // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) + ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); } + ~ImDrawList() { ClearFreeMemory(); } + IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTextureID(ImTextureID texture_id); + IMGUI_API void PopTextureID(); + inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } + inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } + + // Primitives + IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right + IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All); + IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. + IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); + + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() + inline void PathClear() { _Path.resize(0); } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); } // Note: Anti-aliased filling requires points to be in clockwise order. + inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); PathClear(); } + IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); + IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); + + // Channels + // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) + IMGUI_API void ChannelsSplit(int channels_count); + IMGUI_API void ChannelsMerge(); + IMGUI_API void ChannelsSetCurrent(int channel_index); + + // Advanced + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. + + // Internal helpers + // NB: all primitives needs to be reserved via PrimReserve() beforehand! + IMGUI_API void Clear(); + IMGUI_API void ClearFreeMemory(); + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } + IMGUI_API void UpdateClipRect(); + IMGUI_API void UpdateTextureID(); +}; + +// All draw data to render an ImGui frame +// (NB: the style and the naming convention here is a little inconsistent but we preserve them for backward compatibility purpose) +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here. + int CmdListsCount; // Number of ImDrawList* to render + int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size + int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size + ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use) + ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use) + + // Functions + ImDrawData() { Valid = false; Clear(); } + ~ImDrawData() { Clear(); } + void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext! + IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +//----------------------------------------------------------------------------- +// Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFont) +//----------------------------------------------------------------------------- + +struct ImFontConfig +{ + void* FontData; // // TTF/OTF data + int FontDataSize; // // TTF/OTF data size + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + int FontNo; // 0 // Index of font within TTF/OTF file + float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. + const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one. + float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. + + // [Internal] + char Name[40]; // Name (strictly to ease debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); +}; + +struct ImFontGlyph +{ + ImWchar Codepoint; // 0x0000..0xFFFF + float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) + float X0, Y0, X1, Y1; // Glyph corners + float U0, V0, U1, V1; // Texture coordinates +}; + +enum ImFontAtlasFlags_ +{ + ImFontAtlasFlags_None = 0, + ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two + ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas +}; + +// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +// - One or more fonts. +// - Custom graphics data needed to render the shapes needed by Dear ImGui. +// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). +// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. +// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. +// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) +// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. +// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. +// Common pitfalls: +// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the +// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. +// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. +// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, +// - Even though many functions are suffixed with "TTF", OTF data is supported just as well. +// - This is an old API and it is currently awkward for those and and various other reasons! We will address them in the future! +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. + IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates). + IMGUI_API void Clear(); // Clear all input and output. + + // Build atlas, retrieve pixel data. + // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // The pitch is always = Width * BytesPerPixels (1 or 4) + // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API bool IsBuilt() { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); } + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(ImTextureID id) { TexID = id; } + + //------------------------------------------- + // Glyph Ranges + //------------------------------------------- + + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details. + // NB: Consider using GlyphRangesBuilder to build glyph ranges from textual data. + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + + // Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges(). + struct GlyphRangesBuilder + { + ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) + GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); } + bool GetBit(int n) const { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; } + void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array + void AddChar(ImWchar c) { SetBit(c); } // Add character + IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext + IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges + }; + + //------------------------------------------- + // Custom Rectangles/Glyphs API + //------------------------------------------- + + // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels. + // You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. + struct CustomRect + { + unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. + unsigned short Width, Height; // Input // Desired rectangle dimension + unsigned short X, Y; // Output // Packed position in Atlas + float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance + ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset + ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font + CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } + }; + + IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font. + const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } + + // [Internal] + IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); + IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + + //------------------------------------------- + // Members + //------------------------------------------- + + bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. + ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) + ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. + + // [Internal] + // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. + unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight + unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. + ImVector ConfigData; // Internal data + int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList +}; + +// Font runtime data and rendering +// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). +struct ImFont +{ + // Members: Hot ~62/78 bytes + float FontSize; // // Height of characters, set during loading (don't change after loading) + float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() + ImVec2 DisplayOffset; // = (0.f,0.f) // Offset font rendering by xx pixels + ImVector Glyphs; // // All glyphs. + ImVector IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point. + const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) + float FallbackAdvanceX; // == FallbackGlyph->AdvanceX + ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + + // Members: Cold ~18/26 bytes + short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData + ImFontAtlas* ContainerAtlas; // // What we has been loaded into + float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + bool DirtyLookupTables; + int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API void ClearOutputData(); + IMGUI_API void BuildLookupTable(); + IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; + IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const; + IMGUI_API void SetFallbackChar(ImWchar c); + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // [Internal] + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + typedef ImFontGlyph Glyph; // OBSOLETE 1.52+ +#endif +}; + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) && __GNUC__ >= 8 +#pragma GCC diagnostic pop +#endif + +// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif diff --git a/src/3rdparty/imgui/imgui.pri b/src/3rdparty/imgui/imgui.pri new file mode 100644 index 000000000..2e7c546d7 --- /dev/null +++ b/src/3rdparty/imgui/imgui.pri @@ -0,0 +1,9 @@ +INCLUDEPATH += $$PWD + +SOURCES += \ + $$PWD/imgui_draw.cpp \ + $$PWD/imgui.cpp \ + $$PWD/imgui_widgets.cpp + +HEADERS += \ + $$PWD/imgui.h diff --git a/src/3rdparty/imgui/imgui_draw.cpp b/src/3rdparty/imgui/imgui_draw.cpp new file mode 100644 index 000000000..2e77d00fc --- /dev/null +++ b/src/3rdparty/imgui/imgui_draw.cpp @@ -0,0 +1,3156 @@ +// dear imgui, v1.66b +// (drawing and font code) + +/* + +Index of this file: + +// [SECTION] STB libraries implementation +// [SECTION] Style functions +// [SECTION] ImDrawList +// [SECTION] ImDrawData +// [SECTION] Helpers ShadeVertsXXX functions +// [SECTION] ImFontConfig +// [SECTION] ImFontAtlas +// [SECTION] ImFontAtlas glyph ranges helpers + GlyphRangesBuilder +// [SECTION] ImFont +// [SECTION] Internal Render Helpers +// [SECTION] Decompression code +// [SECTION] Default font data (ProggyClean.ttf) + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +#include // vsnprintf, sscanf, printf +#if !defined(alloca) +#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) +#include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here) +#elif defined(_WIN32) +#include // alloca +#if !defined(alloca) +#define alloca _alloca // for clang with MS Codegen +#endif +#else +#include // alloca +#endif +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#endif + +// Clang/GCC warnings with -Weverything +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#if __has_warning("-Wcomma") +#pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here // +#endif +#if __has_warning("-Wreserved-id-macro") +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#endif +#if __has_warning("-Wdouble-promotion") +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#if __GNUC__ >= 8 +#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif +#endif + +//------------------------------------------------------------------------- +// [SECTION] STB libraries implementation +//------------------------------------------------------------------------- + +// Compile time options: +//#define IMGUI_STB_NAMESPACE ImGuiStb +//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#pragma clang diagnostic ignored "-Wimplicit-fallthrough" +#pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier // +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#endif + +#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +#define STBRP_STATIC +#define STBRP_ASSERT(x) IM_ASSERT(x) +#define STBRP_SORT ImQsort +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#ifdef IMGUI_STB_RECT_PACK_FILENAME +#include IMGUI_STB_RECT_PACK_FILENAME +#else +#include "imstb_rectpack.h" +#endif +#endif + +#ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) +#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_assert(x) IM_ASSERT(x) +#define STBTT_fmod(x,y) ImFmod(x,y) +#define STBTT_sqrt(x) ImSqrt(x) +#define STBTT_pow(x,y) ImPow(x,y) +#define STBTT_fabs(x) ImFabs(x) +#define STBTT_ifloor(x) ((int)ImFloorStd(x)) +#define STBTT_iceil(x) ((int)ImCeil(x)) +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#ifdef IMGUI_STB_TRUETYPE_FILENAME +#include IMGUI_STB_TRUETYPE_FILENAME +#else +#include "imstb_truetype.h" +#endif +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImGuiStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Style functions +//----------------------------------------------------------------------------- + +void ImGui::StyleColorsDark(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); + colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = colors[ImGuiCol_Border]; + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); +} + +void ImGui::StyleColorsClassic(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); + colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f); + colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); + colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); + colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); + colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); + colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +// Those light colors are better suited with a thicker font than the default one + FrameBorder +void ImGui::StyleColorsLight(ImGuiStyle* dst) +{ + ImGuiStyle* style = dst ? dst : &ImGui::GetStyle(); + ImVec4* colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); + colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +//----------------------------------------------------------------------------- +// ImDrawList +//----------------------------------------------------------------------------- + +ImDrawListSharedData::ImDrawListSharedData() +{ + Font = NULL; + FontSize = 0.0f; + CurveTessellationTol = 0.0f; + ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f); + + // Const data + for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++) + { + const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(CircleVtx12); + CircleVtx12[i] = ImVec2(ImCos(a), ImSin(a)); + } +} + +void ImDrawList::Clear() +{ + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + Flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill; + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureIdStack.resize(0); + _Path.resize(0); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + // NB: Do not clear channels so our allocations are re-used after the first frame. +} + +void ImDrawList::ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureIdStack.clear(); + _Path.clear(); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + for (int i = 0; i < _Channels.Size; i++) + { + if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i].CmdBuffer.clear(); + _Channels[i].IdxBuffer.clear(); + } + _Channels.clear(); +} + +ImDrawList* ImDrawList::CloneOutput() const +{ + ImDrawList* dst = IM_NEW(ImDrawList(NULL)); + dst->CmdBuffer = CmdBuffer; + dst->IdxBuffer = IdxBuffer; + dst->VtxBuffer = VtxBuffer; + dst->Flags = Flags; + return dst; +} + +// Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds +#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen) +#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL) + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = GetCurrentClipRect(); + draw_cmd.TextureId = GetCurrentTextureId(); + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) +{ + ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + { + AddDrawCmd(); + current_cmd = &CmdBuffer.back(); + } + current_cmd->UserCallback = callback; + current_cmd->UserCallbackData = callback_data; + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::UpdateClipRect() +{ + // If current command is used with different settings we need to add a new command + const ImVec4 curr_clip_rect = GetCurrentClipRect(); + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->ClipRect = curr_clip_rect; +} + +void ImDrawList::UpdateTextureID() +{ + // If current command is used with different settings we need to add a new command + const ImTextureID curr_texture_id = GetCurrentTextureId(); + ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->TextureId = curr_texture_id; +} + +#undef GetCurrentClipRect +#undef GetCurrentTextureId + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect && _ClipRectStack.Size) + { + ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + if (cr.x < current.x) cr.x = current.x; + if (cr.y < current.y) cr.y = current.y; + if (cr.z > current.z) cr.z = current.z; + if (cr.w > current.w) cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + UpdateClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w)); +} + +void ImDrawList::PopClipRect() +{ + IM_ASSERT(_ClipRectStack.Size > 0); + _ClipRectStack.pop_back(); + UpdateClipRect(); +} + +void ImDrawList::PushTextureID(ImTextureID texture_id) +{ + _TextureIdStack.push_back(texture_id); + UpdateTextureID(); +} + +void ImDrawList::PopTextureID() +{ + IM_ASSERT(_TextureIdStack.Size > 0); + _TextureIdStack.pop_back(); + UpdateTextureID(); +} + +void ImDrawList::ChannelsSplit(int channels_count) +{ + IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + _Channels.resize(channels_count); + _ChannelsCount = channels_count; + + // _Channels[] (24/32 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer + // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i].CmdBuffer.resize(0); + _Channels[i].IdxBuffer.resize(0); + } + if (_Channels[i].CmdBuffer.Size == 0) + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _ClipRectStack.back(); + draw_cmd.TextureId = _TextureIdStack.back(); + _Channels[i].CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawList::ChannelsMerge() +{ + // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_ChannelsCount <= 1) + return; + + ChannelsSetCurrent(0); + if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) + CmdBuffer.pop_back(); + + int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + ch.CmdBuffer.pop_back(); + new_cmd_buffer_count += ch.CmdBuffer.Size; + new_idx_buffer_count += ch.IdxBuffer.Size; + } + CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); + IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); + + ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } + } + UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. + _ChannelsCount = 1; +} + +void ImDrawList::ChannelsSetCurrent(int idx) +{ + IM_ASSERT(idx < _ChannelsCount); + if (_ChannelsCurrent == idx) return; + memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times + memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); + _ChannelsCurrent = idx; + memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); + memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; +} + +// NB: this can be called with negative count for removing primitives (as long as the result does not underflow) +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; + draw_cmd.ElemCount += idx_count; + + int vtx_buffer_old_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_old_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; + + int idx_buffer_old_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_old_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness) +{ + if (points_count < 2) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + + int count = points_count; + if (!closed) + count = points_count-1; + + const bool thick_line = thickness > 1.0f; + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + // Anti-aliased stroke + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + + const int idx_count = thick_line ? count*18 : count*12; + const int vtx_count = thick_line ? points_count*4 : points_count*3; + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); + ImVec2* temp_points = temp_normals + points_count; + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + ImVec2 diff = points[i2] - points[i1]; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i1].x = diff.y; + temp_normals[i1].y = -diff.x; + } + if (!closed) + temp_normals[points_count-1] = temp_normals[points_count-2]; + + if (!thick_line) + { + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; + temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE; + temp_points[i2*2+0] = points[i2] + dm; + temp_points[i2*2+1] = points[i2] - dm; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); + _IdxWritePtr += 12; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr += 3; + } + } + else + { + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE); + ImVec2 dm_in = dm * half_inner_thickness; + temp_points[i2*4+0] = points[i2] + dm_out; + temp_points[i2*4+1] = points[i2] + dm_in; + temp_points[i2*4+2] = points[i2] - dm_in; + temp_points[i2*4+3] = points[i2] - dm_out; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Stroke + const int idx_count = count*6; + const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + ImVec2 diff = p2 - p1; + diff *= ImInvLength(diff, 1.0f); + + const float dx = diff.x * (thickness * 0.5f); + const float dy = diff.y * (thickness * 0.5f); + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col) +{ + if (points_count < 3) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + + if (Flags & ImDrawListFlags_AntiAliasedFill) + { + // Anti-aliased Fill + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + const int idx_count = (points_count-2)*3 + points_count*6; + const int vtx_count = (points_count*2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr += 3; + } + + // Compute normals + ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + ImVec2 diff = p1 - p0; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i0].x = diff.y; + temp_normals[i0].y = -diff.x; + } + + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + ImVec2 dm = (n0 + n1) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos = (points[i1] - dm); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos = (points[i1] + dm); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count-2)*3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12) +{ + if (radius == 0.0f || a_min_of_12 > a_max_of_12) + { + _Path.push_back(centre); + return; + } + _Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1)); + for (int a = a_min_of_12; a <= a_max_of_12; a++) + { + const ImVec2& c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)]; + _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); + } +} + +void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments) +{ + if (radius == 0.0f) + { + _Path.push_back(centre); + return; + } + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); + _Path.push_back(ImVec2(centre.x + ImCos(a) * radius, centre.y + ImSin(a) * radius)); + } +} + +static void PathBezierToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; + float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; + float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; + float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; + float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; + float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + + PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); + PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + } +} + +void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + // Auto-tessellated + PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + float t = t_step * i_step; + float u = 1.0f - t; + float w1 = u*u*u; + float w2 = 3*u*u*t; + float w3 = 3*u*t*t; + float w4 = t*t*t; + _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); + } + } +} + +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) +{ + rounding = ImMin(rounding, ImFabs(b.x - a.x) * ( ((rounding_corners & ImDrawCornerFlags_Top) == ImDrawCornerFlags_Top) || ((rounding_corners & ImDrawCornerFlags_Bot) == ImDrawCornerFlags_Bot) ? 0.5f : 1.0f ) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.y - a.y) * ( ((rounding_corners & ImDrawCornerFlags_Left) == ImDrawCornerFlags_Left) || ((rounding_corners & ImDrawCornerFlags_Right) == ImDrawCornerFlags_Right) ? 0.5f : 1.0f ) - 1.0f); + + if (rounding <= 0.0f || rounding_corners == 0) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x, a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x, b.y)); + } + else + { + const float rounding_tl = (rounding_corners & ImDrawCornerFlags_TopLeft) ? rounding : 0.0f; + const float rounding_tr = (rounding_corners & ImDrawCornerFlags_TopRight) ? rounding : 0.0f; + const float rounding_br = (rounding_corners & ImDrawCornerFlags_BotRight) ? rounding : 0.0f; + const float rounding_bl = (rounding_corners & ImDrawCornerFlags_BotLeft) ? rounding : 0.0f; + PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); + PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); + PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); + PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathLineTo(a + ImVec2(0.5f,0.5f)); + PathLineTo(b + ImVec2(0.5f,0.5f)); + PathStroke(col, false, thickness); +} + +// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (Flags & ImDrawListFlags_AntiAliasedLines) + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.50f,0.50f), rounding, rounding_corners_flags); + else + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.49f,0.49f), rounding, rounding_corners_flags); // Better looking lower-right corner and rounded non-AA shapes. + PathStroke(col, true, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (rounding > 0.0f) + { + PathRect(a, b, rounding, rounding_corners_flags); + PathFillConvex(col); + } + else + { + PrimReserve(6, 4); + PrimRect(a, b, col); + } +} + +void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); + PrimWriteVtx(a, uv, col_upr_left); + PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); + PrimWriteVtx(c, uv, col_bot_right); + PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathFillConvex(col); +} + +void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathFillConvex(col); +} + +void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius-0.5f, 0.0f, a_max, num_segments); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius, 0.0f, a_max, num_segments); + PathFillConvex(col); +} + +void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(pos0); + PathBezierCurveTo(cp0, cp1, pos1, num_segments); + PathStroke(col, false, thickness); +} + +void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); + if (text_begin == text_end) + return; + + // Pull default font/size from the shared ImDrawListSharedData instance + if (font == NULL) + font = _Data->Font; + if (font_size == 0.0f) + font_size = _Data->FontSize; + + IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + + ImVec4 clip_rect = _ClipRectStack.back(); + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); +} + +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +{ + AddText(NULL, 0.0f, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimRectUV(a, b, uv_a, uv_b, col); + + if (push_texture_id) + PopTextureID(); +} + +void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); + + if (push_texture_id) + PopTextureID(); +} + +void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (rounding <= 0.0f || (rounding_corners & ImDrawCornerFlags_All) == 0) + { + AddImage(user_texture_id, a, b, uv_a, uv_b, col); + return; + } + + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + int vert_start_idx = VtxBuffer.Size; + PathRect(a, b, rounding, rounding_corners); + PathFillConvex(col); + int vert_end_idx = VtxBuffer.Size; + ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, a, b, uv_a, uv_b, true); + + if (push_texture_id) + PopTextureID(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawData +//----------------------------------------------------------------------------- + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + if (cmd_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); + for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; + cmd_list->VtxBuffer.swap(new_vtx_buffer); + cmd_list->IdxBuffer.resize(0); + TotalVtxCount += cmd_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& scale) +{ + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; + cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Helpers ShadeVertsXXX functions +//----------------------------------------------------------------------------- + +// Generic linear color gradient, write to RGB fields, leave A untouched. +void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) +{ + ImVec2 gradient_extent = gradient_p1 - gradient_p0; + float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); + ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) + { + float d = ImDot(vert->pos - gradient_p0, gradient_extent); + float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); + int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t); + int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t); + int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t); + vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); + } +} + +// Distribute UV over (a, b) rectangle +void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp) +{ + const ImVec2 size = b - a; + const ImVec2 uv_size = uv_b - uv_a; + const ImVec2 scale = ImVec2( + size.x != 0.0f ? (uv_size.x / size.x) : 0.0f, + size.y != 0.0f ? (uv_size.y / size.y) : 0.0f); + + ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + if (clamp) + { + const ImVec2 min = ImMin(uv_a, uv_b); + const ImVec2 max = ImMax(uv_a, uv_b); + for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) + vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max); + } + else + { + for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex) + vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontConfig +//----------------------------------------------------------------------------- + +ImFontConfig::ImFontConfig() +{ + FontData = NULL; + FontDataSize = 0; + FontDataOwnedByAtlas = true; + FontNo = 0; + SizePixels = 0.0f; + OversampleH = 3; + OversampleV = 1; + PixelSnapH = false; + GlyphExtraSpacing = ImVec2(0.0f, 0.0f); + GlyphOffset = ImVec2(0.0f, 0.0f); + GlyphRanges = NULL; + GlyphMinAdvanceX = 0.0f; + GlyphMaxAdvanceX = FLT_MAX; + MergeMode = false; + RasterizerFlags = 0x00; + RasterizerMultiply = 1.0f; + memset(Name, 0, sizeof(Name)); + DstFont = NULL; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas +//----------------------------------------------------------------------------- + +// A work of art lies ahead! (. = white layer, X = black layer, others are blank) +// The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. +const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 108; +const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; +const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000; +static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = +{ + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX " + "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X " + "--- -XXX.XXX- X...X - X...X -X....X - X....X- X..X " + "X - X.X - X.....X - X.....X -X...X - X...X- X..X " + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X- X..X " + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X- X..XXX " + "X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX " + "X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..X..X..XX " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X - X..X..X..X.X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X -XXX X..X..X..X..X" + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X -X..XX........X..X" + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X -X...X...........X" + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X - X..............X" + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X - X.............X" + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X - X.............X" + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X - X............X" + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX - X...........X " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X " + "X.X X..X - -X.......X- X.......X - XX XX - - X..........X " + "XX X..X - - X.....X - X.....X - X.X X.X - - X........X " + " X..X - X...X - X...X - X..X X..X - - X........X " + " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX " + "------------ - X - X -X.....................X- ------------------" + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - " +}; + +static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] = +{ + // Pos ........ Size ......... Offset ...... + { ImVec2( 0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow + { ImVec2(13,0), ImVec2( 7,16), ImVec2( 1, 8) }, // ImGuiMouseCursor_TextInput + { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_ResizeAll + { ImVec2(21,0), ImVec2( 9,23), ImVec2( 4,11) }, // ImGuiMouseCursor_ResizeNS + { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 4) }, // ImGuiMouseCursor_ResizeEW + { ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW + { ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE + { ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand +}; + +ImFontAtlas::ImFontAtlas() +{ + Locked = false; + Flags = ImFontAtlasFlags_None; + TexID = (ImTextureID)NULL; + TexDesiredWidth = 0; + TexGlyphPadding = 1; + + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; + TexWidth = TexHeight = 0; + TexUvScale = ImVec2(0.0f, 0.0f); + TexUvWhitePixel = ImVec2(0.0f, 0.0f); + for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) + CustomRectIds[n] = -1; +} + +ImFontAtlas::~ImFontAtlas() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + Clear(); +} + +void ImFontAtlas::ClearInputData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + for (int i = 0; i < ConfigData.Size; i++) + if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) + { + ImGui::MemFree(ConfigData[i].FontData); + ConfigData[i].FontData = NULL; + } + + // When clearing this we lose access to the font name and other information used to build the font. + for (int i = 0; i < Fonts.Size; i++) + if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) + { + Fonts[i]->ConfigData = NULL; + Fonts[i]->ConfigDataCount = 0; + } + ConfigData.clear(); + CustomRects.clear(); + for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) + CustomRectIds[n] = -1; +} + +void ImFontAtlas::ClearTexData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + if (TexPixelsAlpha8) + ImGui::MemFree(TexPixelsAlpha8); + if (TexPixelsRGBA32) + ImGui::MemFree(TexPixelsRGBA32); + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; +} + +void ImFontAtlas::ClearFonts() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + for (int i = 0; i < Fonts.Size; i++) + IM_DELETE(Fonts[i]); + Fonts.clear(); +} + +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Build atlas on demand + if (TexPixelsAlpha8 == NULL) + { + if (ConfigData.empty()) + AddFontDefault(); + Build(); + } + + *out_pixels = TexPixelsAlpha8; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Convert to RGBA32 format on demand + // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp + if (!TexPixelsRGBA32) + { + unsigned char* pixels = NULL; + GetTexDataAsAlpha8(&pixels, NULL, NULL); + if (pixels) + { + TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); + const unsigned char* src = pixels; + unsigned int* dst = TexPixelsRGBA32; + for (int n = TexWidth * TexHeight; n > 0; n--) + *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); + } + } + + *out_pixels = (unsigned char*)TexPixelsRGBA32; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; +} + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT(font_cfg->SizePixels > 0.0f); + + // Create new font + if (!font_cfg->MergeMode) + Fonts.push_back(IM_NEW(ImFont)); + else + IM_ASSERT(!Fonts.empty()); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. + + ConfigData.push_back(*font_cfg); + ImFontConfig& new_font_cfg = ConfigData.back(); + if (!new_font_cfg.DstFont) + new_font_cfg.DstFont = Fonts.back(); + if (!new_font_cfg.FontDataOwnedByAtlas) + { + new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontDataOwnedByAtlas = true; + memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + } + + // Invalidate texture + ClearTexData(); + return new_font_cfg.DstFont; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(const unsigned char *input); +static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length); +static const char* GetDefaultCompressedFontDataTTFBase85(); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } +static void Decode85(const unsigned char* src, unsigned char* dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. + src += 5; + dst += 4; + } +} + +// Load embedded ProggyClean.ttf at size 13, disable oversampling +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "ProggyClean.ttf, 13px"); + if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f; + + const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); + const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); + ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges); + font->DisplayOffset.y = 1.0f; + return font; +} + +ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + size_t data_size = 0; + void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); + if (!data) + { + IM_ASSERT(0); // Could not load file. + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char* p; + for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); + } + return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontData = ttf_data; + font_cfg.FontDataSize = ttf_size; + font_cfg.SizePixels = size_pixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); + unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +{ + int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + ImGui::MemFree(compressed_ttf); + return font; +} + +int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) +{ + IM_ASSERT(id >= 0x10000); + IM_ASSERT(width > 0 && width <= 0xFFFF); + IM_ASSERT(height > 0 && height <= 0xFFFF); + CustomRect r; + r.ID = id; + r.Width = (unsigned short)width; + r.Height = (unsigned short)height; + CustomRects.push_back(r); + return CustomRects.Size - 1; // Return index +} + +int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) +{ + IM_ASSERT(font != NULL); + IM_ASSERT(width > 0 && width <= 0xFFFF); + IM_ASSERT(height > 0 && height <= 0xFFFF); + CustomRect r; + r.ID = id; + r.Width = (unsigned short)width; + r.Height = (unsigned short)height; + r.GlyphAdvanceX = advance_x; + r.GlyphOffset = offset; + r.Font = font; + CustomRects.push_back(r); + return CustomRects.Size - 1; // Return index +} + +void ImFontAtlas::CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) +{ + IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates + IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed + *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); + *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); +} + +bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) +{ + if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT) + return false; + if (Flags & ImFontAtlasFlags_NoMouseCursors) + return false; + + IM_ASSERT(CustomRectIds[0] != -1); + ImFontAtlas::CustomRect& r = CustomRects[CustomRectIds[0]]; + IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); + ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); + ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; + *out_size = size; + *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; + out_uv_border[0] = (pos) * TexUvScale; + out_uv_border[1] = (pos + size) * TexUvScale; + pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; + out_uv_fill[0] = (pos) * TexUvScale; + out_uv_fill[1] = (pos + size) * TexUvScale; + return true; +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + return ImFontAtlasBuildWithStbTruetype(this); +} + +void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) +{ + for (unsigned int i = 0; i < 256; i++) + { + unsigned int value = (unsigned int)(i * in_brighten_factor); + out_table[i] = value > 255 ? 255 : (value & 0xFF); + } +} + +void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride) +{ + unsigned char* data = pixels + x + y * stride; + for (int j = h; j > 0; j--, data += stride) + for (int i = 0; i < w; i++) + data[i] = table[data[i]]; +} + +bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) +{ + IM_ASSERT(atlas->ConfigData.Size > 0); + + ImFontAtlasBuildRegisterDefaultCustomRects(atlas); + + atlas->TexID = (ImTextureID)NULL; + atlas->TexWidth = atlas->TexHeight = 0; + atlas->TexUvScale = ImVec2(0.0f, 0.0f); + atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); + atlas->ClearTexData(); + + // Count glyphs/ranges + int total_glyphs_count = 0; + int total_ranges_count = 0; + for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) + { + ImFontConfig& cfg = atlas->ConfigData[input_i]; + if (!cfg.GlyphRanges) + cfg.GlyphRanges = atlas->GetGlyphRangesDefault(); + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, total_ranges_count++) + total_glyphs_count += (in_range[1] - in_range[0]) + 1; + } + + // We need a width for the skyline algorithm. Using a dumb heuristic here to decide of width. User can override TexDesiredWidth and TexGlyphPadding if they wish. + // Width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. + atlas->TexWidth = (atlas->TexDesiredWidth > 0) ? atlas->TexDesiredWidth : (total_glyphs_count > 4000) ? 4096 : (total_glyphs_count > 2000) ? 2048 : (total_glyphs_count > 1000) ? 1024 : 512; + atlas->TexHeight = 0; + + // Start packing + const int max_tex_height = 1024*32; + stbtt_pack_context spc = {}; + if (!stbtt_PackBegin(&spc, NULL, atlas->TexWidth, max_tex_height, 0, atlas->TexGlyphPadding, NULL)) + return false; + stbtt_PackSetOversampling(&spc, 1, 1); + + // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). + ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info); + + // Initialize font information (so we can error without any cleanup) + struct ImFontTempBuildData + { + stbtt_fontinfo FontInfo; + stbrp_rect* Rects; + int RectsCount; + stbtt_pack_range* Ranges; + int RangesCount; + }; + ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)atlas->ConfigData.Size * sizeof(ImFontTempBuildData)); + for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) + { + ImFontConfig& cfg = atlas->ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas)); + + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); + IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); + if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) + { + atlas->TexWidth = atlas->TexHeight = 0; // Reset output on failure + ImGui::MemFree(tmp_array); + return false; + } + } + + // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) + int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; + stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyphs_count * sizeof(stbtt_packedchar)); + stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyphs_count * sizeof(stbrp_rect)); + stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_ranges_count * sizeof(stbtt_pack_range)); + memset(buf_packedchars, 0, total_glyphs_count * sizeof(stbtt_packedchar)); + memset(buf_rects, 0, total_glyphs_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. + memset(buf_ranges, 0, total_ranges_count * sizeof(stbtt_pack_range)); + + // First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point) + for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) + { + ImFontConfig& cfg = atlas->ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + // Setup ranges + int font_glyphs_count = 0; + int font_ranges_count = 0; + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, font_ranges_count++) + font_glyphs_count += (in_range[1] - in_range[0]) + 1; + tmp.Ranges = buf_ranges + buf_ranges_n; + tmp.RangesCount = font_ranges_count; + buf_ranges_n += font_ranges_count; + for (int i = 0; i < font_ranges_count; i++) + { + const ImWchar* in_range = &cfg.GlyphRanges[i * 2]; + stbtt_pack_range& range = tmp.Ranges[i]; + range.font_size = cfg.SizePixels; + range.first_unicode_codepoint_in_range = in_range[0]; + range.num_chars = (in_range[1] - in_range[0]) + 1; + range.chardata_for_range = buf_packedchars + buf_packedchars_n; + buf_packedchars_n += range.num_chars; + } + + // Gather the sizes of all rectangle we need + tmp.Rects = buf_rects + buf_rects_n; + tmp.RectsCount = font_glyphs_count; + buf_rects_n += font_glyphs_count; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + IM_ASSERT(n == font_glyphs_count); + + // Detect missing glyphs and replace them with a zero-sized box instead of relying on the default glyphs + // This allows us merging overlapping icon fonts more easily. + int rect_i = 0; + for (int range_i = 0; range_i < tmp.RangesCount; range_i++) + for (int char_i = 0; char_i < tmp.Ranges[range_i].num_chars; char_i++, rect_i++) + if (stbtt_FindGlyphIndex(&tmp.FontInfo, tmp.Ranges[range_i].first_unicode_codepoint_in_range + char_i) == 0) + tmp.Rects[rect_i].w = tmp.Rects[rect_i].h = 0; + + // Pack + stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n); + + // Extend texture height + // Also mark missing glyphs as non-packed so we don't attempt to render into them + for (int i = 0; i < n; i++) + { + if (tmp.Rects[i].w == 0 && tmp.Rects[i].h == 0) + tmp.Rects[i].was_packed = 0; + if (tmp.Rects[i].was_packed) + atlas->TexHeight = ImMax(atlas->TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); + } + } + IM_ASSERT(buf_rects_n == total_glyphs_count); + IM_ASSERT(buf_packedchars_n == total_glyphs_count); + IM_ASSERT(buf_ranges_n == total_ranges_count); + + // Create texture + atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); + atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); + atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight); + memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); + spc.pixels = atlas->TexPixelsAlpha8; + spc.height = atlas->TexHeight; + + // Second pass: render font characters + for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) + { + ImFontConfig& cfg = atlas->ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + if (cfg.RasterizerMultiply != 1.0f) + { + unsigned char multiply_table[256]; + ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply); + for (const stbrp_rect* r = tmp.Rects; r != tmp.Rects + tmp.RectsCount; r++) + if (r->was_packed) + ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, spc.pixels, r->x, r->y, r->w, r->h, spc.stride_in_bytes); + } + tmp.Rects = NULL; + } + + // End packing + stbtt_PackEnd(&spc); + ImGui::MemFree(buf_rects); + buf_rects = NULL; + + // Third pass: setup ImFont and glyphs for runtime + for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++) + { + ImFontConfig& cfg = atlas->ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + if (cfg.MergeMode) + dst_font->BuildLookupTable(); + + const float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels); + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1)); + const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1)); + ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); + const float font_off_x = cfg.GlyphOffset.x; + const float font_off_y = cfg.GlyphOffset.y + (float)(int)(dst_font->Ascent + 0.5f); + + for (int i = 0; i < tmp.RangesCount; i++) + { + stbtt_pack_range& range = tmp.Ranges[i]; + for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) + { + const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; + if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) + continue; + + const int codepoint = range.first_unicode_codepoint_in_range + char_idx; + if (cfg.MergeMode && dst_font->FindGlyphNoFallback((ImWchar)codepoint)) + continue; + + float char_advance_x_org = pc.xadvance; + float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX); + float char_off_x = font_off_x; + if (char_advance_x_org != char_advance_x_mod) + char_off_x += cfg.PixelSnapH ? (float)(int)((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f; + + stbtt_aligned_quad q; + float dummy_x = 0.0f, dummy_y = 0.0f; + stbtt_GetPackedQuad(range.chardata_for_range, atlas->TexWidth, atlas->TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); + dst_font->AddGlyph((ImWchar)codepoint, q.x0 + char_off_x, q.y0 + font_off_y, q.x1 + char_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, char_advance_x_mod); + } + } + } + + // Cleanup temporaries + ImGui::MemFree(buf_packedchars); + ImGui::MemFree(buf_ranges); + ImGui::MemFree(tmp_array); + + ImFontAtlasBuildFinish(atlas); + + return true; +} + +void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas) +{ + if (atlas->CustomRectIds[0] >= 0) + return; + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + else + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2); +} + +void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) +{ + if (!font_config->MergeMode) + { + font->ClearOutputData(); + font->FontSize = font_config->SizePixels; + font->ConfigData = font_config; + font->ContainerAtlas = atlas; + font->Ascent = ascent; + font->Descent = descent; + } + font->ConfigDataCount++; +} + +void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* pack_context_opaque) +{ + stbrp_context* pack_context = (stbrp_context*)pack_context_opaque; + + ImVector& user_rects = atlas->CustomRects; + IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. + + ImVector pack_rects; + pack_rects.resize(user_rects.Size); + memset(pack_rects.Data, 0, sizeof(stbrp_rect) * user_rects.Size); + for (int i = 0; i < user_rects.Size; i++) + { + pack_rects[i].w = user_rects[i].Width; + pack_rects[i].h = user_rects[i].Height; + } + stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size); + for (int i = 0; i < pack_rects.Size; i++) + if (pack_rects[i].was_packed) + { + user_rects[i].X = pack_rects[i].x; + user_rects[i].Y = pack_rects[i].y; + IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height); + atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h); + } +} + +static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) +{ + IM_ASSERT(atlas->CustomRectIds[0] >= 0); + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); + ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; + IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); + IM_ASSERT(r.IsPacked()); + + const int w = atlas->TexWidth; + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + { + // Render/copy pixels + IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); + for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) + for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) + { + const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * w; + const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; + atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; + atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; + } + } + else + { + IM_ASSERT(r.Width == 2 && r.Height == 2); + const int offset = (int)(r.X) + (int)(r.Y) * w; + atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; + } + atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y); +} + +void ImFontAtlasBuildFinish(ImFontAtlas* atlas) +{ + // Render into our custom data block + ImFontAtlasBuildRenderDefaultTexData(atlas); + + // Register custom rectangle glyphs + for (int i = 0; i < atlas->CustomRects.Size; i++) + { + const ImFontAtlas::CustomRect& r = atlas->CustomRects[i]; + if (r.Font == NULL || r.ID > 0x10000) + continue; + + IM_ASSERT(r.Font->ContainerAtlas == atlas); + ImVec2 uv0, uv1; + atlas->CalcCustomRectUV(&r, &uv0, &uv1); + r.Font->AddGlyph((ImWchar)r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX); + } + + // Build all fonts lookup tables + for (int i = 0; i < atlas->Fonts.Size; i++) + if (atlas->Fonts[i]->DirtyLookupTables) + atlas->Fonts[i]->BuildLookupTable(); +} + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar* ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3131, 0x3163, // Korean alphabets + 0xAC00, 0xD79D, // Korean characters + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChineseFull() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0x4e00, 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short* accumulative_offsets, int accumulative_offsets_count, ImWchar* out_ranges) +{ + for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2) + { + out_ranges[0] = out_ranges[1] = (ImWchar)(base_codepoint + accumulative_offsets[n]); + base_codepoint += accumulative_offsets[n]; + } + out_ranges[0] = 0; +} + +//------------------------------------------------------------------------- +// [SECTION] ImFontAtlas glyph ranges helpers + GlyphRangesBuilder +//------------------------------------------------------------------------- + +const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() +{ + // Store 2500 regularly used characters for Simplified Chinese. + // Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8 + // This table covers 97.97% of all characters used during the month in July, 1987. + // You can use ImFontAtlas::GlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. + // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) + static const short accumulative_offsets_from_0x4E00[] = + { + 0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2, + 1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4, + 2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1, + 1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2, + 3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6, + 1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1, + 1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3, + 2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4, + 27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12, + 3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1, + 1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23, + 176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6, + 5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6, + 1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1, + 6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5, + 2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15, + 2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6, + 2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4, + 3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5, + 3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2, + 3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16, + 1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31, + 140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7, + 5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2, + 2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13, + 4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3, + 2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4, + 4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1, + 3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3, + 3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11, + 2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9, + 5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2, + 3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3, + 1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12, + 4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8, + 4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5, + 26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1, + 3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5, + 2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6, + 10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6 + }; + static ImWchar base_ranges[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + }; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 }; + if (!full_ranges[0]) + { + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() +{ + // 1946 common ideograms code points for Japanese + // Sourced from http://theinstructionlimit.com/common-kanji-character-ranges-for-xna-spritefont-rendering + // FIXME: Source a list of the revised 2136 Joyo Kanji list from 2010 and rebuild this. + // You can use ImFontAtlas::GlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. + // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) + static const short accumulative_offsets_from_0x4E00[] = + { + 0,1,2,4,1,1,1,1,2,1,6,2,2,1,8,5,7,11,1,2,10,10,8,2,4,20,2,11,8,2,1,2,1,6,2,1,7,5,3,7,1,1,13,7,9,1,4,6,1,2,1,10,1,1,9,2,2,4,5,6,14,1,1,9,3,18, + 5,4,2,2,10,7,1,1,1,3,2,4,3,23,2,10,12,2,14,2,4,13,1,6,10,3,1,7,13,6,4,13,5,2,3,17,2,2,5,7,6,4,1,7,14,16,6,13,9,15,1,1,7,16,4,7,1,19,9,2,7,15, + 2,6,5,13,25,4,14,13,11,25,1,1,1,2,1,2,2,3,10,11,3,3,1,1,4,4,2,1,4,9,1,4,3,5,5,2,7,12,11,15,7,16,4,5,16,2,1,1,6,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1, + 2,1,12,3,3,9,5,8,1,11,1,2,3,18,20,4,1,3,6,1,7,3,5,5,7,2,2,12,3,1,4,2,3,2,3,11,8,7,4,17,1,9,25,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,6,16,1,2,1,1,3,12, + 20,2,5,20,8,7,6,2,1,1,1,1,6,2,1,2,10,1,1,6,1,3,1,2,1,4,1,12,4,1,3,1,1,1,1,1,10,4,7,5,13,1,15,1,1,30,11,9,1,15,38,14,1,32,17,20,1,9,31,2,21,9, + 4,49,22,2,1,13,1,11,45,35,43,55,12,19,83,1,3,2,3,13,2,1,7,3,18,3,13,8,1,8,18,5,3,7,25,24,9,24,40,3,17,24,2,1,6,2,3,16,15,6,7,3,12,1,9,7,3,3, + 3,15,21,5,16,4,5,12,11,11,3,6,3,2,31,3,2,1,1,23,6,6,1,4,2,6,5,2,1,1,3,3,22,2,6,2,3,17,3,2,4,5,1,9,5,1,1,6,15,12,3,17,2,14,2,8,1,23,16,4,2,23, + 8,15,23,20,12,25,19,47,11,21,65,46,4,3,1,5,6,1,2,5,26,2,1,1,3,11,1,1,1,2,1,2,3,1,1,10,2,3,1,1,1,3,6,3,2,2,6,6,9,2,2,2,6,2,5,10,2,4,1,2,1,2,2, + 3,1,1,3,1,2,9,23,9,2,1,1,1,1,5,3,2,1,10,9,6,1,10,2,31,25,3,7,5,40,1,15,6,17,7,27,180,1,3,2,2,1,1,1,6,3,10,7,1,3,6,17,8,6,2,2,1,3,5,5,8,16,14, + 15,1,1,4,1,2,1,1,1,3,2,7,5,6,2,5,10,1,4,2,9,1,1,11,6,1,44,1,3,7,9,5,1,3,1,1,10,7,1,10,4,2,7,21,15,7,2,5,1,8,3,4,1,3,1,6,1,4,2,1,4,10,8,1,4,5, + 1,5,10,2,7,1,10,1,1,3,4,11,10,29,4,7,3,5,2,3,33,5,2,19,3,1,4,2,6,31,11,1,3,3,3,1,8,10,9,12,11,12,8,3,14,8,6,11,1,4,41,3,1,2,7,13,1,5,6,2,6,12, + 12,22,5,9,4,8,9,9,34,6,24,1,1,20,9,9,3,4,1,7,2,2,2,6,2,28,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,8,8,3,2,1,5,1,2,2,3,1,11,11,7,3,6,10,8,6,16,16, + 22,7,12,6,21,5,4,6,6,3,6,1,3,2,1,2,8,29,1,10,1,6,13,6,6,19,31,1,13,4,4,22,17,26,33,10,4,15,12,25,6,67,10,2,3,1,6,10,2,6,2,9,1,9,4,4,1,2,16,2, + 5,9,2,3,8,1,8,3,9,4,8,6,4,8,11,3,2,1,1,3,26,1,7,5,1,11,1,5,3,5,2,13,6,39,5,1,5,2,11,6,10,5,1,15,5,3,6,19,21,22,2,4,1,6,1,8,1,4,8,2,4,2,2,9,2, + 1,1,1,4,3,6,3,12,7,1,14,2,4,10,2,13,1,17,7,3,2,1,3,2,13,7,14,12,3,1,29,2,8,9,15,14,9,14,1,3,1,6,5,9,11,3,38,43,20,7,7,8,5,15,12,19,15,81,8,7, + 1,5,73,13,37,28,8,8,1,15,18,20,165,28,1,6,11,8,4,14,7,15,1,3,3,6,4,1,7,14,1,1,11,30,1,5,1,4,14,1,4,2,7,52,2,6,29,3,1,9,1,21,3,5,1,26,3,11,14, + 11,1,17,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,7,7,5,17,3,3,3,1,23,10,4,4,6,3,1,16,17,22,3,10,21,16,16,6,4,10,2,1,1,2,8,8,6,5,3,3,3,39,25, + 15,1,1,16,6,7,25,15,6,6,12,1,22,13,1,4,9,5,12,2,9,1,12,28,8,3,5,10,22,60,1,2,40,4,61,63,4,1,13,12,1,4,31,12,1,14,89,5,16,6,29,14,2,5,49,18,18, + 5,29,33,47,1,17,1,19,12,2,9,7,39,12,3,7,12,39,3,1,46,4,12,3,8,9,5,31,15,18,3,2,2,66,19,13,17,5,3,46,124,13,57,34,2,5,4,5,8,1,1,1,4,3,1,17,5, + 3,5,3,1,8,5,6,3,27,3,26,7,12,7,2,17,3,7,18,78,16,4,36,1,2,1,6,2,1,39,17,7,4,13,4,4,4,1,10,4,2,4,6,3,10,1,19,1,26,2,4,33,2,73,47,7,3,8,2,4,15, + 18,1,29,2,41,14,1,21,16,41,7,39,25,13,44,2,2,10,1,13,7,1,7,3,5,20,4,8,2,49,1,10,6,1,6,7,10,7,11,16,3,12,20,4,10,3,1,2,11,2,28,9,2,4,7,2,15,1, + 27,1,28,17,4,5,10,7,3,24,10,11,6,26,3,2,7,2,2,49,16,10,16,15,4,5,27,61,30,14,38,22,2,7,5,1,3,12,23,24,17,17,3,3,2,4,1,6,2,7,5,1,1,5,1,1,9,4, + 1,3,6,1,8,2,8,4,14,3,5,11,4,1,3,32,1,19,4,1,13,11,5,2,1,8,6,8,1,6,5,13,3,23,11,5,3,16,3,9,10,1,24,3,198,52,4,2,2,5,14,5,4,22,5,20,4,11,6,41, + 1,5,2,2,11,5,2,28,35,8,22,3,18,3,10,7,5,3,4,1,5,3,8,9,3,6,2,16,22,4,5,5,3,3,18,23,2,6,23,5,27,8,1,33,2,12,43,16,5,2,3,6,1,20,4,2,9,7,1,11,2, + 10,3,14,31,9,3,25,18,20,2,5,5,26,14,1,11,17,12,40,19,9,6,31,83,2,7,9,19,78,12,14,21,76,12,113,79,34,4,1,1,61,18,85,10,2,2,13,31,11,50,6,33,159, + 179,6,6,7,4,4,2,4,2,5,8,7,20,32,22,1,3,10,6,7,28,5,10,9,2,77,19,13,2,5,1,4,4,7,4,13,3,9,31,17,3,26,2,6,6,5,4,1,7,11,3,4,2,1,6,2,20,4,1,9,2,6, + 3,7,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,5,13,8,4,11,23,1,10,6,2,1,3,21,2,2,4,24,31,4,10,10,2,5,192,15,4,16,7,9,51,1,2,1,1,5,1,1,2,1,3,5,3,1,3,4,1, + 3,1,3,3,9,8,1,2,2,2,4,4,18,12,92,2,10,4,3,14,5,25,16,42,4,14,4,2,21,5,126,30,31,2,1,5,13,3,22,5,6,6,20,12,1,14,12,87,3,19,1,8,2,9,9,3,3,23,2, + 3,7,6,3,1,2,3,9,1,3,1,6,3,2,1,3,11,3,1,6,10,3,2,3,1,2,1,5,1,1,11,3,6,4,1,7,2,1,2,5,5,34,4,14,18,4,19,7,5,8,2,6,79,1,5,2,14,8,2,9,2,1,36,28,16, + 4,1,1,1,2,12,6,42,39,16,23,7,15,15,3,2,12,7,21,64,6,9,28,8,12,3,3,41,59,24,51,55,57,294,9,9,2,6,2,15,1,2,13,38,90,9,9,9,3,11,7,1,1,1,5,6,3,2, + 1,2,2,3,8,1,4,4,1,5,7,1,4,3,20,4,9,1,1,1,5,5,17,1,5,2,6,2,4,1,4,5,7,3,18,11,11,32,7,5,4,7,11,127,8,4,3,3,1,10,1,1,6,21,14,1,16,1,7,1,3,6,9,65, + 51,4,3,13,3,10,1,1,12,9,21,110,3,19,24,1,1,10,62,4,1,29,42,78,28,20,18,82,6,3,15,6,84,58,253,15,155,264,15,21,9,14,7,58,40,39, + }; + static ImWchar base_ranges[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + }; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 }; + if (!full_ranges[0]) + { + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0xA640, 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesThai() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x2010, 0x205E, // Punctuations + 0x0E00, 0x0E7F, // Thai + 0, + }; + return &ranges[0]; +} + +void ImFontAtlas::GlyphRangesBuilder::AddText(const char* text, const char* text_end) +{ + while (text_end ? (text < text_end) : *text) + { + unsigned int c = 0; + int c_len = ImTextCharFromUtf8(&c, text, text_end); + text += c_len; + if (c_len == 0) + break; + if (c < 0x10000) + AddChar((ImWchar)c); + } +} + +void ImFontAtlas::GlyphRangesBuilder::AddRanges(const ImWchar* ranges) +{ + for (; ranges[0]; ranges += 2) + for (ImWchar c = ranges[0]; c <= ranges[1]; c++) + AddChar(c); +} + +void ImFontAtlas::GlyphRangesBuilder::BuildRanges(ImVector* out_ranges) +{ + for (int n = 0; n < 0x10000; n++) + if (GetBit(n)) + { + out_ranges->push_back((ImWchar)n); + while (n < 0x10000 && GetBit(n + 1)) + n++; + out_ranges->push_back((ImWchar)n); + } + out_ranges->push_back(0); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + Scale = 1.0f; + FallbackChar = (ImWchar)'?'; + DisplayOffset = ImVec2(0.0f, 0.0f); + ClearOutputData(); +} + +ImFont::~ImFont() +{ + // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. + // If you want to delete fonts you need to do it between Render() and NewFrame(). + // FIXME-CLEANUP + /* + ImGuiContext& g = *GImGui; + if (g.Font == this) + g.Font = NULL; + */ + ClearOutputData(); +} + +void ImFont::ClearOutputData() +{ + FontSize = 0.0f; + Glyphs.clear(); + IndexAdvanceX.clear(); + IndexLookup.clear(); + FallbackGlyph = NULL; + FallbackAdvanceX = 0.0f; + ConfigDataCount = 0; + ConfigData = NULL; + ContainerAtlas = NULL; + Ascent = Descent = 0.0f; + DirtyLookupTables = true; + MetricsTotalSurface = 0; +} + +void ImFont::BuildLookupTable() +{ + int max_codepoint = 0; + for (int i = 0; i != Glyphs.Size; i++) + max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); + + IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved + IndexAdvanceX.clear(); + IndexLookup.clear(); + DirtyLookupTables = false; + GrowIndex(max_codepoint + 1); + for (int i = 0; i < Glyphs.Size; i++) + { + int codepoint = (int)Glyphs[i].Codepoint; + IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; + IndexLookup[codepoint] = (ImWchar)i; + } + + // Create a glyph to handle TAB + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (FindGlyph((ImWchar)' ')) + { + if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times + Glyphs.resize(Glyphs.Size + 1); + ImFontGlyph& tab_glyph = Glyphs.back(); + tab_glyph = *FindGlyph((ImWchar)' '); + tab_glyph.Codepoint = '\t'; + tab_glyph.AdvanceX *= 4; + IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; + IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size-1); + } + + FallbackGlyph = FindGlyphNoFallback(FallbackChar); + FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f; + for (int i = 0; i < max_codepoint + 1; i++) + if (IndexAdvanceX[i] < 0.0f) + IndexAdvanceX[i] = FallbackAdvanceX; +} + +void ImFont::SetFallbackChar(ImWchar c) +{ + FallbackChar = c; + BuildLookupTable(); +} + +void ImFont::GrowIndex(int new_size) +{ + IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); + if (new_size <= IndexLookup.Size) + return; + IndexAdvanceX.resize(new_size, -1.0f); + IndexLookup.resize(new_size, (ImWchar)-1); +} + +// x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. +// Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). +void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +{ + Glyphs.resize(Glyphs.Size + 1); + ImFontGlyph& glyph = Glyphs.back(); + glyph.Codepoint = (ImWchar)codepoint; + glyph.X0 = x0; + glyph.Y0 = y0; + glyph.X1 = x1; + glyph.Y1 = y1; + glyph.U0 = u0; + glyph.V0 = v0; + glyph.U1 = u1; + glyph.V1 = v1; + glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX + + if (ConfigData->PixelSnapH) + glyph.AdvanceX = (float)(int)(glyph.AdvanceX + 0.5f); + + // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) + DirtyLookupTables = true; + MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f); +} + +void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +{ + IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. + int index_size = IndexLookup.Size; + + if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists + return; + if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + return; + + GrowIndex(dst + 1); + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1; + IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; +} + +const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const +{ + if (c >= IndexLookup.Size) + return FallbackGlyph; + const ImWchar i = IndexLookup[c]; + if (i == (ImWchar)-1) + return FallbackGlyph; + return &Glyphs.Data[i]; +} + +const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const +{ + if (c >= IndexLookup.Size) + return NULL; + const ImWchar i = IndexLookup[c]; + if (i == (ImWchar)-1) + return NULL; + return &Glyphs.Data[i]; +} + +const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters + + const char* word_end = text; + const char* prev_word_end = NULL; + bool inside_word = true; + + const char* s = text; + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char* next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + + if (c < 32) + { + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + if (c == '\r') + { + s = next_s; + continue; + } + } + + const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX[(int)c] : FallbackAdvanceX); + if (ImCharIsBlankW(c)) + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + word_end = s; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width >= wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + + const float line_height = size; + const float scale = size / FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + const char* prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; + } + if (c == '\r') + continue; + } + + const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX[(int)c] : FallbackAdvanceX) * scale; + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (line_width > 0 || text_size.y == 0.0f) + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const +{ + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded. + return; + if (const ImFontGlyph* glyph = FindGlyph(c)) + { + float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + } +} + +void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls. + + // Align to be pixel perfect + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + float x = pos.x; + float y = pos.y; + if (y > clip_rect.w) + return; + + const float scale = size / FontSize; + const float line_height = FontSize * scale; + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + // Fast-forward to first visible line + const char* s = text_begin; + if (y + line_height < clip_rect.y && !word_wrap_enabled) + while (y + line_height < clip_rect.y && s < text_end) + { + s = (const char*)memchr(s, '\n', text_end - s); + s = s ? s + 1 : text_end; + y += line_height; + } + + // For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() + // Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) + if (text_end - s > 10000 && !word_wrap_enabled) + { + const char* s_end = s; + float y_end = y; + while (y_end < clip_rect.w && s_end < text_end) + { + s_end = (const char*)memchr(s_end, '\n', text_end - s_end); + s_end = s_end ? s_end + 1 : text_end; + y_end += line_height; + } + text_end = s_end; + } + if (s == text_end) + return; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = pos.x; + y += line_height; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + x = pos.x; + y += line_height; + if (y > clip_rect.w) + break; // break out of main loop + continue; + } + if (c == '\r') + continue; + } + + float char_width = 0.0f; + if (const ImFontGlyph* glyph = FindGlyph((ImWchar)c)) + { + char_width = glyph->AdvanceX * scale; + + // Arbitrarily assume that both space and tabs are empty glyphs as an optimization + if (c != ' ' && c != '\t') + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: + { + idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); + idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); + vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; + vtx_write += 4; + vtx_current_idx += 4; + idx_write += 6; + } + } + } + } + + x += char_width; + } + + // Give back unused vertices + draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); + draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; +} + +//----------------------------------------------------------------------------- +// [SECTION] Internal Render Helpers +// (progressively moved from imgui.cpp to here when they are redesigned to stop accessing ImGui global state) +//----------------------------------------------------------------------------- +// - RenderMouseCursor() +// - RenderArrowPointingAt() +// - RenderRectFilledRangeH() +//----------------------------------------------------------------------------- + +void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor) +{ + if (mouse_cursor == ImGuiMouseCursor_None) + return; + IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT); + + const ImU32 col_shadow = IM_COL32(0, 0, 0, 48); + const ImU32 col_border = IM_COL32(0, 0, 0, 255); // Black + const ImU32 col_fill = IM_COL32(255, 255, 255, 255); // White + + ImFontAtlas* font_atlas = draw_list->_Data->Font->ContainerAtlas; + ImVec2 offset, size, uv[4]; + if (font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2])) + { + pos -= offset; + const ImTextureID tex_id = font_atlas->TexID; + draw_list->PushTextureID(tex_id); + draw_list->AddImage(tex_id, pos + ImVec2(1,0)*scale, pos + ImVec2(1,0)*scale + size*scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_id, pos + ImVec2(2,0)*scale, pos + ImVec2(2,0)*scale + size*scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_id, pos, pos + size*scale, uv[2], uv[3], col_border); + draw_list->AddImage(tex_id, pos, pos + size*scale, uv[0], uv[1], col_fill); + draw_list->PopTextureID(); + } +} + +// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. +void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) +{ + switch (direction) + { + case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings + } +} + +static inline float ImAcos01(float x) +{ + if (x <= 0.0f) return IM_PI * 0.5f; + if (x >= 1.0f) return 0.0f; + return ImAcos(x); + //return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do. +} + +// FIXME: Cleanup and move code to ImDrawList. +void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding) +{ + if (x_end_norm == x_start_norm) + return; + if (x_start_norm > x_end_norm) + ImSwap(x_start_norm, x_end_norm); + + ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); + ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); + if (rounding == 0.0f) + { + draw_list->AddRectFilled(p0, p1, col, 0.0f); + return; + } + + rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding); + const float inv_rounding = 1.0f / rounding; + const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding); + const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding); + const float x0 = ImMax(p0.x, rect.Min.x + rounding); + if (arc0_b == arc0_e) + { + draw_list->PathLineTo(ImVec2(x0, p1.y)); + draw_list->PathLineTo(ImVec2(x0, p0.y)); + } + else if (arc0_b == 0.0f && arc0_e == IM_PI*0.5f) + { + draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL + draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR + } + else + { + draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL + draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR + } + if (p1.x > rect.Min.x + rounding) + { + const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding); + const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding); + const float x1 = ImMin(p1.x, rect.Max.x - rounding); + if (arc1_b == arc1_e) + { + draw_list->PathLineTo(ImVec2(x1, p0.y)); + draw_list->PathLineTo(ImVec2(x1, p1.y)); + } + else if (arc1_b == 0.0f && arc1_e == IM_PI*0.5f) + { + draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR + draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR + } + else + { + draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR + draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR + } + } + draw_list->PathFillConvex(col); +} + + +//----------------------------------------------------------------------------- +// [SECTION] Decompression code +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array and encoded as base85. +// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(const unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier_out_e, *stb__barrier_out_b; +static const unsigned char *stb__barrier_in_b; +static unsigned char *stb__dout; +static void stb__match(const unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT(stb__dout + length <= stb__barrier_out_e); + if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; } + if (data < stb__barrier_out_b) { stb__dout = stb__barrier_out_e+1; return; } + while (length--) *stb__dout++ = *data++; +} + +static void stb__lit(const unsigned char *data, unsigned int length) +{ + IM_ASSERT(stb__dout + length <= stb__barrier_out_e); + if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; } + if (data < stb__barrier_in_b) { stb__dout = stb__barrier_out_e+1; return; } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) + +static const unsigned char *stb_decompress_token(const unsigned char *i) +{ + if (*i >= 0x20) { // use fewer if's for cases that expand small + if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; + else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } else { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; + else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; + else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; + else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen, i; + + blocklen = buflen % 5552; + while (buflen) { + for (i=0; i + 7 < blocklen; i += 8) { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/) +{ + unsigned int olen; + if (stb__in4(0) != 0x57bC0000) return 0; + if (stb__in4(4) != 0) return 0; // error! stream is > 4GB + olen = stb_decompress_length(i); + stb__barrier_in_b = i; + stb__barrier_out_e = output + olen; + stb__barrier_out_b = output; + i += 16; + + stb__dout = output; + for (;;) { + const unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) { + if (*i == 0x05 && i[1] == 0xfa) { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) return 0; + if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) + return 0; + return olen; + } else { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Default font data (ProggyClean.ttf) +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) +// Download and more information at http://upperbounds.net +//----------------------------------------------------------------------------- +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding). +// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. +//----------------------------------------------------------------------------- +static const char proggy_clean_ttf_compressed_data_base85[11980+1] = + "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" + "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N" + "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." + "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G" + "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)" + "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" + "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" + "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" + "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" + "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" + "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" + "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" + "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" + "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" + "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" + "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" + "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" + "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" + "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-" + "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" + "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" + ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@" + "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" + "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" + "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#" + "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" + "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" + "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" + "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" + "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" + "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" + "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" + "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-" + "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" + "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" + "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" + "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" + ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" + "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" + "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" + "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" + "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" + "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO" + "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" + ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T" + "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" + "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" + "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" + "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" + "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; + +static const char* GetDefaultCompressedFontDataTTFBase85() +{ + return proggy_clean_ttf_compressed_data_base85; +} diff --git a/src/3rdparty/imgui/imgui_internal.h b/src/3rdparty/imgui/imgui_internal.h new file mode 100644 index 000000000..e4830c1cb --- /dev/null +++ b/src/3rdparty/imgui/imgui_internal.h @@ -0,0 +1,1331 @@ +// dear imgui, v1.66b +// (internal structures/api) + +// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! +// Set: +// #define IMGUI_DEFINE_MATH_OPERATORS +// To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) + +#pragma once + +#ifndef IMGUI_VERSION +#error Must include imgui.h before imgui_internal.h +#endif + +#include // FILE* +#include // NULL, malloc, free, qsort, atoi, atof +#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf +#include // INT_MIN, INT_MAX + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + +//----------------------------------------------------------------------------- +// Forward Declarations +//----------------------------------------------------------------------------- + +struct ImRect; // An axis-aligned rectangle (2 points) +struct ImDrawDataBuilder; // Helper to build a ImDrawData instance +struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColumnData; // Storage data for a single column +struct ImGuiColumnsSet; // Storage data for a columns set +struct ImGuiContext; // Main imgui context +struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() +struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box +struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data +struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only +struct ImGuiNavMoveResult; // Result of a directional navigation move query result +struct ImGuiNextWindowData; // Storage for SetNexWindow** functions +struct ImGuiPopupRef; // Storage for current popup stack +struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file +struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it +struct ImGuiWindow; // Storage for one window +struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame) +struct ImGuiWindowSettings; // Storage for window settings stored in .ini file (we keep one of those even if the actual window wasn't instanced during this session) + +// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. +typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() +typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() +typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags +typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() +typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d() +typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests +typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for Separator() - internal +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior() +typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() + +//------------------------------------------------------------------------- +// STB libraries +//------------------------------------------------------------------------- + +namespace ImGuiStb +{ + +#undef STB_TEXTEDIT_STRING +#undef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_STRING ImGuiInputTextState +#define STB_TEXTEDIT_CHARTYPE ImWchar +#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#include "imstb_textedit.h" + +} // namespace ImGuiStb + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +#ifndef GImGui +extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointer +#endif + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +#define IM_PI 3.14159265358979323846f +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" // Play it nice with Windows users (2018/05 news: Microsoft announced that Notepad will finally display Unix-style carriage returns!) +#else +#define IM_NEWLINE "\n" +#endif +#define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1] +#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose +#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 + +// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall +#ifdef _MSC_VER +#define IMGUI_CDECL __cdecl +#else +#define IMGUI_CDECL +#endif + +// Helpers: UTF-8 <> wchar +IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count +IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count +IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count +IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) +IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8 +IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8 + +// Helpers: Misc +IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings +IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode); +static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } +static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } +static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } +static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } +#define ImQsort qsort + +// Helpers: Geometry +IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p); +IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); +IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p); +IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w); +IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy); + +// Helpers: String +IMGUI_API int ImStricmp(const char* str1, const char* str2); +IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); +IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); +IMGUI_API char* ImStrdup(const char* str); +IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); +IMGUI_API int ImStrlenW(const ImWchar* str); +IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line +IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line +IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); +IMGUI_API void ImStrTrimBlanks(char* str); +IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3); +IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3); +IMGUI_API const char* ImParseFormatFindStart(const char* format); +IMGUI_API const char* ImParseFormatFindEnd(const char* format); +IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, int buf_size); +IMGUI_API int ImParseFormatPrecision(const char* format, int default_value); + +// Helpers: ImVec2/ImVec4 operators +// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.) +// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself. +#ifdef IMGUI_DEFINE_MATH_OPERATORS +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } +static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x+rhs.x, lhs.y+rhs.y, lhs.z+rhs.z, lhs.w+rhs.w); } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); } +static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x*rhs.x, lhs.y*rhs.y, lhs.z*rhs.z, lhs.w*rhs.w); } +#endif + +// Helpers: Maths +// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) +#ifndef IMGUI_DISABLE_MATH_FUNCTIONS +static inline float ImFabs(float x) { return fabsf(x); } +static inline float ImSqrt(float x) { return sqrtf(x); } +static inline float ImPow(float x, float y) { return powf(x, y); } +static inline double ImPow(double x, double y) { return pow(x, y); } +static inline float ImFmod(float x, float y) { return fmodf(x, y); } +static inline double ImFmod(double x, double y) { return fmod(x, y); } +static inline float ImCos(float x) { return cosf(x); } +static inline float ImSin(float x) { return sinf(x); } +static inline float ImAcos(float x) { return acosf(x); } +static inline float ImAtan2(float y, float x) { return atan2f(y, x); } +static inline double ImAtof(const char* s) { return atof(s); } +static inline float ImFloorStd(float x) { return floorf(x); } // we already uses our own ImFloor() { return (float)(int)v } internally so the standard one wrapper is named differently (it's used by stb_truetype) +static inline float ImCeil(float x) { return ceilf(x); } +#endif +// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support for variety of types: signed/unsigned int/long long float/double, using templates here but we could also redefine them 6 times +template static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } +template static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } +template static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +template static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } +template static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } +// - Misc maths helpers +static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } +static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } +static inline ImVec2 ImClamp(const ImVec2& v, const ImVec2& mn, ImVec2 mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); } +static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } +static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } +static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } +static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } +static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; } +static inline float ImFloor(float f) { return (float)(int)f; } +static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } +static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } +static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } +static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } +static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } + +// Helper: ImPool<>. Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, +// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. +typedef int ImPoolIdx; +template +struct IMGUI_API ImPool +{ + ImVector Data; // Contiguous data + ImGuiStorage Map; // ID->Index + ImPoolIdx FreeIdx; // Next free idx to use + + ImPool() { FreeIdx = 0; } + ~ImPool() { Clear(); } + T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Data[idx] : NULL; } + T* GetByIndex(ImPoolIdx n) { return &Data[n]; } + ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Data.Data && p < Data.Data + Data.Size); return (ImPoolIdx)(p - Data.Data); } + T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Data[*p_idx]; *p_idx = FreeIdx; return Add(); } + void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Data[idx].~T(); } Map.Clear(); Data.clear(); FreeIdx = 0; } + T* Add() { int idx = FreeIdx; if (idx == Data.Size) { Data.resize(Data.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Data[idx]; } IM_PLACEMENT_NEW(&Data[idx]) T(); return &Data[idx]; } + void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); } + void Remove(ImGuiID key, ImPoolIdx idx) { Data[idx].~T(); *(int*)&Data[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); } + void Reserve(int capacity) { Data.reserve(capacity); Map.Data.reserve(capacity); } + int GetSize() const { return Data.Size; } +}; + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D and maintenance of some patches) +struct ImVec1 +{ + float x; + ImVec1() { x = 0.0f; } + ImVec1(float _x) { x = _x; } +}; + +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat + ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // return true on click + release on same item [DEFAULT if no PressedOn* flag is set] + ImGuiButtonFlags_PressedOnClick = 1 << 2, // return true on click (default requires click+release) + ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return true on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return true on double-click (default requires click+release) + ImGuiButtonFlags_FlattenChildren = 1 << 5, // allow interactions even if a child window is overlapping + ImGuiButtonFlags_AllowItemOverlap = 1 << 6, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() + ImGuiButtonFlags_DontClosePopups = 1 << 7, // disable automatically closing parent popup on press // [UNUSED] + ImGuiButtonFlags_Disabled = 1 << 8, // disable interactions + ImGuiButtonFlags_AlignTextBaseLine = 1 << 9, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + ImGuiButtonFlags_NoKeyModifiers = 1 << 10, // disable interaction if a key modifier is held + ImGuiButtonFlags_NoHoldingActiveID = 1 << 11, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) + ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12, // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) + ImGuiButtonFlags_NoNavFocus = 1 << 13 // don't override navigation focus when activated +}; + +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags_Vertical = 1 << 0 +}; + +enum ImGuiDragFlags_ +{ + ImGuiDragFlags_None = 0, + ImGuiDragFlags_Vertical = 1 << 0 +}; + +enum ImGuiColumnsFlags_ +{ + // Default: 0 + ImGuiColumnsFlags_None = 0, + ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers + ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers + ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns + ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window + ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. +}; + +enum ImGuiSelectableFlagsPrivate_ +{ + // NB: need to be in sync with last value of ImGuiSelectableFlags_ + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 10, + ImGuiSelectableFlags_PressedOnClick = 1 << 11, + ImGuiSelectableFlags_PressedOnRelease = 1 << 12, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 13 +}; + +enum ImGuiSeparatorFlags_ +{ + ImGuiSeparatorFlags_None = 0, + ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar + ImGuiSeparatorFlags_Vertical = 1 << 1 +}; + +// Storage for LastItem data +enum ImGuiItemStatusFlags_ +{ + ImGuiItemStatusFlags_None = 0, + ImGuiItemStatusFlags_HoveredRect = 1 << 0, + ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, + ImGuiItemStatusFlags_Edited = 1 << 2 // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) +}; + +// FIXME: this is in development, not exposed/functional as a generic feature yet. +enum ImGuiLayoutType_ +{ + ImGuiLayoutType_Vertical, + ImGuiLayoutType_Horizontal +}; + +enum ImGuiAxis +{ + ImGuiAxis_None = -1, + ImGuiAxis_X = 0, + ImGuiAxis_Y = 1 +}; + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram +}; + +enum ImGuiInputSource +{ + ImGuiInputSource_None = 0, + ImGuiInputSource_Mouse, + ImGuiInputSource_Nav, + ImGuiInputSource_NavKeyboard, // Only used occasionally for storage, not tested/handled by most code + ImGuiInputSource_NavGamepad, // " + ImGuiInputSource_COUNT +}; + +// FIXME-NAV: Clarify/expose various repeat delay/rate +enum ImGuiInputReadMode +{ + ImGuiInputReadMode_Down, + ImGuiInputReadMode_Pressed, + ImGuiInputReadMode_Released, + ImGuiInputReadMode_Repeat, + ImGuiInputReadMode_RepeatSlow, + ImGuiInputReadMode_RepeatFast +}; + +enum ImGuiNavHighlightFlags_ +{ + ImGuiNavHighlightFlags_None = 0, + ImGuiNavHighlightFlags_TypeDefault = 1 << 0, + ImGuiNavHighlightFlags_TypeThin = 1 << 1, + ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, + ImGuiNavHighlightFlags_NoRounding = 1 << 3 +}; + +enum ImGuiNavDirSourceFlags_ +{ + ImGuiNavDirSourceFlags_None = 0, + ImGuiNavDirSourceFlags_Keyboard = 1 << 0, + ImGuiNavDirSourceFlags_PadDPad = 1 << 1, + ImGuiNavDirSourceFlags_PadLStick = 1 << 2 +}; + +enum ImGuiNavMoveFlags_ +{ + ImGuiNavMoveFlags_None = 0, + ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side + ImGuiNavMoveFlags_LoopY = 1 << 1, + ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) + ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful for provided for completeness + ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) + ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5 // Store alternate result in NavMoveResultLocalVisibleSet that only comprise elements that are already fully visible. +}; + +enum ImGuiNavForward +{ + ImGuiNavForward_None, + ImGuiNavForward_ForwardQueued, + ImGuiNavForward_ForwardActive +}; + +enum ImGuiPopupPositionPolicy +{ + ImGuiPopupPositionPolicy_Default, + ImGuiPopupPositionPolicy_ComboBox +}; + +// 2D axis aligned bounding-box +// NB: we can't rely on ImVec2 math operators being available here +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {} + ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } + float GetWidth() const { return Max.x - Min.x; } + float GetHeight() const { return Max.y - Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } + void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } + void TranslateX(float dx) { Min.x += dx; Max.x += dx; } + void TranslateY(float dy) { Min.y += dy; Max.y += dy; } + void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. + void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. + void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } + bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } +}; + +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColorMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } +}; + +// Stacked storage data for BeginGroup()/EndGroup() +struct ImGuiGroupData +{ + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec1 BackupIndent; + ImVec1 BackupGroupOffset; + ImVec2 BackupCurrentLineSize; + float BackupCurrentLineTextBaseOffset; + float BackupLogLinePosY; + ImGuiID BackupActiveIdIsAlive; + bool BackupActiveIdPreviousFrameIsAlive; + bool AdvanceCursor; +}; + +// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. +struct IMGUI_API ImGuiMenuColumns +{ + int Count; + float Spacing; + float Width, NextWidth; + float Pos[4], NextWidths[4]; + + ImGuiMenuColumns(); + void Update(int count, float spacing, bool clear); + float DeclColumns(float w0, float w1, float w2); + float CalcExtraSpace(float avail_w); +}; + +// Internal state of the currently focused/edited text input box +struct IMGUI_API ImGuiInputTextState +{ + ImGuiID ID; // widget id owning the text state + ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + ImVector InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + ImVector TempBuffer; // temporary buffer for callback and other other operations. size=capacity. + int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. + int BufCapacityA; // end-user buffer capacity + float ScrollX; + ImGuiStb::STB_TexteditState StbState; + float CursorAnim; + bool CursorFollow; + bool SelectedAllMouseLock; + + // Temporarily set when active + ImGuiInputTextFlags UserFlags; + ImGuiInputTextCallback UserCallback; + void* UserCallbackData; + + ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } + bool HasSelection() const { return StbState.select_start != StbState.select_end; } + void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } + void SelectAll() { StbState.select_start = 0; StbState.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = false; } + void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation +}; + +// Windows data saved in imgui.ini file +struct ImGuiWindowSettings +{ + char* Name; + ImGuiID ID; + ImVec2 Pos; + ImVec2 Size; + bool Collapsed; + + ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ImVec2(0,0); Collapsed = false; } +}; + +struct ImGuiSettingsHandler +{ + const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' + ImGuiID TypeHash; // == ImHash(TypeName, 0, 0) + void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" + void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry + void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' + void* UserData; + + ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } +}; + +// Storage for current popup stack +struct ImGuiPopupRef +{ + ImGuiID PopupId; // Set on OpenPopup() + ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow* ParentWindow; // Set on OpenPopup() + int OpenFrameCount; // Set on OpenPopup() + ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differenciate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) + ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup +}; + +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + float OffsetNormBeforeResize; + ImGuiColumnsFlags Flags; // Not exposed + ImRect ClipRect; + + ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = 0; } +}; + +struct ImGuiColumnsSet +{ + ImGuiID ID; + ImGuiColumnsFlags Flags; + bool IsFirstFrame; + bool IsBeingResized; + int Current; + int Count; + float MinX, MaxX; + float LineMinY, LineMaxY; + float StartPosY; // Copy of CursorPos + float StartMaxPosX; // Copy of CursorMaxPos + ImVector Columns; + + ImGuiColumnsSet() { Clear(); } + void Clear() + { + ID = 0; + Flags = 0; + IsFirstFrame = false; + IsBeingResized = false; + Current = 0; + Count = 1; + MinX = MaxX = 0.0f; + LineMinY = LineMaxY = 0.0f; + StartPosY = 0.0f; + StartMaxPosX = 0.0f; + Columns.clear(); + } +}; + +// Data shared between all ImDrawList instances +struct IMGUI_API ImDrawListSharedData +{ + ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas + ImFont* Font; // Current/default font (optional, for simplified AddText overload) + float FontSize; // Current/default font size (optional, for simplified AddText overload) + float CurveTessellationTol; + ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() + + // Const data + // FIXME: Bake rounded corners fill/borders in atlas + ImVec2 CircleVtx12[12]; + + ImDrawListSharedData(); +}; + +struct ImDrawDataBuilder +{ + ImVector Layers[2]; // Global layers for: regular, tooltip + + void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); } + void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); } + IMGUI_API void FlattenIntoSingleLayer(); +}; + +struct ImGuiNavMoveResult +{ + ImGuiID ID; // Best candidate + ImGuiWindow* Window; // Best candidate window + float DistBox; // Best candidate box distance to current NavId + float DistCenter; // Best candidate center distance to current NavId + float DistAxial; + ImRect RectRel; // Best candidate bounding box in window relative space + + ImGuiNavMoveResult() { Clear(); } + void Clear() { ID = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); } +}; + +// Storage for SetNexWindow** functions +struct ImGuiNextWindowData +{ + ImGuiCond PosCond; + ImGuiCond SizeCond; + ImGuiCond ContentSizeCond; + ImGuiCond CollapsedCond; + ImGuiCond SizeConstraintCond; + ImGuiCond FocusCond; + ImGuiCond BgAlphaCond; + ImVec2 PosVal; + ImVec2 PosPivotVal; + ImVec2 SizeVal; + ImVec2 ContentSizeVal; + bool CollapsedVal; + ImRect SizeConstraintRect; + ImGuiSizeCallback SizeCallback; + void* SizeCallbackUserData; + float BgAlphaVal; + ImVec2 MenuBarOffsetMinVal; // This is not exposed publicly, so we don't clear it. + + ImGuiNextWindowData() + { + PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0; + PosVal = PosPivotVal = SizeVal = ImVec2(0.0f, 0.0f); + ContentSizeVal = ImVec2(0.0f, 0.0f); + CollapsedVal = false; + SizeConstraintRect = ImRect(); + SizeCallback = NULL; + SizeCallbackUserData = NULL; + BgAlphaVal = FLT_MAX; + MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); + } + + void Clear() + { + PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0; + } +}; + +// Main imgui context +struct ImGuiContext +{ + bool Initialized; + bool FrameScopeActive; // Set by NewFrame(), cleared by EndFrame()/Render() + bool FontAtlasOwnedByContext; // Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it. + ImGuiIO IO; + ImGuiStyle Style; + ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() + float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. + float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. + ImDrawListSharedData DrawListSharedData; + + double Time; + int FrameCount; + int FrameCountEnded; + int FrameCountRendered; + ImVector Windows; // Windows, sorted in display order, back to front + ImVector WindowsFocusOrder; // Windows, sorted in focus order, back to front + ImVector WindowsSortBuffer; + ImVector CurrentWindowStack; + ImGuiStorage WindowsById; + int WindowsActiveCount; + ImGuiWindow* CurrentWindow; // Being drawn into + ImGuiWindow* HoveredWindow; // Will catch mouse inputs + ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiID HoveredId; // Hovered widget + bool HoveredIdAllowOverlap; + ImGuiID HoveredIdPreviousFrame; + float HoveredIdTimer; // Measure contiguous hovering time + float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active + ImGuiID ActiveId; // Active widget + ImGuiID ActiveIdPreviousFrame; + ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) + float ActiveIdTimer; + bool ActiveIdIsJustActivated; // Set at the time of activation for one frame + bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) + bool ActiveIdHasBeenEdited; // Was the value associated to the widget Edited over the course of the Active state. + bool ActiveIdPreviousFrameIsAlive; + bool ActiveIdPreviousFrameHasBeenEdited; + int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it) + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) + ImGuiWindow* ActiveIdWindow; + ImGuiWindow* ActiveIdPreviousFrameWindow; + ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard) + ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. + float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. + ImVec2 LastValidMousePos; + ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. + ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() + ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() + ImVector FontStack; // Stack for PushFont()/PopFont() + ImVector OpenPopupStack; // Which popups are open (persistent) + ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) + ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions + bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions + ImGuiCond NextTreeNodeOpenCond; + + // Navigation data (for gamepad/keyboard) + ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow' + ImGuiID NavId; // Focused item for navigation + ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem() + ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0 + ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0 + ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0 + ImGuiID NavJustTabbedId; // Just tabbed to this id. + ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest) + ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame + ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. + ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. + int NavScoringCount; // Metrics for debugging + ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed front-most. + ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f + ImGuiWindow* NavWindowingList; + float NavWindowingTimer; + float NavWindowingHighlightAlpha; + bool NavWindowingToggleLayer; + int NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later. + int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing + bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid + bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default) + bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover) + bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. + bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest + bool NavInitRequest; // Init request for appearing window to select first item + bool NavInitRequestFromMove; + ImGuiID NavInitResultId; + ImRect NavInitResultRectRel; + bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items + bool NavMoveRequest; // Move request for this frame + ImGuiNavMoveFlags NavMoveRequestFlags; + ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu) + ImGuiDir NavMoveDir, NavMoveDirLast; // Direction of the move request (left/right/up/down), direction of the previous move request + ImGuiDir NavMoveClipDir; + ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow + ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) + ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) + + // Render + ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user + ImDrawDataBuilder DrawDataBuilder; + float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) + ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays + ImGuiMouseCursor MouseCursor; + + // Drag and Drop + bool DragDropActive; + bool DragDropWithinSourceOrTarget; + ImGuiDragDropFlags DragDropSourceFlags; + int DragDropSourceFrameCount; + int DragDropMouseButton; + ImGuiPayload DragDropPayload; + ImRect DragDropTargetRect; + ImGuiID DragDropTargetId; + ImGuiDragDropFlags DragDropAcceptFlags; + float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) + ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) + ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) + int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source + ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly + unsigned char DragDropPayloadBufLocal[8]; // Local buffer for small payloads + + // Widget state + ImGuiInputTextState InputTextState; + ImFont InputTextPasswordFont; + ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets + ImVec4 ColorPickerRef; + bool DragCurrentAccumDirty; + float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings + float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio + ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + int TooltipOverrideCount; + ImVector PrivateClipboard; // If no custom clipboard handler is defined + ImVec2 PlatformImePos, PlatformImeLastPos; // Cursor position request & last passed to the OS Input Method Editor + + // Settings + bool SettingsLoaded; + float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero + ImGuiTextBuffer SettingsIniData; // In memory .ini settings + ImVector SettingsHandlers; // List of .ini settings handlers + ImVector SettingsWindows; // ImGuiWindow .ini settings entries (parsed from the last loaded .ini file and maintained on saving) + + // Logging + bool LogEnabled; + FILE* LogFile; // If != NULL log to stdout/ file + ImGuiTextBuffer LogClipboard; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + int LogStartDepth; + int LogAutoExpandMaxDepth; + + // Misc + float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds. + int FramerateSecPerFrameIdx; + float FramerateSecPerFrameAccum; + int WantCaptureMouseNextFrame; // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags + int WantCaptureKeyboardNextFrame; + int WantTextInputNextFrame; + char TempBuffer[1024*3+1]; // Temporary text buffer + + ImGuiContext(ImFontAtlas* shared_font_atlas) : OverlayDrawList(NULL) + { + Initialized = false; + FrameScopeActive = false; + Font = NULL; + FontSize = FontBaseSize = 0.0f; + FontAtlasOwnedByContext = shared_font_atlas ? false : true; + IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); + + Time = 0.0f; + FrameCount = 0; + FrameCountEnded = FrameCountRendered = -1; + WindowsActiveCount = 0; + CurrentWindow = NULL; + HoveredWindow = NULL; + HoveredRootWindow = NULL; + HoveredId = 0; + HoveredIdAllowOverlap = false; + HoveredIdPreviousFrame = 0; + HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; + ActiveId = 0; + ActiveIdPreviousFrame = 0; + ActiveIdIsAlive = 0; + ActiveIdTimer = 0.0f; + ActiveIdIsJustActivated = false; + ActiveIdAllowOverlap = false; + ActiveIdHasBeenEdited = false; + ActiveIdPreviousFrameIsAlive = false; + ActiveIdPreviousFrameHasBeenEdited = false; + ActiveIdAllowNavDirFlags = 0; + ActiveIdClickOffset = ImVec2(-1,-1); + ActiveIdWindow = ActiveIdPreviousFrameWindow = NULL; + ActiveIdSource = ImGuiInputSource_None; + LastActiveId = 0; + LastActiveIdTimer = 0.0f; + LastValidMousePos = ImVec2(0.0f, 0.0f); + MovingWindow = NULL; + NextTreeNodeOpenVal = false; + NextTreeNodeOpenCond = 0; + + NavWindow = NULL; + NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0; + NavJustTabbedId = NavJustMovedToId = NavNextActivateId = 0; + NavInputSource = ImGuiInputSource_None; + NavScoringRectScreen = ImRect(); + NavScoringCount = 0; + NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL; + NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; + NavWindowingToggleLayer = false; + NavLayer = 0; + NavIdTabCounter = INT_MAX; + NavIdIsAlive = false; + NavMousePosDirty = false; + NavDisableHighlight = true; + NavDisableMouseHover = false; + NavAnyRequest = false; + NavInitRequest = false; + NavInitRequestFromMove = false; + NavInitResultId = 0; + NavMoveFromClampedRefRect = false; + NavMoveRequest = false; + NavMoveRequestFlags = 0; + NavMoveRequestForward = ImGuiNavForward_None; + NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; + + DimBgRatio = 0.0f; + OverlayDrawList._Data = &DrawListSharedData; + OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging + MouseCursor = ImGuiMouseCursor_Arrow; + + DragDropActive = DragDropWithinSourceOrTarget = false; + DragDropSourceFlags = 0; + DragDropSourceFrameCount = -1; + DragDropMouseButton = -1; + DragDropTargetId = 0; + DragDropAcceptFlags = 0; + DragDropAcceptIdCurrRectSurface = 0.0f; + DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; + DragDropAcceptFrameCount = -1; + memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); + + ScalarAsInputTextId = 0; + ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; + DragCurrentAccumDirty = false; + DragCurrentAccum = 0.0f; + DragSpeedDefaultRatio = 1.0f / 100.0f; + ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); + TooltipOverrideCount = 0; + PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX); + + SettingsLoaded = false; + SettingsDirtyTimer = 0.0f; + + LogEnabled = false; + LogFile = NULL; + LogStartDepth = 0; + LogAutoExpandMaxDepth = 2; + + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); + FramerateSecPerFrameIdx = 0; + FramerateSecPerFrameAccum = 0.0f; + WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1; + memset(TempBuffer, 0, sizeof(TempBuffer)); + } +}; + +// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). +// This is going to be exposed in imgui.h when stabilized enough. +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_NoTabStop = 1 << 0, // false + ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. + ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 + ImGuiItemFlags_NoNav = 1 << 3, // false + ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false + ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window + ImGuiItemFlags_Default_ = 0 +}; + +// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. +// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered. +struct IMGUI_API ImGuiWindowTempData +{ + ImVec2 CursorPos; + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; // Initial position in client area with padding + ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Turned into window->SizeContents at the beginning of next frame + ImVec2 CurrentLineSize; + float CurrentLineTextBaseOffset; + ImVec2 PrevLineSize; + float PrevLineTextBaseOffset; + float LogLinePosY; + int TreeDepth; + ImU32 TreeDepthMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31 + ImGuiID LastItemId; + ImGuiItemStatusFlags LastItemStatusFlags; + ImRect LastItemRect; // Interaction rect + ImRect LastItemDisplayRect; // End-user display rect (only valid if LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) + bool NavHideHighlightOneFrame; + bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f) + int NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) + int NavLayerCurrentMask; // = (1 << NavLayerCurrent) used by ItemAdd prior to clipping. + int NavLayerActiveMask; // Which layer have been written to (result from previous frame) + int NavLayerActiveMaskNext; // Which layer have been written to (buffer for current frame) + bool MenuBarAppending; // FIXME: Remove this + ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. + ImVector ChildWindows; + ImGuiStorage* StateStorage; + ImGuiLayoutType LayoutType; + ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() + + // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. + ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default] + float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window + float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] + ImVectorItemFlagsStack; + ImVector ItemWidthStack; + ImVector TextWrapPosStack; + ImVectorGroupStack; + int StackSizesBackup[6]; // Store size of various stacks for asserting + + ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + ImVec1 GroupOffset; + ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. + ImGuiColumnsSet* ColumnsSet; // Current columns set + + ImGuiWindowTempData() + { + CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); + CurrentLineSize = PrevLineSize = ImVec2(0.0f, 0.0f); + CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; + LogLinePosY = -1.0f; + TreeDepth = 0; + TreeDepthMayJumpToParentOnPop = 0x00; + LastItemId = 0; + LastItemStatusFlags = 0; + LastItemRect = LastItemDisplayRect = ImRect(); + NavHideHighlightOneFrame = false; + NavHasScroll = false; + NavLayerActiveMask = NavLayerActiveMaskNext = 0x00; + NavLayerCurrent = 0; + NavLayerCurrentMask = 1 << 0; + MenuBarAppending = false; + MenuBarOffset = ImVec2(0.0f, 0.0f); + StateStorage = NULL; + LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical; + ItemWidth = 0.0f; + ItemFlags = ImGuiItemFlags_Default_; + TextWrapPos = -1.0f; + memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); + + Indent = ImVec1(0.0f); + GroupOffset = ImVec1(0.0f); + ColumnsOffset = ImVec1(0.0f); + ColumnsSet = NULL; + } +}; + +// Storage for one window +struct IMGUI_API ImGuiWindow +{ + char* Name; + ImGuiID ID; // == ImHash(Name) + ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ + ImVec2 Pos; // Position (always rounded-up to nearest pixel) + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 SizeFullAtLastBegin; // Copy of SizeFull at the end of Begin. This is the reference value we'll use on the next frame to decide if we need scrollbars. + ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame. Include decoration, window title, border, menu, etc. + ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() + ImVec2 WindowPadding; // Window padding at the time of begin. + float WindowRounding; // Window rounding at the time of begin. + float WindowBorderSize; // Window border size at the time of begin. + ImGuiID MoveId; // == window->GetID("#MOVE") + ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) + ImVec2 Scroll; + ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) + ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered + ImVec2 ScrollbarSizes; // Size taken by scrollbars on each axis + bool ScrollbarX, ScrollbarY; + bool Active; // Set to true on Begin(), unless Collapsed + bool WasActive; + bool WriteAccessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool WantCollapseToggle; + bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) + bool Appearing; // Set during the frame where the window is appearing (or re-appearing) + bool Hidden; // Do not display (== (HiddenFramesForResize > 0) || + bool HasCloseButton; // Set when the window has a close button (p_open != NULL) + int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + int BeginOrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. + int BeginOrderWithinContext; // Order within entire imgui context. This is mostly used for debugging submission order related issues. + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + int AutoFitFramesX, AutoFitFramesY; + bool AutoFitOnlyGrows; + int AutoFitChildAxises; + ImGuiDir AutoPosLastDirection; + int HiddenFramesRegular; // Hide the window for N frames + int HiddenFramesForResize; // Hide the window for N frames while allowing items to be submitted so we can measure their size + ImGuiCond SetWindowPosAllowFlags; // store acceptable condition flags for SetNextWindowPos() use. + ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use. + ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use. + ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right. + + ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. + ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack + ImRect ClipRect; // Current clipping rectangle. = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. + ImRect OuterRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. + ImRect InnerMainRect, InnerClipRect; + ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis + int LastFrameActive; // Last frame number the window was Active. + float ItemWidthDefault; + ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items + ImGuiStorage StateStorage; + ImVector ColumnsStorage; + float FontWindowScale; // User scale multiplier per-window + int SettingsIdx; // Index into SettingsWindow[] (indices are always valid as we only grow the array from the back) + + ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) + ImDrawList DrawListInst; + ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL. + ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. + ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. + ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. + + ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) + ImGuiID NavLastIds[2]; // Last known NavId for this window, per layer (0/1) + ImRect NavRectRel[2]; // Reference rectangle, in window relative space + + // Navigation / Focus + // FIXME-NAV: Merge all this with the new Nav system, at least the request variables should be moved to ImGuiContext + int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() + int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) + int FocusIdxAllRequestCurrent; // Item being requested for focus + int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus + int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) + int FocusIdxTabRequestNext; // " + +public: + ImGuiWindow(ImGuiContext* context, const char* name); + ~ImGuiWindow(); + + ImGuiID GetID(const char* str, const char* str_end = NULL); + ImGuiID GetID(const void* ptr); + ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL); + ImGuiID GetIDNoKeepAlive(const void* ptr); + ImGuiID GetIDFromRectangle(const ImRect& r_abs); + + // We don't use g.FontSize because the window may be != g.CurrentWidow. + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } + float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } +}; + +// Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data. +struct ImGuiItemHoveredDataBackup +{ + ImGuiID LastItemId; + ImGuiItemStatusFlags LastItemStatusFlags; + ImRect LastItemRect; + ImRect LastItemDisplayRect; + + ImGuiItemHoveredDataBackup() { Backup(); } + void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; } + void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; } +}; + +//----------------------------------------------------------------------------- +// Internal API +// No guarantee of forward compatibility here. +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) + // If this ever crash because g.CurrentWindow is NULL it means that either + // - ImGui::NewFrame() has never been called, which is illegal. + // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. + inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; } + IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); + IMGUI_API ImGuiWindow* FindWindowByName(const char* name); + IMGUI_API void FocusWindow(ImGuiWindow* window); + IMGUI_API void FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window); + IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window); + IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window); + IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window); + IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); + IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window); + IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent); + IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); + IMGUI_API void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x); + IMGUI_API void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); + IMGUI_API float GetWindowScrollMaxX(ImGuiWindow* window); + IMGUI_API float GetWindowScrollMaxY(ImGuiWindow* window); + IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); + IMGUI_API void SetCurrentFont(ImFont* font); + inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } + + // Init + IMGUI_API void Initialize(ImGuiContext* context); + IMGUI_API void Shutdown(ImGuiContext* context); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). + + // NewFrame + IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); + IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); + IMGUI_API void UpdateMouseMovingWindow(); + + // Settings + IMGUI_API void MarkIniSettingsDirty(); + IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); + IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); + IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id); + IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); + + // Basic Accessors + inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } + inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } + inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void ClearActiveID(); + IMGUI_API ImGuiID GetHoveredID(); + IMGUI_API void SetHoveredID(ImGuiID id); + IMGUI_API void KeepAliveID(ImGuiID id); + IMGUI_API void MarkItemEdited(ImGuiID id); + + // Basic Helpers for widget code + IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); + IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); + IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL); + IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id); + IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); + IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop = true); // Return true if focus is requested + IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); + IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); + IMGUI_API void PushMultiItemsWidths(int components, float width_full = 0.0f); + IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); + IMGUI_API void PopItemFlag(); + + // Popups, Modals, Tooltips + IMGUI_API void OpenPopupEx(ImGuiID id); + IMGUI_API void ClosePopup(ImGuiID id); + IMGUI_API void ClosePopupToLevel(int remaining); + IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window); + IMGUI_API bool IsPopupOpen(ImGuiID id); + IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); + IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true); + IMGUI_API ImGuiWindow* GetFrontMostPopupModal(); + IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); + IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default); + + // Navigation + IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); + IMGUI_API bool NavMoveRequestButNoResultYet(); + IMGUI_API void NavMoveRequestCancel(); + IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags); + IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); + IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode); + IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f); + IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate); + IMGUI_API void ActivateItem(ImGuiID id); // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again. + IMGUI_API void SetNavID(ImGuiID id, int nav_layer); + IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel); + + // Inputs + inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { const int key_index = GImGui->IO.KeyMap[key]; return (key_index >= 0) ? IsKeyPressed(key_index, repeat) : false; } + inline bool IsNavInputDown(ImGuiNavInput n) { return GImGui->IO.NavInputs[n] > 0.0f; } + inline bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode) { return GetNavInputAmount(n, mode) > 0.0f; } + inline bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode) { return (GetNavInputAmount(n1, mode) + GetNavInputAmount(n2, mode)) > 0.0f; } + + // Drag and Drop + IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); + IMGUI_API void ClearDragDrop(); + IMGUI_API bool IsDragDropPayloadBeingAccepted(); + + // New Columns API (FIXME-WIP) + IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). + IMGUI_API void EndColumns(); // close columns + IMGUI_API void PushColumnClipRect(int column_index = -1); + + // Render helpers + // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. + // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) + IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); + IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL); + IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); + IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); + IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0); + IMGUI_API void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale = 1.0f); + IMGUI_API void RenderBullet(ImVec2 pos); + IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col, float sz); + IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight + IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. + IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); + + // Render helpers (those functions don't access any ImGui state!) + IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor = ImGuiMouseCursor_Arrow); + IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); + IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); + + // Widgets + IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); + IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); + IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags); + IMGUI_API void Scrollbar(ImGuiLayoutType direction); + IMGUI_API void VerticalSeparator(); // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. + + // Widgets low-level behaviors + IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API void TreePushRawID(ImGuiID id); + + // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. + // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). + // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, const T v_min, const T v_max, const char* format, float power, ImGuiDragFlags flags); + template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, const T v_min, const T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos); + template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); + + // InputText + IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format); + + // Color + IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); + IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags); + IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags); + + // Plot + IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + + // Shade functions (write over already created vertices) + IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); + IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); + +} // namespace ImGui + +// ImFontAtlas internals +IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); +IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* spc); +IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); +IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif diff --git a/src/3rdparty/imgui/imgui_widgets.cpp b/src/3rdparty/imgui/imgui_widgets.cpp new file mode 100644 index 000000000..8cce4f916 --- /dev/null +++ b/src/3rdparty/imgui/imgui_widgets.cpp @@ -0,0 +1,5744 @@ +// dear imgui, v1.66b +// (widgets code) + +/* + +Index of this file: + +// [SECTION] Forward Declarations +// [SECTION] Widgets: Text, etc. +// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) +// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) +// [SECTION] Widgets: ComboBox +// [SECTION] Data Type and Data Formatting Helpers +// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +// [SECTION] Widgets: InputText, InputTextMultiline +// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +// [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +// [SECTION] Widgets: Selectable +// [SECTION] Widgets: ListBox +// [SECTION] Widgets: PlotLines, PlotHistogram +// [SECTION] Widgets: Value helpers +// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +#include // toupper, isprint +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#endif + +// Clang/GCC warnings with -Weverything +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#if __GNUC__ >= 8 +#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif +#endif + +//------------------------------------------------------------------------- +// Data +//------------------------------------------------------------------------- + +// Those MIN/MAX values are not define because we need to point to them +static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); +static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF) +static const ImU32 IM_U32_MIN = 0; +static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF) +#ifdef LLONG_MIN +static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll); +static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll); +#else +static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1; +static const ImS64 IM_S64_MAX = 9223372036854775807LL; +#endif +static const ImU64 IM_U64_MIN = 0; +#ifdef ULLONG_MAX +static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull); +#else +static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); +#endif + +//------------------------------------------------------------------------- +// [SECTION] Forward Declarations +//------------------------------------------------------------------------- + +// Data Type helpers +static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format); +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format); + +// For InputTextEx() +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data); +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Text, etc. +//------------------------------------------------------------------------- +// - TextUnformatted() +// - Text() +// - TextV() +// - TextColored() +// - TextColoredV() +// - TextDisabled() +// - TextDisabledV() +// - TextWrapped() +// - TextWrappedV() +// - LabelText() +// - LabelTextV() +// - BulletText() +// - BulletTextV() +//------------------------------------------------------------------------- + +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + IM_ASSERT(text != NULL); + const char* text_begin = text; + if (text_end == NULL) + text_end = text + strlen(text); // FIXME-OPT + + const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); + const float wrap_pos_x = window->DC.TextWrapPos; + const bool wrap_enabled = wrap_pos_x >= 0.0f; + if (text_end - text > 2000 && !wrap_enabled) + { + // Long text! + // Perform manual coarse clipping to optimize for long multi-line text + // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. + // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. + const char* line = text; + const float line_height = GetTextLineHeight(); + const ImRect clip_rect = window->ClipRect; + ImVec2 text_size(0,0); + + if (text_pos.y <= clip_rect.Max.y) + { + ImVec2 pos = text_pos; + + // Lines to skip (can't skip when logging text) + if (!g.LogEnabled) + { + int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); + if (lines_skippable > 0) + { + int lines_skipped = 0; + while (line < text_end && lines_skipped < lines_skippable) + { + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + } + + // Lines to render + if (line < text_end) + { + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); + while (line < text_end) + { + if (IsClippedEx(line_rect, 0, false)) + break; + + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + const ImVec2 line_size = CalcTextSize(line, line_end, false); + text_size.x = ImMax(text_size.x, line_size.x); + RenderText(pos, line, line_end, false); + line = line_end + 1; + line_rect.Min.y += line_height; + line_rect.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + + text_size.y += (pos - text_pos).y; + } + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(bb); + ItemAdd(bb, 0); + } + else + { + const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; + const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + + // Account of baseline offset + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size); + if (!ItemAdd(bb, 0)) + return; + + // Render (we don't hide text after ## in this end-user function) + RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); + } +} + +void ImGui::Text(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextV(fmt, args); + va_end(args); +} + +void ImGui::TextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + TextUnformatted(g.TempBuffer, text_end); +} + +void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextColoredV(col, fmt, args); + va_end(args); +} + +void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, col); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextWrapped(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextWrappedV(fmt, args); + va_end(args); +} + +void ImGui::TextWrappedV(const char* fmt, va_list args) +{ + bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set + if (need_wrap) PushTextWrapPos(0.0f); + TextV(fmt, args); + if (need_wrap) PopTextWrapPos(); +} + +void ImGui::LabelText(const char* label, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + LabelTextV(label, fmt, args); + va_end(args); +} + +// Add a label+text combo aligned to other label+value widgets +void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, 0)) + return; + + // Render + const char* value_text_begin = &g.TempBuffer[0]; + const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin = g.TempBuffer; + const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it + const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding + ItemSize(bb); + if (!ItemAdd(bb, 0)) + return; + + // Render + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Main +//------------------------------------------------------------------------- +// - ButtonBehavior() [Internal] +// - Button() +// - SmallButton() +// - InvisibleButton() +// - ArrowButton() +// - CloseButton() [Internal] +// - CollapseButton() [Internal] +// - Scrollbar() [Internal] +// - Image() +// - ImageButton() +// - Checkbox() +// - CheckboxFlags() +// - RadioButton() +// - ProgressBar() +// - Bullet() +//------------------------------------------------------------------------- + +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (flags & ImGuiButtonFlags_Disabled) + { + if (out_hovered) *out_hovered = false; + if (out_held) *out_held = false; + if (g.ActiveId == id) ClearActiveID(); + return false; + } + + // Default behavior requires click+release on same spot + if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) + flags |= ImGuiButtonFlags_PressedOnClickRelease; + + ImGuiWindow* backup_hovered_window = g.HoveredWindow; + if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) + g.HoveredWindow = window; + + bool pressed = false; + bool hovered = ItemHoverable(bb, id); + + // Drag source doesn't report as hovered + if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover)) + hovered = false; + + // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button + if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) + if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + { + hovered = true; + SetHoveredID(id); + if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy + { + pressed = true; + FocusWindow(window); + } + } + + if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) + g.HoveredWindow = backup_hovered_window; + + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. + if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) + hovered = false; + + // Mouse + if (hovered) + { + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + { + // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat + // PressedOnClickRelease | * | .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds + // PressedOnClick | | .. + // PressedOnRelease | | .. (NOT on release) + // PressedOnDoubleClick | | .. + // FIXME-NAV: We don't honor those different behaviors. + if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) + { + SetActiveID(id, window); + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); + FocusWindow(window); + } + if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) + { + pressed = true; + if (flags & ImGuiButtonFlags_NoHoldingActiveID) + ClearActiveID(); + else + SetActiveID(id, window); // Hold on ID + FocusWindow(window); + } + if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) + { + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + ClearActiveID(); + } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) + pressed = true; + } + + if (pressed) + g.NavDisableHighlight = true; + } + + // Gamepad/Keyboard navigation + // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse. + if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId)) + hovered = true; + + if (g.NavActivateDownId == id) + { + bool nav_activated_by_code = (g.NavActivateId == id); + bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed); + if (nav_activated_by_code || nav_activated_by_inputs) + pressed = true; + if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id) + { + // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. + g.NavActivateId = id; // This is so SetActiveId assign a Nav source + SetActiveID(id, window); + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + } + } + + bool held = false; + if (g.ActiveId == id) + { + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; + if (g.IO.MouseDown[0]) + { + held = true; + } + else + { + if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + if (!g.DragDropActive) + pressed = true; + ClearActiveID(); + } + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + g.NavDisableHighlight = true; + } + else if (g.ActiveIdSource == ImGuiInputSource_Nav) + { + if (g.NavActivateDownId != id) + ClearActiveID(); + } + } + + if (out_hovered) *out_hovered = hovered; + if (out_held) *out_held = held; + + return pressed; +} + +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, id)) + return false; + + if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) + flags |= ImGuiButtonFlags_Repeat; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + if (pressed) + MarkItemEdited(id); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavHighlight(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); + + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); + + return pressed; +} + +bool ImGui::Button(const char* label, const ImVec2& size_arg) +{ + return ButtonEx(label, size_arg, 0); +} + +// Small buttons fits within text without additional vertical spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; + return pressed; +} + +// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. +// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size. + IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f); + + const ImGuiID id = window->GetID(str_id); + ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + return pressed; +} + +bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(str_id); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + const float default_size = GetFrameHeight(); + ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); + if (!ItemAdd(bb, id)) + return false; + + if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) + flags |= ImGuiButtonFlags_Repeat; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavHighlight(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding); + RenderArrow(bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), dir); + + return pressed; +} + +bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) +{ + float sz = GetFrameHeight(); + return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), 0); +} + +// Button to close a window +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window. + // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible). + const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); + bool is_clipped = !ItemAdd(bb, id); + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + if (is_clipped) + return pressed; + + // Render + ImVec2 center = bb.GetCenter(); + if (hovered) + window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9); + + float cross_extent = (radius * 0.7071f) - 1.0f; + ImU32 cross_col = GetColorU32(ImGuiCol_Text); + center -= ImVec2(0.5f, 0.5f); + window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f); + + return pressed; +} + +bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); + ItemAdd(bb, id); + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); + + ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + if (hovered || held) + window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, col, 9); + RenderArrow(bb.Min + g.Style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); + + // Switch to moving the window after mouse is moved beyond the initial drag threshold + if (IsItemActive() && IsMouseDragging()) + StartMouseMovingWindow(window); + + return pressed; +} + +// Vertical/Horizontal scrollbar +// The entire piece of code below is rather confusing because: +// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +void ImGui::Scrollbar(ImGuiLayoutType direction) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const bool horizontal = (direction == ImGuiLayoutType_Horizontal); + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); + + // Render background + bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); + float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; + const ImRect window_rect = window->Rect(); + const float border_size = window->WindowBorderSize; + ImRect bb = horizontal + ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) + : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); + if (!horizontal) + bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); + if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f) + return; + + int window_rounding_corners; + if (horizontal) + window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); + else + window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners); + bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); + + // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) + float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); + float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; + float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w; + float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; + + // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) + // But we maintain a minimum size in pixel to allow for the user to still aim inside. + IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. + const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f); + const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; + + // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). + bool held = false; + bool hovered = false; + const bool previously_held = (g.ActiveId == id); + ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus); + + float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); + float scroll_ratio = ImSaturate(scroll_v / scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + if (held && grab_h_norm < 1.0f) + { + float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; + float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + SetHoveredID(id); + + bool seek_absolute = false; + if (!previously_held) + { + // On initial click calculate the distance between mouse and the center of the grab + if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) + { + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + } + else + { + seek_absolute = true; + *click_delta_to_grab_center_v = 0.0f; + } + } + + // Apply scroll + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position + const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); + scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); + if (horizontal) + window->Scroll.x = scroll_v; + else + window->Scroll.y = scroll_v; + + // Update values for rendering + scroll_ratio = ImSaturate(scroll_v / scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + + // Update distance to grab now that we have seeked and saturated + if (seek_absolute) + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + } + + // Render + const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + ImRect grab_rect; + if (horizontal) + grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y); + else + grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y)); + window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); +} + +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + if (border_col.w > 0.0f) + bb.Max += ImVec2(2, 2); + ItemSize(bb); + if (!ItemAdd(bb, 0)) + return; + + if (border_col.w > 0.0f) + { + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); + window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col)); + } + else + { + window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); + } +} + +// frame_padding < 0: uses FramePadding from style (default) +// frame_padding = 0: no framing +// frame_padding > 0: set framing size +// The color used are the button colors. +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Default to using texture ID as ID. User can still push string/integer prefixes. + // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. + PushID((void*)(intptr_t)user_texture_id); + const ImGuiID id = window->GetID("#image"); + PopID(); + + const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2); + const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); + ItemSize(bb); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavHighlight(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); + window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); + + return pressed; +} + +bool ImGui::Checkbox(const char* label, bool* v) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); // We want a square shape to we use Y twice + ItemSize(check_bb, style.FramePadding.y); + + ImRect total_bb = check_bb; + if (label_size.x > 0) + SameLine(0, style.ItemInnerSpacing.x); + const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); + if (label_size.x > 0) + { + ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); + total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); + } + + if (!ItemAdd(total_bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + { + *v = !(*v); + MarkItemEdited(id); + } + + RenderNavHighlight(total_bb, id); + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + if (*v) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f); + } + + if (g.LogEnabled) + LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]"); + if (label_size.x > 0.0f) + RenderText(text_bb.Min, label); + + return pressed; +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + bool v = ((*flags & flags_value) == flags_value); + bool pressed = Checkbox(label, &v); + if (pressed) + { + if (v) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + + return pressed; +} + +bool ImGui::RadioButton(const char* label, bool active) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); + ItemSize(check_bb, style.FramePadding.y); + + ImRect total_bb = check_bb; + if (label_size.x > 0) + SameLine(0, style.ItemInnerSpacing.x); + const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); + if (label_size.x > 0) + { + ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); + total_bb.Add(text_bb); + } + + if (!ItemAdd(total_bb, id)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = (float)(int)center.x + 0.5f; + center.y = (float)(int)center.y + 0.5f; + const float radius = check_bb.GetHeight() * 0.5f; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + MarkItemEdited(id); + + RenderNavHighlight(total_bb, id); + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); + if (active) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); + } + + if (style.FrameBorderSize > 0.0f) + { + window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize); + } + + if (g.LogEnabled) + LogRenderedText(&text_bb.Min, active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(text_bb.Min, label); + + return pressed; +} + +bool ImGui::RadioButton(const char* label, int* v, int v_button) +{ + const bool pressed = RadioButton(label, *v == v_button); + if (pressed) + *v = v_button; + return pressed; +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, 0)) + return; + + // Render + fraction = ImSaturate(fraction); + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); + const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); + RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + char overlay_buf[32]; + if (!overlay) + { + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); +} + +void ImGui::Bullet() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, 0)) + { + SameLine(0, style.FramePadding.x*2); + return; + } + + // Render and stay on same line + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + SameLine(0, style.FramePadding.x*2); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Low-level Layout helpers +//------------------------------------------------------------------------- +// - Spacing() +// - Dummy() +// - NewLine() +// - AlignTextToFramePadding() +// - Separator() +// - VerticalSeparator() [Internal] +// - SplitterBehavior() [Internal] +//------------------------------------------------------------------------- + +void ImGui::Spacing() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ItemSize(ImVec2(0,0)); +} + +void ImGui::Dummy(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + ItemAdd(bb, 0); +} + +void ImGui::NewLine() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; + window->DC.LayoutType = ImGuiLayoutType_Vertical; + if (window->DC.CurrentLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0,0)); + else + ItemSize(ImVec2(0.0f, g.FontSize)); + window->DC.LayoutType = backup_layout_type; +} + +void ImGui::AlignTextToFramePadding() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + window->DC.CurrentLineSize.y = ImMax(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); +} + +// Horizontal/vertical separating line +void ImGui::Separator() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + // Those flags should eventually be overridable by the user + ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; + IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected + if (flags & ImGuiSeparatorFlags_Vertical) + { + VerticalSeparator(); + return; + } + + // Horizontal Separator + if (window->DC.ColumnsSet) + PopClipRect(); + + float x1 = window->Pos.x; + float x2 = window->Pos.x + window->Size.x; + if (!window->DC.GroupStack.empty()) + x1 += window->DC.Indent.x; + + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); + ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. + if (!ItemAdd(bb, 0)) + { + if (window->DC.ColumnsSet) + PushColumnClipRect(); + return; + } + + window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator)); + + if (g.LogEnabled) + LogRenderedText(&bb.Min, "--------------------------------"); + + if (window->DC.ColumnsSet) + { + PushColumnClipRect(); + window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; + } +} + +void ImGui::VerticalSeparator() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + float y1 = window->DC.CursorPos.y; + float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; + const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); + ItemSize(ImVec2(bb.GetWidth(), 0.0f)); + if (!ItemAdd(bb, 0)) + return; + + window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogText(" |"); +} + +// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. +bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; + window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; + bool item_add = ItemAdd(bb, id); + window->DC.ItemFlags = item_flags_backup; + if (!item_add) + return false; + + bool hovered, held; + ImRect bb_interact = bb; + bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f)); + ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); + if (g.ActiveId != id) + SetItemAllowOverlap(); + + if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay)) + SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + + ImRect bb_render = bb; + if (held) + { + ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min; + float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x; + + // Minimum pane size + float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1); + float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2); + if (mouse_delta < -size_1_maximum_delta) + mouse_delta = -size_1_maximum_delta; + if (mouse_delta > size_2_maximum_delta) + mouse_delta = size_2_maximum_delta; + + // Apply resize + if (mouse_delta != 0.0f) + { + if (mouse_delta < 0.0f) + IM_ASSERT(*size1 + mouse_delta >= min_size1); + if (mouse_delta > 0.0f) + IM_ASSERT(*size2 - mouse_delta >= min_size2); + *size1 += mouse_delta; + *size2 -= mouse_delta; + bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta)); + MarkItemEdited(id); + } + } + + // Render + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding); + + return held; +} + + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ComboBox +//------------------------------------------------------------------------- +// - BeginCombo() +// - EndCombo() +// - Combo() +//------------------------------------------------------------------------- + +static float CalcMaxPopupHeightFromItemCount(int items_count) +{ + ImGuiContext& g = *GImGui; + if (items_count <= 0) + return FLT_MAX; + return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); +} + +bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) +{ + // Always consume the SetNextWindowSizeConstraint() call in our early return paths + ImGuiContext& g = *GImGui; + ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond; + g.NextWindowData.SizeConstraintCond = 0; + + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth(); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); + bool popup_open = IsPopupOpen(id); + + const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); + const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + if (!(flags & ImGuiComboFlags_NoPreview)) + window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left); + if (!(flags & ImGuiComboFlags_NoArrowButton)) + { + window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); + RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down); + } + RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); + if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) + RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f)); + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if ((pressed || g.NavActivateId == id) && !popup_open) + { + if (window->DC.NavLayerCurrent == 0) + window->NavLastIds[0] = id; + OpenPopupEx(id); + popup_open = true; + } + + if (!popup_open) + return false; + + if (backup_next_window_size_constraint) + { + g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint; + g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); + } + else + { + if ((flags & ImGuiComboFlags_HeightMask_) == 0) + flags |= ImGuiComboFlags_HeightRegular; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one + int popup_max_height_in_items = -1; + if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8; + else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4; + else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20; + SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + } + + char name[16]; + ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth + + // Peak into expected window size so we can position it + if (ImGuiWindow* popup_window = FindWindowByName(name)) + if (popup_window->WasActive) + { + ImVec2 size_expected = CalcWindowExpectedSize(popup_window); + if (flags & ImGuiComboFlags_PopupAlignLeft) + popup_window->AutoPosLastDirection = ImGuiDir_Left; + ImRect r_outer = GetWindowAllowedExtentRect(popup_window); + ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox); + SetNextWindowPos(pos); + } + + // Horizontally align ourselves with the framed text + ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(style.FramePadding.x, style.WindowPadding.y)); + bool ret = Begin(name, NULL, window_flags); + PopStyleVar(); + if (!ret) + { + EndPopup(); + IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above + return false; + } + return true; +} + +void ImGui::EndCombo() +{ + EndPopup(); +} + +// Getter for the old Combo() API: const char*[] +static bool Items_ArrayGetter(void* data, int idx, const char** out_text) +{ + const char* const* items = (const char* const*)data; + if (out_text) + *out_text = items[idx]; + return true; +} + +// Getter for the old Combo() API: "item1\0item2\0item3\0" +static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) +{ + // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. + const char* items_separated_by_zeros = (const char*)data; + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + if (idx == items_count) + break; + p += strlen(p) + 1; + items_count++; + } + if (!*p) + return false; + if (out_text) + *out_text = p; + return true; +} + +// Old API, prefer using BeginCombo() nowadays if you can. +bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items) +{ + ImGuiContext& g = *GImGui; + + // Call the getter to obtain the preview string which is a parameter to BeginCombo() + const char* preview_value = NULL; + if (*current_item >= 0 && *current_item < items_count) + items_getter(data, *current_item, &preview_value); + + // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. + if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond) + SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + + if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) + return false; + + // Display items + // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed) + bool value_changed = false; + for (int i = 0; i < items_count; i++) + { + PushID((void*)(intptr_t)i); + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + if (Selectable(item_text, item_selected)) + { + value_changed = true; + *current_item = i; + } + if (item_selected) + SetItemDefaultFocus(); + PopID(); + } + + EndCombo(); + return value_changed; +} + +// Combo box helper allowing to pass an array of strings. +bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) +{ + const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); + return value_changed; +} + +// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0" +bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) +{ + int items_count = 0; + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open + while (*p) + { + p += strlen(p) + 1; + items_count++; + } + bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Data Type and Data Formatting Helpers [Internal] +//------------------------------------------------------------------------- +// - PatchFormatStringFloatToInt() +// - DataTypeFormatString() +// - DataTypeApplyOp() +// - DataTypeApplyOpFromText() +// - GetMinimumStepAtDecimalPrecision +// - RoundScalarWithFormat<>() +//------------------------------------------------------------------------- + +struct ImGuiDataTypeInfo +{ + size_t Size; + const char* PrintFmt; // Unused + const char* ScanFmt; +}; + +static const ImGuiDataTypeInfo GDataTypeInfo[] = +{ + { sizeof(int), "%d", "%d" }, + { sizeof(unsigned int), "%u", "%u" }, +#ifdef _MSC_VER + { sizeof(ImS64), "%I64d","%I64d" }, + { sizeof(ImU64), "%I64u","%I64u" }, +#else + { sizeof(ImS64), "%lld", "%lld" }, + { sizeof(ImU64), "%llu", "%llu" }, +#endif + { sizeof(float), "%f", "%f" }, // float are promoted to double in va_arg + { sizeof(double), "%f", "%lf" }, +}; +IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); + +// FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was "%.0f". +// Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls. +// To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?! +static const char* PatchFormatStringFloatToInt(const char* fmt) +{ + if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for "%.0f" which is expected to be the most common case. + return "%d"; + const char* fmt_start = ImParseFormatFindStart(fmt); // Find % (if any, and ignore %%) + const char* fmt_end = ImParseFormatFindEnd(fmt_start); // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user). + if (fmt_end > fmt_start && fmt_end[-1] == 'f') + { +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (fmt_start == fmt && fmt_end[0] == 0) + return "%d"; + ImGuiContext& g = *GImGui; + ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%.*s%%d%s", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision. + return g.TempBuffer; +#else + IM_ASSERT(0 && "DragInt(): Invalid format string!"); // Old versions used a default parameter of "%.0f", please replace with e.g. "%d" +#endif + } + return fmt; +} + +static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format) +{ + if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) // Signedness doesn't matter when pushing the argument + return ImFormatString(buf, buf_size, format, *(const ImU32*)data_ptr); + if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) // Signedness doesn't matter when pushing the argument + return ImFormatString(buf, buf_size, format, *(const ImU64*)data_ptr); + if (data_type == ImGuiDataType_Float) + return ImFormatString(buf, buf_size, format, *(const float*)data_ptr); + if (data_type == ImGuiDataType_Double) + return ImFormatString(buf, buf_size, format, *(const double*)data_ptr); + IM_ASSERT(0); + return 0; +} + +// FIXME: Adding support for clamping on boundaries of the data type would be nice. +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) +{ + IM_ASSERT(op == '+' || op == '-'); + switch (data_type) + { + case ImGuiDataType_S32: + if (op == '+') *(int*)output = *(const int*)arg1 + *(const int*)arg2; + else if (op == '-') *(int*)output = *(const int*)arg1 - *(const int*)arg2; + return; + case ImGuiDataType_U32: + if (op == '+') *(unsigned int*)output = *(const unsigned int*)arg1 + *(const ImU32*)arg2; + else if (op == '-') *(unsigned int*)output = *(const unsigned int*)arg1 - *(const ImU32*)arg2; + return; + case ImGuiDataType_S64: + if (op == '+') *(ImS64*)output = *(const ImS64*)arg1 + *(const ImS64*)arg2; + else if (op == '-') *(ImS64*)output = *(const ImS64*)arg1 - *(const ImS64*)arg2; + return; + case ImGuiDataType_U64: + if (op == '+') *(ImU64*)output = *(const ImU64*)arg1 + *(const ImU64*)arg2; + else if (op == '-') *(ImU64*)output = *(const ImU64*)arg1 - *(const ImU64*)arg2; + return; + case ImGuiDataType_Float: + if (op == '+') *(float*)output = *(const float*)arg1 + *(const float*)arg2; + else if (op == '-') *(float*)output = *(const float*)arg1 - *(const float*)arg2; + return; + case ImGuiDataType_Double: + if (op == '+') *(double*)output = *(const double*)arg1 + *(const double*)arg2; + else if (op == '-') *(double*)output = *(const double*)arg1 - *(const double*)arg2; + return; + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); +} + +// User can input math operators (e.g. +100) to edit a numerical values. +// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format) +{ + while (ImCharIsBlankA(*buf)) + buf++; + + // We don't support '-' op because it would conflict with inputing negative value. + // Instead you can use +-100 to subtract from an existing value + char op = buf[0]; + if (op == '+' || op == '*' || op == '/') + { + buf++; + while (ImCharIsBlankA(*buf)) + buf++; + } + else + { + op = 0; + } + if (!buf[0]) + return false; + + // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all. + IM_ASSERT(data_type < ImGuiDataType_COUNT); + int data_backup[2]; + IM_ASSERT(GDataTypeInfo[data_type].Size <= sizeof(data_backup)); + memcpy(data_backup, data_ptr, GDataTypeInfo[data_type].Size); + + if (format == NULL) + format = GDataTypeInfo[data_type].ScanFmt; + + int arg1i = 0; + if (data_type == ImGuiDataType_S32) + { + int* v = (int*)data_ptr; + int arg0i = *v; + float arg1f = 0.0f; + if (op && sscanf(initial_value_buf, format, &arg0i) < 1) + return false; + // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision + if (op == '+') { if (sscanf(buf, "%d", &arg1i)) *v = (int)(arg0i + arg1i); } // Add (use "+-" to subtract) + else if (op == '*') { if (sscanf(buf, "%f", &arg1f)) *v = (int)(arg0i * arg1f); } // Multiply + else if (op == '/') { if (sscanf(buf, "%f", &arg1f) && arg1f != 0.0f) *v = (int)(arg0i / arg1f); } // Divide + else { if (sscanf(buf, format, &arg1i) == 1) *v = arg1i; } // Assign constant + } + else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) + { + // Assign constant + // FIXME: We don't bother handling support for legacy operators since they are a little too crappy. Instead we may implement a proper expression evaluator in the future. + sscanf(buf, format, data_ptr); + } + else if (data_type == ImGuiDataType_Float) + { + // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in + format = "%f"; + float* v = (float*)data_ptr; + float arg0f = *v, arg1f = 0.0f; + if (op && sscanf(initial_value_buf, format, &arg0f) < 1) + return false; + if (sscanf(buf, format, &arg1f) < 1) + return false; + if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract) + else if (op == '*') { *v = arg0f * arg1f; } // Multiply + else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide + else { *v = arg1f; } // Assign constant + } + else if (data_type == ImGuiDataType_Double) + { + format = "%lf"; // scanf differentiate float/double unlike printf which forces everything to double because of ellipsis + double* v = (double*)data_ptr; + double arg0f = *v, arg1f = 0.0; + if (op && sscanf(initial_value_buf, format, &arg0f) < 1) + return false; + if (sscanf(buf, format, &arg1f) < 1) + return false; + if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract) + else if (op == '*') { *v = arg0f * arg1f; } // Multiply + else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide + else { *v = arg1f; } // Assign constant + } + return memcmp(data_backup, data_ptr, GDataTypeInfo[data_type].Size) != 0; +} + +static float GetMinimumStepAtDecimalPrecision(int decimal_precision) +{ + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + if (decimal_precision < 0) + return FLT_MIN; + return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision); +} + +template +static const char* ImAtoi(const char* src, TYPE* output) +{ + int negative = 0; + if (*src == '-') { negative = 1; src++; } + if (*src == '+') { src++; } + TYPE v = 0; + while (*src >= '0' && *src <= '9') + v = (v * 10) + (*src++ - '0'); + *output = negative ? -v : v; + return src; +} + +template +TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v) +{ + const char* fmt_start = ImParseFormatFindStart(format); + if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string + return v; + char v_str[64]; + ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v); + const char* p = v_str; + while (*p == ' ') + p++; + if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) + v = (TYPE)ImAtof(p); + else + ImAtoi(p, (SIGNEDTYPE*)&v); + return v; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +//------------------------------------------------------------------------- +// - DragBehaviorT<>() [Internal] +// - DragBehavior() [Internal] +// - DragScalar() +// - DragScalarN() +// - DragFloat() +// - DragFloat2() +// - DragFloat3() +// - DragFloat4() +// - DragFloatRange2() +// - DragInt() +// - DragInt2() +// - DragInt3() +// - DragInt4() +// - DragIntRange2() +//------------------------------------------------------------------------- + +// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) +template +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + const bool has_min_max = (v_min != v_max); + + // Default tweak speed + if (v_speed == 0.0f && has_min_max && (v_max - v_min < FLT_MAX)) + v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio); + + // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings + float adjust_delta = 0.0f; + if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f) + { + adjust_delta = g.IO.MouseDelta[axis]; + if (g.IO.KeyAlt) + adjust_delta *= 1.0f / 100.0f; + if (g.IO.KeyShift) + adjust_delta *= 10.0f; + } + else if (g.ActiveIdSource == ImGuiInputSource_Nav) + { + int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; + adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis]; + v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision)); + } + adjust_delta *= v_speed; + + // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. + if (axis == ImGuiAxis_Y) + adjust_delta = -adjust_delta; + + // Clear current value on activation + // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. + bool is_just_activated = g.ActiveIdIsJustActivated; + bool is_already_past_limits_and_pushing_outward = has_min_max && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); + if (is_just_activated || is_already_past_limits_and_pushing_outward) + { + g.DragCurrentAccum = 0.0f; + g.DragCurrentAccumDirty = false; + } + else if (adjust_delta != 0.0f) + { + g.DragCurrentAccum += adjust_delta; + g.DragCurrentAccumDirty = true; + } + + if (!g.DragCurrentAccumDirty) + return false; + + TYPE v_cur = *v; + FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; + + const bool is_power = (power != 1.0f && is_decimal && has_min_max && (v_max - v_min < FLT_MAX)); + if (is_power) + { + // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range + FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); + FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min)); + v_cur = v_min + (TYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min); + v_old_ref_for_accum_remainder = v_old_norm_curved; + } + else + { + v_cur += (TYPE)g.DragCurrentAccum; + } + + // Round to user desired precision based on format string + v_cur = RoundScalarWithFormatT(format, data_type, v_cur); + + // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. + g.DragCurrentAccumDirty = false; + if (is_power) + { + FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); + g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder); + } + else + { + g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v); + } + + // Lose zero sign for float/double + if (v_cur == (TYPE)-0) + v_cur = (TYPE)0; + + // Clamp values (+ handle overflow/wrap-around for integer types) + if (*v != v_cur && has_min_max) + { + if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_decimal)) + v_cur = v_min; + if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_decimal)) + v_cur = v_max; + } + + // Apply result + if (*v == v_cur) + return false; + *v = v_cur; + return true; +} + +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + { + if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0]) + ClearActiveID(); + else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + ClearActiveID(); + } + if (g.ActiveId != id) + return false; + + switch (data_type) + { + case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)v, v_speed, v_min ? *(const ImS32* )v_min : IM_S32_MIN, v_max ? *(const ImS32* )v_max : IM_S32_MAX, format, power, flags); + case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)v, v_speed, v_min ? *(const ImU32* )v_min : IM_U32_MIN, v_max ? *(const ImU32* )v_max : IM_U32_MAX, format, power, flags); + case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)v, v_speed, v_min ? *(const ImS64* )v_min : IM_S64_MIN, v_max ? *(const ImS64* )v_max : IM_S64_MAX, format, power, flags); + case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)v, v_speed, v_min ? *(const ImU64* )v_min : IM_U64_MIN, v_max ? *(const ImU64* )v_max : IM_U64_MAX, format, power, flags); + case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)v, v_speed, v_min ? *(const float* )v_min : -FLT_MAX, v_max ? *(const float* )v_max : FLT_MAX, format, power, flags); + case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)v, v_speed, v_min ? *(const double*)v_min : -DBL_MAX, v_max ? *(const double*)v_max : DBL_MAX, format, power, flags); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + if (power != 1.0f) + IM_ASSERT(v_min != NULL && v_max != NULL); // When using a power curve the drag needs to have known bounds + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + // NB- we don't call ItemSize() yet because we may turn into a text edit box below + if (!ItemAdd(total_bb, id, &frame_bb)) + { + ItemSize(total_bb, style.FramePadding.y); + return false; + } + const bool hovered = ItemHoverable(frame_bb, id); + + // Default format string when passing NULL + // Patch old "%.0f" format string to use "%d", read function comments for more details. + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + if (format == NULL) + format = GDataTypeInfo[data_type].PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) + format = PatchFormatStringFloatToInt(format); + + // Tabbing or CTRL-clicking on Drag turns it into an input box + bool start_text_input = false; + const bool tab_focus_requested = FocusableItemRegister(window, id); + if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) + { + start_text_input = true; + g.ScalarAsInputTextId = 0; + } + } + if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + { + FocusableItemUnregister(window); + return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); + } + + // Actual drag behavior + ItemSize(total_bb, style.FramePadding.y); + const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None); + if (value_changed) + MarkItemEdited(id); + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + + return value_changed; +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min, const void* v_max, const char* format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragScalar("##v", data_type, v, v_speed, v_min, v_max, format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + v = (void*)((char*)v + type_size); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + return value_changed; +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + return value_changed; +} + +// NB: v_speed is float to allow adjusting the drag speed with more precision +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format) +{ + return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format); +} + +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format); +} + +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format); +} + +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format); +} + +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +//------------------------------------------------------------------------- +// - SliderBehaviorT<>() [Internal] +// - SliderBehavior() [Internal] +// - SliderScalar() +// - SliderScalarN() +// - SliderFloat() +// - SliderFloat2() +// - SliderFloat3() +// - SliderFloat4() +// - SliderAngle() +// - SliderInt() +// - SliderInt2() +// - SliderInt3() +// - SliderInt4() +// - VSliderScalar() +// - VSliderFloat() +// - VSliderInt() +//------------------------------------------------------------------------- + +template +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos) +{ + if (v_min == v_max) + return 0.0f; + + const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); + if (is_power) + { + if (v_clamped < 0.0f) + { + const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min)); + return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos; + } + else + { + const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min))); + return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos); + } + } + + // Linear slider + return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); +} + +// FIXME: Move some of the code into SliderBehavior(). Current responsability is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. +template +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + const bool is_power = (power != 1.0f) && is_decimal; + + const float grab_padding = 2.0f; + const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; + float grab_sz = style.GrabMinSize; + SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max); + if (!is_decimal && v_range >= 0) // v_range < 0 may happen on integer overflows + grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit + grab_sz = ImMin(grab_sz, slider_sz); + const float slider_usable_sz = slider_sz - grab_sz; + const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz*0.5f; + const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz*0.5f; + + // For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f + float linear_zero_pos; // 0.0->1.0f + if (is_power && v_min * v_max < 0.0f) + { + // Different sign + const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f/power); + const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f/power); + linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0)); + } + else + { + // Same sign + linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; + } + + // Process interacting with the slider + bool value_changed = false; + if (g.ActiveId == id) + { + bool set_new_value = false; + float clicked_t = 0.0f; + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (!g.IO.MouseDown[0]) + { + ClearActiveID(); + } + else + { + const float mouse_abs_pos = g.IO.MousePos[axis]; + clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; + if (axis == ImGuiAxis_Y) + clicked_t = 1.0f - clicked_t; + set_new_value = true; + } + } + else if (g.ActiveIdSource == ImGuiInputSource_Nav) + { + const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); + float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y; + if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + { + ClearActiveID(); + } + else if (delta != 0.0f) + { + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; + if ((decimal_precision > 0) || is_power) + { + delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds + if (IsNavInputDown(ImGuiNavInput_TweakSlow)) + delta /= 10.0f; + } + else + { + if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow)) + delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps + else + delta /= 100.0f; + } + if (IsNavInputDown(ImGuiNavInput_TweakFast)) + delta *= 10.0f; + set_new_value = true; + if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits + set_new_value = false; + else + clicked_t = ImSaturate(clicked_t + delta); + } + } + + if (set_new_value) + { + TYPE v_new; + if (is_power) + { + // Account for power curve scale on both sides of the zero + if (clicked_t < linear_zero_pos) + { + // Negative: rescale to the negative range before powering + float a = 1.0f - (clicked_t / linear_zero_pos); + a = ImPow(a, power); + v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); + } + else + { + // Positive: rescale to the positive range before powering + float a; + if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) + a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); + else + a = clicked_t; + a = ImPow(a, power); + v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); + } + } + else + { + // Linear slider + if (is_decimal) + { + v_new = ImLerp(v_min, v_max, clicked_t); + } + else + { + // For integer values we want the clicking position to match the grab box so we round above + // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t; + TYPE v_new_off_floor = (TYPE)(v_new_off_f); + TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); + if (!is_decimal && v_new_off_floor < v_new_off_round) + v_new = v_min + v_new_off_round; + else + v_new = v_min + v_new_off_floor; + } + } + + // Round to user desired precision based on format string + v_new = RoundScalarWithFormatT(format, data_type, v_new); + + // Apply result + if (*v != v_new) + { + *v = v_new; + value_changed = true; + } + } + } + + // Output grab position so it can be displayed by the caller + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + if (axis == ImGuiAxis_Y) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + if (axis == ImGuiAxis_X) + *out_grab_bb = ImRect(grab_pos - grab_sz*0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz*0.5f, bb.Max.y - grab_padding); + else + *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f); + + return value_changed; +} + +// For 32-bits and larger types, slider bounds are limited to half the natural type range. +// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. +// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +{ + switch (data_type) + { + case ImGuiDataType_S32: + IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2); + return SliderBehaviorT(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb); + case ImGuiDataType_U32: + IM_ASSERT(*(const ImU32*)v_min <= IM_U32_MAX/2); + return SliderBehaviorT(bb, id, data_type, (ImU32*)v, *(const ImU32*)v_min, *(const ImU32*)v_max, format, power, flags, out_grab_bb); + case ImGuiDataType_S64: + IM_ASSERT(*(const ImS64*)v_min >= IM_S64_MIN/2 && *(const ImS64*)v_max <= IM_S64_MAX/2); + return SliderBehaviorT(bb, id, data_type, (ImS64*)v, *(const ImS64*)v_min, *(const ImS64*)v_max, format, power, flags, out_grab_bb); + case ImGuiDataType_U64: + IM_ASSERT(*(const ImU64*)v_min <= IM_U64_MAX/2); + return SliderBehaviorT(bb, id, data_type, (ImU64*)v, *(const ImU64*)v_min, *(const ImU64*)v_max, format, power, flags, out_grab_bb); + case ImGuiDataType_Float: + IM_ASSERT(*(const float*)v_min >= -FLT_MAX/2.0f && *(const float*)v_max <= FLT_MAX/2.0f); + return SliderBehaviorT(bb, id, data_type, (float*)v, *(const float*)v_min, *(const float*)v_max, format, power, flags, out_grab_bb); + case ImGuiDataType_Double: + IM_ASSERT(*(const double*)v_min >= -DBL_MAX/2.0f && *(const double*)v_max <= DBL_MAX/2.0f); + return SliderBehaviorT(bb, id, data_type, (double*)v, *(const double*)v_min, *(const double*)v_max, format, power, flags, out_grab_bb); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + // NB- we don't call ItemSize() yet because we may turn into a text edit box below + if (!ItemAdd(total_bb, id, &frame_bb)) + { + ItemSize(total_bb, style.FramePadding.y); + return false; + } + + // Default format string when passing NULL + // Patch old "%.0f" format string to use "%d", read function comments for more details. + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + if (format == NULL) + format = GDataTypeInfo[data_type].PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) + format = PatchFormatStringFloatToInt(format); + + // Tabbing or CTRL-clicking on Slider turns it into an input box + bool start_text_input = false; + const bool tab_focus_requested = FocusableItemRegister(window, id); + const bool hovered = ItemHoverable(frame_bb, id); + if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + if (tab_focus_requested || g.IO.KeyCtrl || g.NavInputId == id) + { + start_text_input = true; + g.ScalarAsInputTextId = 0; + } + } + if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + { + FocusableItemUnregister(window); + return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); + } + + ItemSize(total_bb, style.FramePadding.y); + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); + + // Slider behavior + ImRect grab_bb; + const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_None, &grab_bb); + if (value_changed) + MarkItemEdited(id); + + // Render grab + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= SliderScalar("##v", data_type, v, v_min, v_max, format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + v = (void*)((char*)v + type_size); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + return value_changed; +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); +} + +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format) +{ + if (format == NULL) + format = "%.0f deg"; + float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); + *v_rad = v_deg * (2*IM_PI) / 360.0f; + return value_changed; +} + +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format) +{ + return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format); +} + +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format); +} + +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format); +} + +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format); +} + +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(frame_bb, id)) + return false; + + // Default format string when passing NULL + // Patch old "%.0f" format string to use "%d", read function comments for more details. + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + if (format == NULL) + format = GDataTypeInfo[data_type].PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) + format = PatchFormatStringFloatToInt(format); + + const bool hovered = ItemHoverable(frame_bb, id); + if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); + + // Slider behavior + ImRect grab_bb; + const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb); + if (value_changed) + MarkItemEdited(id); + + // Render grab + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + // For the vertical slider we allow centered text to overlap the frame padding + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); +} + +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format) +{ + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +//------------------------------------------------------------------------- +// - ImParseFormatFindStart() [Internal] +// - ImParseFormatFindEnd() [Internal] +// - ImParseFormatTrimDecorations() [Internal] +// - ImParseFormatPrecision() [Internal] +// - InputScalarAsWidgetReplacement() [Internal] +// - InputScalar() +// - InputScalarN() +// - InputFloat() +// - InputFloat2() +// - InputFloat3() +// - InputFloat4() +// - InputInt() +// - InputInt2() +// - InputInt3() +// - InputInt4() +// - InputDouble() +//------------------------------------------------------------------------- + +// We don't use strchr() because our strings are usually very short and often start with '%' +const char* ImParseFormatFindStart(const char* fmt) +{ + while (char c = fmt[0]) + { + if (c == '%' && fmt[1] != '%') + return fmt; + else if (c == '%') + fmt++; + fmt++; + } + return fmt; +} + +const char* ImParseFormatFindEnd(const char* fmt) +{ + // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. + if (fmt[0] != '%') + return fmt; + const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A')); + const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a')); + for (char c; (c = *fmt) != 0; fmt++) + { + if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0) + return fmt + 1; + if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0) + return fmt + 1; + } + return fmt; +} + +// Extract the format out of a format string with leading or trailing decorations +// fmt = "blah blah" -> return fmt +// fmt = "%.3f" -> return fmt +// fmt = "hello %.3f" -> return fmt + 6 +// fmt = "%.3f hello" -> return buf written with "%.3f" +const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, int buf_size) +{ + const char* fmt_start = ImParseFormatFindStart(fmt); + if (fmt_start[0] != '%') + return fmt; + const char* fmt_end = ImParseFormatFindEnd(fmt_start); + if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data. + return fmt_start; + ImStrncpy(buf, fmt_start, ImMin((int)(fmt_end + 1 - fmt_start), buf_size)); + return buf; +} + +// Parse display precision back from the display format string +// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. +int ImParseFormatPrecision(const char* fmt, int default_precision) +{ + fmt = ImParseFormatFindStart(fmt); + if (fmt[0] != '%') + return default_precision; + fmt++; + while (*fmt >= '0' && *fmt <= '9') + fmt++; + int precision = INT_MAX; + if (*fmt == '.') + { + fmt = ImAtoi(fmt + 1, &precision); + if (precision < 0 || precision > 99) + precision = default_precision; + } + if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation + precision = -1; + if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX) + precision = -1; + return (precision == INT_MAX) ? default_precision : precision; +} + +// Create text input in place of an active drag/slider (used when doing a CTRL+Click on drag/slider widgets) +// FIXME: Logic is awkward and confusing. This should be reworked to facilitate using in other situations. +bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) + // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id + SetActiveID(g.ScalarAsInputTextId, window); + SetHoveredID(0); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + + char fmt_buf[32]; + char data_buf[32]; + format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf)); + DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, data_ptr, format); + ImStrTrimBlanks(data_buf); + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); + bool value_changed = InputTextEx(label, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); + if (g.ScalarAsInputTextId == 0) // First frame we started displaying the InputText widget + { + IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID + g.ScalarAsInputTextId = g.ActiveId; + SetHoveredID(id); + } + if (value_changed) + return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialText.Data, data_type, data_ptr, NULL); + return false; +} + +// NB: format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "format" argument) +bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_ptr, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + if (format == NULL) + format = GDataTypeInfo[data_type].PrintFmt; + + char buf[64]; + DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, data_ptr, format); + + bool value_changed = false; + if ((extra_flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) + extra_flags |= ImGuiInputTextFlags_CharsDecimal; + extra_flags |= ImGuiInputTextFlags_AutoSelectAll; + + if (step != NULL) + { + const float button_size = GetFrameHeight(); + + BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() + PushID(label); + PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); + if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view + value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialText.Data, data_type, data_ptr, format); + PopItemWidth(); + + // Step buttons + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", ImVec2(button_size, button_size), ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '-', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", ImVec2(button_size, button_size), ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + TextUnformatted(label, FindRenderedTextEnd(label)); + + PopID(); + EndGroup(); + } + else + { + if (InputText(label, buf, IM_ARRAYSIZE(buf), extra_flags)) + value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialText.Data, data_type, data_ptr, format); + } + + return value_changed; +} + +bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= InputScalar("##v", data_type, v, step, step_fast, format, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + v = (void*)((char*)v + type_size); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags extra_flags) +{ + extra_flags |= ImGuiInputTextFlags_CharsScientific; + return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, extra_flags); +} + +bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags extra_flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, extra_flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags extra_flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, extra_flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags extra_flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, extra_flags); +} + +// Prefer using "const char* format" directly, which is more flexible and consistent with other API. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char format[16] = "%f"; + if (decimal_precision >= 0) + ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); + return InputFloat(label, v, step, step_fast, format, extra_flags); +} + +bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char format[16] = "%f"; + if (decimal_precision >= 0) + ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); + return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, extra_flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char format[16] = "%f"; + if (decimal_precision >= 0) + ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); + return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, extra_flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char format[16] = "%f"; + if (decimal_precision >= 0) + ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); + return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, extra_flags); +} +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, extra_flags); +} + +bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", extra_flags); +} + +bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", extra_flags); +} + +bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", extra_flags); +} + +bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags extra_flags) +{ + extra_flags |= ImGuiInputTextFlags_CharsScientific; + return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, extra_flags); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: InputText, InputTextMultiline +//------------------------------------------------------------------------- +// - InputText() +// - InputTextMultiline() +// - InputTextEx() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +{ + int line_count = 0; + const char* s = text_begin; + while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + if (c == '\n') + line_count++; + s--; + if (s[0] != '\n' && s[0] != '\r') + line_count++; + *out_text_end = s; + return line_count; +} + +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) +{ + ImFont* font = GImGui->Font; + const float line_height = GImGui->FontSize; + const float scale = line_height / font->FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + unsigned int c = (unsigned int)(*s++); + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (stop_on_new_line) + break; + continue; + } + if (c == '\r') + continue; + + const float char_width = font->GetCharAdvance((ImWchar)c) * scale; + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) +namespace ImGuiStb +{ + +static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } +static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } +static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } +static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; +static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) +{ + const ImWchar* text = obj->TextW.Data; + const ImWchar* text_remaining = NULL; + const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); + r->x0 = 0.0f; + r->x1 = size.x; + r->baseline_y_delta = size.y; + r->ymin = 0.0f; + r->ymax = size.y; + r->num_chars = (int)(text_remaining - (text + line_start_idx)); +} + +static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } +#ifdef __APPLE__ // FIXME: Move setting to IO structure +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } +#else +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +#endif +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL + +static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) +{ + ImWchar* dst = obj->TextW.Data + pos; + + // We maintain our buffer length in both UTF-8 and wchar formats + obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); + obj->CurLenW -= n; + + // Offset remaining text (FIXME-OPT: Use memmove) + const ImWchar* src = obj->TextW.Data + pos + n; + while (ImWchar c = *src++) + *dst++ = c; + *dst = '\0'; +} + +static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) +{ + const bool is_resizable = (obj->UserFlags & ImGuiInputTextFlags_CallbackResize) != 0; + const int text_len = obj->CurLenW; + IM_ASSERT(pos <= text_len); + + const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); + if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA)) + return false; + + // Grow internal buffer if needed + if (new_text_len + text_len + 1 > obj->TextW.Size) + { + if (!is_resizable) + return false; + IM_ASSERT(text_len < obj->TextW.Size); + obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1); + } + + ImWchar* text = obj->TextW.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); + memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + + obj->CurLenW += new_text_len; + obj->CurLenA += new_text_len_utf8; + obj->TextW[obj->CurLenW] = '\0'; + + return true; +} + +// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) +#define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left +#define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right +#define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up +#define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down +#define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line +#define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line +#define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text +#define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text +#define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor +#define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor +#define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo +#define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo +#define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word +#define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word +#define STB_TEXTEDIT_K_SHIFT 0x20000 + +#define STB_TEXTEDIT_IMPLEMENTATION +#include "imstb_textedit.h" + +} + +void ImGuiInputTextState::OnKeyPressed(int key) +{ + stb_textedit_key(this, &StbState, key); + CursorFollow = true; + CursorAnimReset(); +} + +ImGuiInputTextCallbackData::ImGuiInputTextCallbackData() +{ + memset(this, 0, sizeof(*this)); +} + +// Public API to manipulate UTF-8 text +// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. +void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) +{ + IM_ASSERT(pos + bytes_count <= BufTextLen); + char* dst = Buf + pos; + const char* src = Buf + pos + bytes_count; + while (char c = *src++) + *dst++ = c; + *dst = '\0'; + + if (CursorPos + bytes_count >= pos) + CursorPos -= bytes_count; + else if (CursorPos >= pos) + CursorPos = pos; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; +} + +void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +{ + const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + if (new_text_len + BufTextLen >= BufSize) + { + if (!is_resizable) + return; + + // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the midly similar code (until we remove the U16 buffer alltogether!) + ImGuiContext& g = *GImGui; + ImGuiInputTextState* edit_state = &g.InputTextState; + IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); + IM_ASSERT(Buf == edit_state->TempBuffer.Data); + int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; + edit_state->TempBuffer.reserve(new_buf_size + 1); + Buf = edit_state->TempBuffer.Data; + BufSize = edit_state->BufCapacityA = new_buf_size; + } + + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; + + if (CursorPos >= pos) + CursorPos += new_text_len; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen += new_text_len; +} + +// Return false to discard a character. +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + unsigned int c = *p_char; + + if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) + { + bool pass = false; + pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); + pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); + if (!pass) + return false; + } + + if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. + return false; + + if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)) + { + if (flags & ImGuiInputTextFlags_CharsDecimal) + if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + return false; + + if (flags & ImGuiInputTextFlags_CharsScientific) + if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) + return false; + + if (flags & ImGuiInputTextFlags_CharsHexadecimal) + if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) + return false; + + if (flags & ImGuiInputTextFlags_CharsUppercase) + if (c >= 'a' && c <= 'z') + *p_char = (c += (unsigned int)('A'-'a')); + + if (flags & ImGuiInputTextFlags_CharsNoBlank) + if (ImCharIsBlankW(c)) + return false; + } + + if (flags & ImGuiInputTextFlags_CallbackCharFilter) + { + ImGuiInputTextCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData)); + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventChar = (ImWchar)c; + callback_data.Flags = flags; + callback_data.UserData = user_data; + if (callback(&callback_data) != 0) + return false; + *p_char = callback_data.EventChar; + if (!callback_data.EventChar) + return false; + } + + return true; +} + +// Edit a string of text +// - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". +// This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match +// Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator. +// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. +// - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h +// (FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) +bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + + ImGuiContext& g = *GImGui; + const ImGuiIO& io = g.IO; + const ImGuiStyle& style = g.Style; + + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; + const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; + const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; + if (is_resizable) + IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! + + if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope, + BeginGroup(); + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); + + ImGuiWindow* draw_window = window; + if (is_multiline) + { + ItemAdd(total_bb, id, &frame_bb); + if (!BeginChildFrame(id, frame_bb.GetSize())) + { + EndChildFrame(); + EndGroup(); + return false; + } + draw_window = GetCurrentWindow(); + draw_window->DC.NavLayerActiveMaskNext |= draw_window->DC.NavLayerCurrentMask; // This is to ensure that EndChild() will display a navigation highlight + size.x -= draw_window->ScrollbarSizes.x; + } + else + { + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb)) + return false; + } + const bool hovered = ItemHoverable(frame_bb, id); + if (hovered) + g.MouseCursor = ImGuiMouseCursor_TextInput; + + // Password pushes a temporary font with only a fallback glyph + if (is_password) + { + const ImFontGlyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->DisplayOffset = g.Font->DisplayOffset; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackAdvanceX = glyph->AdvanceX; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } + + // NB: we are only allowed to access 'edit_state' if we are the active widget. + ImGuiInputTextState& edit_state = g.InputTextState; + + const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing + const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); + const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; + + const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.ID == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); + const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard)); + + bool clear_active_id = false; + + bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); + if (focus_requested || user_clicked || user_scrolled || user_nav_input_start) + { + if (g.ActiveId != id) + { + // Start edition + // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int prev_len_w = edit_state.CurLenW; + const int init_buf_len = (int)strlen(buf); + edit_state.TextW.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + edit_state.InitialText.resize(init_buf_len + 1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + memcpy(edit_state.InitialText.Data, buf, init_buf_len + 1); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.TextW.Data, buf_size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + edit_state.CursorAnimReset(); + + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). + const bool recycle_state = (edit_state.ID == id) && (prev_len_w == edit_state.CurLenW); + if (recycle_state) + { + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + edit_state.CursorClamp(); + } + else + { + edit_state.ID = id; + edit_state.ScrollX = 0.0f; + stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); + if (!is_multiline && focus_requested_by_code) + select_all = true; + } + if (flags & ImGuiInputTextFlags_AlwaysInsertMode) + edit_state.StbState.insert_mode = true; + if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) + select_all = true; + } + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory)) + g.ActiveIdAllowNavDirFlags |= ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); + } + else if (io.MouseClicked[0]) + { + // Release focus when we click outside + clear_active_id = true; + } + + bool value_changed = false; + bool enter_pressed = false; + int backup_current_text_length = 0; + + if (g.ActiveId == id) + { + if (!is_editable && !g.ActiveIdIsJustActivated) + { + // When read-only we always use the live data passed to the function + edit_state.TextW.resize(buf_size+1); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.TextW.Data, edit_state.TextW.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); + edit_state.CursorClamp(); + } + + backup_current_text_length = edit_state.CurLenA; + edit_state.BufCapacityA = buf_size; + edit_state.UserFlags = flags; + edit_state.UserCallback = callback; + edit_state.UserCallbackData = callback_user_data; + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + g.WantTextInputNextFrame = 1; + + // Edit in progress + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); + + const bool is_osx = io.ConfigMacOSXBehaviors; + if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0])) + { + edit_state.SelectAll(); + edit_state.SelectedAllMouseLock = true; + } + else if (hovered && is_osx && io.MouseDoubleClicked[0]) + { + // Double-click select a word only, OS X style (by simulating keystrokes) + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + } + else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) + { + if (hovered) + { + stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + edit_state.CursorAnimReset(); + } + } + else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + edit_state.CursorAnimReset(); + edit_state.CursorFollow = true; + } + if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) + edit_state.SelectedAllMouseLock = false; + + if (io.InputCharacters[0]) + { + // Process text input (before we check for Return because using some IME will effectively send a Return?) + // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. + bool ignore_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); + if (!ignore_inputs && is_editable && !user_nav_input_start) + for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++) + { + // Insert character if they pass filtering + unsigned int c = (unsigned int)io.InputCharacters[n]; + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) + edit_state.OnKeyPressed((int)c); + } + + // Consume characters + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + } + } + + bool cancel_edit = false; + if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) + { + // Handle key-presses + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); + const bool is_osx = io.ConfigMacOSXBehaviors; + const bool is_shortcut_key = (is_osx ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl + const bool is_osx_shift_shortcut = is_osx && io.KeySuper && io.KeyShift && !io.KeyCtrl && !io.KeyAlt; + const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl + const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End + const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper; + const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper; + + const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection()); + const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection()); + const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable; + const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && is_editable && is_undoable); + const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && is_editable && is_undoable; + + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) + { + if (!edit_state.HasSelection()) + { + if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); + } + edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + } + else if (IsKeyPressedMap(ImGuiKey_Enter)) + { + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) + { + enter_pressed = clear_active_id = true; + } + else if (is_editable) + { + unsigned int c = '\n'; // Insert new line + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) + edit_state.OnKeyPressed((int)c); + } + } + else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) + edit_state.OnKeyPressed((int)c); + } + else if (IsKeyPressedMap(ImGuiKey_Escape)) + { + clear_active_id = cancel_edit = true; + } + else if (is_undo || is_redo) + { + edit_state.OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO); + edit_state.ClearSelection(); + } + else if (is_shortcut_key && IsKeyPressedMap(ImGuiKey_A)) + { + edit_state.SelectAll(); + edit_state.CursorFollow = true; + } + else if (is_cut || is_copy) + { + // Cut, Copy + if (io.SetClipboardTextFn) + { + const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; + const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; + edit_state.TempBuffer.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(edit_state.TempBuffer.Data, edit_state.TempBuffer.Size, edit_state.TextW.Data+ib, edit_state.TextW.Data+ie); + SetClipboardText(edit_state.TempBuffer.Data); + } + if (is_cut) + { + if (!edit_state.HasSelection()) + edit_state.SelectAll(); + edit_state.CursorFollow = true; + stb_textedit_cut(&edit_state, &edit_state.StbState); + } + } + else if (is_paste) + { + if (const char* clipboard = GetClipboardText()) + { + // Filter pasted buffer + const int clipboard_len = (int)strlen(clipboard); + ImWchar* clipboard_filtered = (ImWchar*)MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + int clipboard_filtered_len = 0; + for (const char* s = clipboard; *s; ) + { + unsigned int c; + s += ImTextCharFromUtf8(&c, s, NULL); + if (c == 0) + break; + if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, callback_user_data)) + continue; + clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; + } + clipboard_filtered[clipboard_filtered_len] = 0; + if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation + { + stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + edit_state.CursorFollow = true; + } + MemFree(clipboard_filtered); + } + } + } + + if (g.ActiveId == id) + { + const char* apply_new_text = NULL; + int apply_new_text_length = 0; + if (cancel_edit) + { + // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. + if (is_editable && strcmp(buf, edit_state.InitialText.Data) != 0) + { + apply_new_text = edit_state.InitialText.Data; + apply_new_text_length = edit_state.InitialText.Size - 1; + } + } + + // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame. + // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage. + bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); + if (apply_edit_back_to_user_buffer) + { + // Apply new value immediately - copy modified buffer back + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. + if (is_editable) + { + edit_state.TempBuffer.resize(edit_state.TextW.Size * 4 + 1); + ImTextStrToUtf8(edit_state.TempBuffer.Data, edit_state.TempBuffer.Size, edit_state.TextW.Data, NULL); + } + + // User callback + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) + { + IM_ASSERT(callback != NULL); + + // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + ImGuiInputTextFlags event_flag = 0; + ImGuiKey event_key = ImGuiKey_COUNT; + if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) + { + event_flag = ImGuiInputTextFlags_CallbackCompletion; + event_key = ImGuiKey_Tab; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_UpArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_DownArrow; + } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + event_flag = ImGuiInputTextFlags_CallbackAlways; + + if (event_flag) + { + ImGuiInputTextCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData)); + callback_data.EventFlag = event_flag; + callback_data.Flags = flags; + callback_data.UserData = callback_user_data; + + callback_data.EventKey = event_key; + callback_data.Buf = edit_state.TempBuffer.Data; + callback_data.BufTextLen = edit_state.CurLenA; + callback_data.BufSize = edit_state.BufCapacityA; + callback_data.BufDirty = false; + + // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) + ImWchar* text = edit_state.TextW.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); + + // Call user code + callback(&callback_data); + + // Read back what user may have modified + IM_ASSERT(callback_data.Buf == edit_state.TempBuffer.Data); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == edit_state.BufCapacityA); + IM_ASSERT(callback_data.Flags == flags); + if (callback_data.CursorPos != utf8_cursor_pos) { edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); edit_state.CursorFollow = true; } + if (callback_data.SelectionStart != utf8_selection_start) { edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end) { edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (callback_data.BufDirty) + { + IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + if (callback_data.BufTextLen > backup_current_text_length && is_resizable) + edit_state.TextW.resize(edit_state.TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.TextW.Data, edit_state.TextW.Size, callback_data.Buf, NULL); + edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() + edit_state.CursorAnimReset(); + } + } + } + + // Will copy result string if modified + if (is_editable && strcmp(edit_state.TempBuffer.Data, buf) != 0) + { + apply_new_text = edit_state.TempBuffer.Data; + apply_new_text_length = edit_state.CurLenA; + } + } + + // Copy result to user buffer + if (apply_new_text) + { + IM_ASSERT(apply_new_text_length >= 0); + if (backup_current_text_length != apply_new_text_length && is_resizable) + { + ImGuiInputTextCallbackData callback_data; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; + callback_data.Flags = flags; + callback_data.Buf = buf; + callback_data.BufTextLen = apply_new_text_length; + callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1); + callback_data.UserData = callback_user_data; + callback(&callback_data); + buf = callback_data.Buf; + buf_size = callback_data.BufSize; + apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1); + IM_ASSERT(apply_new_text_length <= buf_size); + } + + // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. + ImStrncpy(buf, edit_state.TempBuffer.Data, ImMin(apply_new_text_length + 1, buf_size)); + value_changed = true; + } + + // Clear temporary user storage + edit_state.UserFlags = 0; + edit_state.UserCallback = NULL; + edit_state.UserCallbackData = NULL; + } + + // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value) + if (clear_active_id && g.ActiveId == id) + ClearActiveID(); + + // Render + // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. + const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempBuffer.Data : buf; buf = NULL; + + // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line + // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. + // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. + const int buf_display_max_length = 2 * 1024 * 1024; + + if (!is_multiline) + { + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + } + + const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size + ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.f, 0.f); + const bool is_currently_scrolling = (edit_state.ID == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); + if (g.ActiveId == id || is_currently_scrolling) + { + edit_state.CursorAnim += io.DeltaTime; + + // This is going to be messy. We need to: + // - Display the text (this alone can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + const ImWchar* text_begin = edit_state.TextW.Data; + ImVec2 cursor_offset, select_start_offset; + + { + // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. + const ImWchar* searches_input_ptr[2]; + searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; + searches_input_ptr[1] = NULL; + int searches_remaining = 1; + int searches_result_line_number[2] = { -1, -999 }; + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + searches_result_line_number[1] = -1; + searches_remaining++; + } + + // Iterate all lines to find our line numbers + // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. + searches_remaining += is_multiline ? 1 : 0; + int line_count = 0; + //for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++) // FIXME-OPT: Could use this when wchar_t are 16-bits + for (const ImWchar* s = text_begin; *s != 0; s++) + if (*s == '\n') + { + line_count++; + if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + } + line_count++; + if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; + if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; + + // Calculate 2d position by finding the beginning of the line and measuring distance + cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; + cursor_offset.y = searches_result_line_number[0] * g.FontSize; + if (searches_result_line_number[1] >= 0) + { + select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; + select_start_offset.y = searches_result_line_number[1] * g.FontSize; + } + + // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) + if (is_multiline) + text_size = ImVec2(size.x, line_count * g.FontSize); + } + + // Scroll + if (edit_state.CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = size.x * 0.25f; + if (cursor_offset.x < edit_state.ScrollX) + edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); + else if (cursor_offset.x - size.x >= edit_state.ScrollX) + edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); + } + else + { + edit_state.ScrollX = 0.0f; + } + + // Vertical scroll + if (is_multiline) + { + float scroll_y = draw_window->Scroll.y; + if (cursor_offset.y - g.FontSize < scroll_y) + scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - size.y >= scroll_y) + scroll_y = cursor_offset.y - size.y; + draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag + draw_window->Scroll.y = scroll_y; + render_pos.y = draw_window->DC.CursorPos.y; + } + } + edit_state.CursorFollow = false; + const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); + + // Draw selection + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); + + float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); + ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; + for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) + { + if (rect_pos.y > clip_rect.w + g.FontSize) + break; + if (rect_pos.y < clip_rect.y) + { + //p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p); // FIXME-OPT: Could use this when wchar_t are 16-bits + //p = p ? p + 1 : text_selected_end; + while (p < text_selected_end) + if (*p++ == '\n') + break; + } + else + { + ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); + if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); + rect.ClipWith(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.y += g.FontSize; + } + } + + const int buf_display_len = edit_state.CurLenA; + if (is_multiline || buf_display_len < buf_display_max_length) + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); + + // Draw blinking cursor + bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (g.InputTextState.CursorAnim <= 0.0f) || ImFmod(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + if (is_editable) + g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); + } + else + { + // Render text only + const char* buf_end = NULL; + if (is_multiline) + text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width + else + buf_end = buf_display + strlen(buf_display); + if (is_multiline || (buf_end - buf_display) < buf_display_max_length) + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + } + + if (is_multiline) + { + Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line + EndChildFrame(); + EndGroup(); + } + + if (is_password) + PopFont(); + + // Log as text + if (g.LogEnabled && !is_password) + LogRenderedText(&render_pos, buf_display, NULL); + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if (value_changed) + MarkItemEdited(id); + + if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) + return enter_pressed; + else + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +//------------------------------------------------------------------------- +// - ColorEdit3() +// - ColorEdit4() +// - ColorPicker3() +// - RenderColorRectWithAlphaCheckerboard() [Internal] +// - ColorPicker4() +// - ColorButton() +// - SetColorEditOptions() +// - ColorTooltip() [Internal] +// - ColorEditOptionsPopup() [Internal] +// - ColorPickerOptionsPopup() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) +{ + return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha); +} + +// Edit colors components (each component in 0.0f..1.0f range). +// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item. +bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float square_sz = GetFrameHeight(); + const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); + const float w_items_all = CalcItemWidth() - w_extra; + const char* label_display_end = FindRenderedTextEnd(label); + + BeginGroup(); + PushID(label); + + // If we're not showing any slider there's no point in doing any HSV conversions + const ImGuiColorEditFlags flags_untouched = flags; + if (flags & ImGuiColorEditFlags_NoInputs) + flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions; + + // Context menu: display and modify options (before defaults are applied) + if (!(flags & ImGuiColorEditFlags_NoOptions)) + ColorEditOptionsPopup(col, flags); + + // Read stored options + if (!(flags & ImGuiColorEditFlags__InputsMask)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask); + if (!(flags & ImGuiColorEditFlags__DataTypeMask)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask); + if (!(flags & ImGuiColorEditFlags__PickerMask)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask); + flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); + + const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; + const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; + const int components = alpha ? 4 : 3; + + // Convert to the formats we need + float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; + if (flags & ImGuiColorEditFlags_HSV) + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; + + bool value_changed = false; + bool value_changed_as_float = false; + + if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + { + // RGB/HSV 0..255 Sliders + const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + + const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); + const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; + const char* fmt_table_int[3][4] = + { + { "%3d", "%3d", "%3d", "%3d" }, // Short display + { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA + { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA + }; + const char* fmt_table_float[3][4] = + { + { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display + { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA + { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA + }; + const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1; + + PushItemWidth(w_item_one); + for (int n = 0; n < components; n++) + { + if (n > 0) + SameLine(0, style.ItemInnerSpacing.x); + if (n + 1 == components) + PushItemWidth(w_item_last); + if (flags & ImGuiColorEditFlags_Float) + value_changed = value_changed_as_float = value_changed | DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); + else + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context"); + } + PopItemWidth(); + PopItemWidth(); + } + else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + { + // RGB Hexadecimal Input + char buf[64]; + if (alpha) + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255)); + else + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255)); + PushItemWidth(w_items_all); + if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) + { + value_changed = true; + char* p = buf; + while (*p == '#' || ImCharIsBlankA(*p)) + p++; + i[0] = i[1] = i[2] = i[3] = 0; + if (alpha) + sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context"); + PopItemWidth(); + } + + ImGuiWindow* picker_active_window = NULL; + if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) + { + if (!(flags & ImGuiColorEditFlags_NoInputs)) + SameLine(0, style.ItemInnerSpacing.x); + + const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f); + if (ColorButton("##ColorButton", col_v4, flags)) + { + if (!(flags & ImGuiColorEditFlags_NoPicker)) + { + // Store current color and open a picker + g.ColorPickerRef = col_v4; + OpenPopup("picker"); + SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y)); + } + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context"); + + if (BeginPopup("picker")) + { + picker_active_window = g.CurrentWindow; + if (label != label_display_end) + { + TextUnformatted(label, label_display_end); + Spacing(); + } + ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? + value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); + PopItemWidth(); + EndPopup(); + } + } + + if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) + { + SameLine(0, style.ItemInnerSpacing.x); + TextUnformatted(label, label_display_end); + } + + // Convert back + if (picker_active_window == NULL) + { + if (!value_changed_as_float) + for (int n = 0; n < 4; n++) + f[n] = i[n] / 255.0f; + if (flags & ImGuiColorEditFlags_HSV) + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + if (value_changed) + { + col[0] = f[0]; + col[1] = f[1]; + col[2] = f[2]; + if (alpha) + col[3] = f[3]; + } + } + + PopID(); + EndGroup(); + + // Drag and Drop Target + // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test. + if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) + { + memcpy((float*)col, payload->Data, sizeof(float) * 3); + value_changed = true; + } + if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) + { + memcpy((float*)col, payload->Data, sizeof(float) * components); + value_changed = true; + } + EndDragDropTarget(); + } + + // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). + if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window) + window->DC.LastItemId = g.ActiveId; + + if (value_changed) + MarkItemEdited(window->DC.LastItemId); + + return value_changed; +} + +bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) +{ + float col4[4] = { col[0], col[1], col[2], 1.0f }; + if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha)) + return false; + col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; + return true; +} + +static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b) +{ + float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; + int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); + int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); + int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); + return IM_COL32(r, g, b, 0xFF); +} + +// Helper for ColorPicker4() +// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. +// I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether. +void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) + { + ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col)); + ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col)); + window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags); + + int yi = 0; + for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++) + { + float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y); + if (y2 <= y1) + continue; + for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f) + { + float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x); + if (x2 <= x1) + continue; + int rounding_corners_flags_cell = 0; + if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; } + if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; } + rounding_corners_flags_cell &= rounding_corners_flags; + window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell); + } + } + } + else + { + window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags); + } +} + +// Helper for ColorPicker4() +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w) +{ + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE); +} + +// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + ImDrawList* draw_list = window->DrawList; + + ImGuiStyle& style = g.Style; + ImGuiIO& io = g.IO; + + PushID(label); + BeginGroup(); + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + flags |= ImGuiColorEditFlags_NoSmallPreview; + + // Context menu: display and store options. + if (!(flags & ImGuiColorEditFlags_NoOptions)) + ColorPickerOptionsPopup(col, flags); + + // Read stored options + if (!(flags & ImGuiColorEditFlags__PickerMask)) + flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask; + IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected + if (!(flags & ImGuiColorEditFlags_NoOptions)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); + + // Setup + int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4; + bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha); + ImVec2 picker_pos = window->DC.CursorPos; + float square_sz = GetFrameHeight(); + float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars + float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box + float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; + float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; + float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f); + + float backup_initial_col[4]; + memcpy(backup_initial_col, col, components * sizeof(float)); + + float wheel_thickness = sv_picker_size * 0.08f; + float wheel_r_outer = sv_picker_size * 0.50f; + float wheel_r_inner = wheel_r_outer - wheel_thickness; + ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f); + + // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. + float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); + ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point. + ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point. + ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point. + + float H,S,V; + ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V); + + bool value_changed = false, value_changed_h = false, value_changed_sv = false; + + PushItemFlag(ImGuiItemFlags_NoNav, true); + if (flags & ImGuiColorEditFlags_PickerHueWheel) + { + // Hue wheel + SV triangle logic + InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size)); + if (IsItemActive()) + { + ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; + ImVec2 current_off = g.IO.MousePos - wheel_center; + float initial_dist2 = ImLengthSqr(initial_off); + if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1)) + { + // Interactive with Hue wheel + H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f; + if (H < 0.0f) + H += 1.0f; + value_changed = value_changed_h = true; + } + float cos_hue_angle = ImCos(-H * 2.0f * IM_PI); + float sin_hue_angle = ImSin(-H * 2.0f * IM_PI); + if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle))) + { + // Interacting with SV triangle + ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle); + if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)) + current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated); + float uu, vv, ww; + ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww); + V = ImClamp(1.0f - vv, 0.0001f, 1.0f); + S = ImClamp(uu / V, 0.0001f, 1.0f); + value_changed = value_changed_sv = true; + } + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context"); + } + else if (flags & ImGuiColorEditFlags_PickerHueBar) + { + // SV rectangle logic + InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); + if (IsItemActive()) + { + S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1)); + V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + value_changed = value_changed_sv = true; + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context"); + + // Hue bar logic + SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); + InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); + if (IsItemActive()) + { + H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + value_changed = value_changed_h = true; + } + } + + // Alpha bar logic + if (alpha_bar) + { + SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y)); + InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); + if (IsItemActive()) + { + col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + value_changed = true; + } + } + PopItemFlag(); // ImGuiItemFlags_NoNav + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + { + SameLine(0, style.ItemInnerSpacing.x); + BeginGroup(); + } + + if (!(flags & ImGuiColorEditFlags_NoLabel)) + { + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) + { + if ((flags & ImGuiColorEditFlags_NoSidePreview)) + SameLine(0, style.ItemInnerSpacing.x); + TextUnformatted(label, label_display_end); + } + } + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + { + PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); + ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + if ((flags & ImGuiColorEditFlags_NoLabel)) + Text("Current"); + ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)); + if (ref_col != NULL) + { + Text("Original"); + ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]); + if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2))) + { + memcpy(col, ref_col, components * sizeof(float)); + value_changed = true; + } + } + PopItemFlag(); + EndGroup(); + } + + // Convert back color to RGB + if (value_changed_h || value_changed_sv) + ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); + + // R,G,B and H,S,V slider color editor + bool value_changed_fix_hue_wrap = false; + if ((flags & ImGuiColorEditFlags_NoInputs) == 0) + { + PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; + if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0) + if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB)) + { + // FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. + // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) + value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); + value_changed = true; + } + if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0) + value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV); + if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0) + value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX); + PopItemWidth(); + } + + // Try to cancel hue wrap (after ColorEdit4 call), if any + if (value_changed_fix_hue_wrap) + { + float new_H, new_S, new_V; + ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V); + if (new_H <= 0 && H > 0) + { + if (new_V <= 0 && V != new_V) + ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]); + else if (new_S <= 0) + ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]); + } + } + + ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); + ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); + ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f)); + + const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) }; + ImVec2 sv_cursor_pos; + + if (flags & ImGuiColorEditFlags_PickerHueWheel) + { + // Render Hue Wheel + const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). + const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12); + for (int n = 0; n < 6; n++) + { + const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps; + const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps; + const int vert_start_idx = draw_list->VtxBuffer.Size; + draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc); + draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness); + const int vert_end_idx = draw_list->VtxBuffer.Size; + + // Paint colors over existing vertices + ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner); + ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner); + ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]); + } + + // Render Cursor + preview on Hue Wheel + float cos_hue_angle = ImCos(H * 2.0f * IM_PI); + float sin_hue_angle = ImSin(H * 2.0f * IM_PI); + ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f); + float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; + int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32); + draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments); + + // Render SV triangle (rotated according to hue) + ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle); + ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle); + ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle); + ImVec2 uv_white = GetFontTexUvWhitePixel(); + draw_list->PrimReserve(6, 6); + draw_list->PrimVtx(tra, uv_white, hue_color32); + draw_list->PrimVtx(trb, uv_white, hue_color32); + draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE); + draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS); + draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK); + draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS); + draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f); + sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V)); + } + else if (flags & ImGuiColorEditFlags_PickerHueBar) + { + // Render SV Square + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE); + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK); + RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f); + sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much + sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2); + + // Render Hue Bar + for (int i = 0; i < 6; ++i) + draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]); + float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f); + RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); + } + + // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) + float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f; + draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12); + + // Render alpha bar + if (alpha_bar) + { + float alpha = ImSaturate(col[3]); + ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size); + RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); + draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK); + float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f); + RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); + } + + EndGroup(); + + if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0) + value_changed = false; + if (value_changed) + MarkItemEdited(window->DC.LastItemId); + + PopID(); + + return value_changed; +} + +// A little colored square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(desc_id); + float default_size = GetFrameHeight(); + if (size.x == 0.0f) + size.x = default_size; + if (size.y == 0.0f) + size.y = default_size; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + if (flags & ImGuiColorEditFlags_NoAlpha) + flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); + + ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f); + float grid_step = ImMin(size.x, size.y) / 2.99f; + float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); + ImRect bb_inner = bb; + float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. + bb_inner.Expand(off); + if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f) + { + float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f); + RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); + window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); + } + else + { + // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha + ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha; + if (col_source.w < 1.0f) + RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); + else + window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All); + } + RenderNavHighlight(bb, id); + if (g.Style.FrameBorderSize > 0.0f) + RenderFrameBorder(bb.Min, bb.Max, rounding); + else + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border + + // Drag and Drop Source + // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test. + if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource()) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once); + else + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once); + ColorButton(desc_id, col, flags); + SameLine(); + TextUnformatted("Color"); + EndDragDropSource(); + } + + // Tooltip + if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered) + ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); + + if (pressed) + MarkItemEdited(id); + + return pressed; +} + +void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) +{ + ImGuiContext& g = *GImGui; + if ((flags & ImGuiColorEditFlags__InputsMask) == 0) + flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask; + if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0) + flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; + if ((flags & ImGuiColorEditFlags__PickerMask) == 0) + flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; + IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected + g.ColorEditOptions = flags; +} + +// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) +{ + ImGuiContext& g = *GImGui; + + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + BeginTooltipEx(0, true); + + const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; + if (text_end > text) + { + TextUnformatted(text, text_end); + Separator(); + } + + ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); + ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); + SameLine(); + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); + else + Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); + EndTooltip(); +} + +void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) +{ + bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask); + bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); + if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) + return; + ImGuiContext& g = *GImGui; + ImGuiColorEditFlags opts = g.ColorEditOptions; + if (allow_opt_inputs) + { + if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB; + if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV; + if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) != 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX; + } + if (allow_opt_datatype) + { + if (allow_opt_inputs) Separator(); + if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8; + if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float; + } + + if (allow_opt_inputs || allow_opt_datatype) + Separator(); + if (Button("Copy as..", ImVec2(-1,0))) + OpenPopup("Copy"); + if (BeginPopup("Copy")) + { + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + char buf[64]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + if (Selectable(buf)) + SetClipboardText(buf); + ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); + if (Selectable(buf)) + SetClipboardText(buf); + if (flags & ImGuiColorEditFlags_NoAlpha) + ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb); + else + ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca); + if (Selectable(buf)) + SetClipboardText(buf); + EndPopup(); + } + + g.ColorEditOptions = opts; + EndPopup(); +} + +void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags) +{ + bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask); + bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); + if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context")) + return; + ImGuiContext& g = *GImGui; + if (allow_opt_picker) + { + ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function + PushItemWidth(picker_size.x); + for (int picker_type = 0; picker_type < 2; picker_type++) + { + // Draw small/thumbnail version of each picker type (over an invisible button for selection) + if (picker_type > 0) Separator(); + PushID(picker_type); + ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha); + if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; + ImVec2 backup_pos = GetCursorScreenPos(); + if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup + g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask); + SetCursorScreenPos(backup_pos); + ImVec4 dummy_ref_col; + memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4)); + ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags); + PopID(); + } + PopItemWidth(); + } + if (allow_opt_alpha_bar) + { + if (allow_opt_picker) Separator(); + CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); + } + EndPopup(); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +//------------------------------------------------------------------------- +// - TreeNode() +// - TreeNodeV() +// - TreeNodeEx() +// - TreeNodeExV() +// - TreeNodeBehavior() [Internal] +// - TreePush() +// - TreePop() +// - TreeAdvanceToLabelPos() +// - GetTreeNodeToLabelSpacing() +// - SetNextTreeNodeOpen() +// - CollapsingHeader() +//------------------------------------------------------------------------- + +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + return TreeNodeBehavior(window->GetID(label), 0, label, NULL); +} + +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} + +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); +} + +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags, label, NULL); +} + +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) +{ + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; + + // We only write to the tree storage if the user clicks (or explicitly use SetNextTreeNode*** functions) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiStorage* storage = window->DC.StateStorage; + + bool is_open; + if (g.NextTreeNodeOpenCond != 0) + { + if (g.NextTreeNodeOpenCond & ImGuiCond_Always) + { + is_open = g.NextTreeNodeOpenVal; + storage->SetInt(id, is_open); + } + else + { + // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently. + const int stored_value = storage->GetInt(id, -1); + if (stored_value == -1) + { + is_open = g.NextTreeNodeOpenVal; + storage->SetInt(id, is_open); + } + else + { + is_open = stored_value != 0; + } + } + g.NextTreeNodeOpenCond = 0; + } + else + { + is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + } + + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + is_open = true; + + return is_open; +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + // We vertically grow up to current line height up the typical widget height. + const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it + const float frame_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); + if (display_frame) + { + // Framed header expand a little outside the default padding + frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; + frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; + } + + const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); + + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + // (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not) + const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y); + bool is_open = TreeNodeBehaviorIsOpen(id, flags); + + // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child. + // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). + // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero. + if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth); + + bool item_add = ItemAdd(interact_bb, id); + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; + window->DC.LastItemDisplayRect = frame_bb; + + if (!item_add) + { + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; + } + + // Flags that affects opening behavior: + // - 0(default) ..................... single-click anywhere to open + // - OpenOnDoubleClick .............. double-click anywhere to open + // - OpenOnArrow .................... single-click on arrow to open + // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open + ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0); + if (!(flags & ImGuiTreeNodeFlags_Leaf)) + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); + + bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + if (!(flags & ImGuiTreeNodeFlags_Leaf)) + { + bool toggled = false; + if (pressed) + { + toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id); + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + toggled |= g.IO.MouseDoubleClicked[0]; + if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. + toggled = false; + } + + if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open) + { + toggled = true; + NavMoveRequestCancel(); + } + if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority? + { + toggled = true; + NavMoveRequestCancel(); + } + + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(id, is_open); + } + } + if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) + SetItemAllowOverlap(); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); + if (display_frame) + { + // Framed type + RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding); + RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin); + RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); + if (g.LogEnabled) + { + // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. + const char log_prefix[] = "\n##"; + const char log_suffix[] = "##"; + LogRenderedText(&text_pos, log_prefix, log_prefix+3); + RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); + LogRenderedText(&text_pos, log_suffix+1, log_suffix+3); + } + else + { + RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); + } + } + else + { + // Unframed typed for tree nodes + if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) + { + RenderFrame(frame_bb.Min, frame_bb.Max, col, false); + RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin); + } + + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); + else if (!(flags & ImGuiTreeNodeFlags_Leaf)) + RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f); + if (g.LogEnabled) + LogRenderedText(&text_pos, ">"); + RenderText(text_pos, label, label_end, false); + } + + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; +} + +void ImGui::TreePush(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(str_id ? str_id : "#TreePush"); +} + +void ImGui::TreePush(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); +} + +void ImGui::TreePushRawID(ImGuiID id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + window->IDStack.push_back(id); +} + +void ImGui::TreePop() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + Unindent(); + + window->DC.TreeDepth--; + if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) + if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth))) + { + SetNavID(window->IDStack.back(), g.NavLayer); + NavMoveRequestCancel(); + } + window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1; + + IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. + PopID(); +} + +void ImGui::TreeAdvanceToLabelPos() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); +} + +// Horizontal distance preceding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->SkipItems) + return; + g.NextTreeNodeOpenVal = is_open; + g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always; +} + +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label); +} + +bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + if (p_open && !*p_open) + return false; + + ImGuiID id = window->GetID(label); + bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label); + if (p_open) + { + // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + ImGuiContext& g = *GImGui; + ImGuiItemHoveredDataBackup last_item_backup; + float button_radius = g.FontSize * 0.5f; + ImVec2 button_center = ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_radius, window->DC.LastItemRect.GetCenter().y); + if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), button_center, button_radius)) + *p_open = false; + last_item_backup.Restore(); + } + + return is_open; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Selectable +//------------------------------------------------------------------------- +// - Selectable() +//------------------------------------------------------------------------- + +// Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image. +// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped. + PopClipRect(); + + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrentLineTextBaseOffset; + ImRect bb_inner(pos, pos + size); + ItemSize(bb_inner); + + // Fill horizontal space. + ImVec2 window_padding = window->WindowPadding; + float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; + float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); + ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); + ImRect bb(pos, pos + size_draw); + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) + bb.Max.x += window_padding.x; + + // Selectables are tightly packed together, we extend the box to cover spacing between selectable. + float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); + float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); + float spacing_R = style.ItemSpacing.x - spacing_L; + float spacing_D = style.ItemSpacing.y - spacing_U; + bb.Min.x -= spacing_L; + bb.Min.y -= spacing_U; + bb.Max.x += spacing_R; + bb.Max.y += spacing_D; + if (!ItemAdd(bb, (flags & ImGuiSelectableFlags_Disabled) ? 0 : id)) + { + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) + PushColumnClipRect(); + return false; + } + + // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_NoHoldingActiveID) button_flags |= ImGuiButtonFlags_NoHoldingActiveID; + if (flags & ImGuiSelectableFlags_PressedOnClick) button_flags |= ImGuiButtonFlags_PressedOnClick; + if (flags & ImGuiSelectableFlags_PressedOnRelease) button_flags |= ImGuiButtonFlags_PressedOnRelease; + if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; + if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + if (flags & ImGuiSelectableFlags_Disabled) + selected = false; + + // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets) + if (pressed || hovered) + if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) + { + g.NavDisableHighlight = true; + SetNavID(id, window->DC.NavLayerCurrent); + } + if (pressed) + MarkItemEdited(id); + + // Render + if (hovered || selected) + { + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); + } + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) + { + PushColumnClipRect(); + bb.Max.x -= (GetContentRegionMax().x - max_x); + } + + if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderTextClipped(bb_inner.Min, bb.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); + if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); + + // Automatically close popups + if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup)) + CloseCurrentPopup(); + return pressed; +} + +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + if (Selectable(label, *p_selected, flags, size_arg)) + { + *p_selected = !*p_selected; + return true; + } + return false; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ListBox +//------------------------------------------------------------------------- +// - ListBox() +// - ListBoxHeader() +// - ListBoxFooter() +//------------------------------------------------------------------------- + +// FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we want to keep the same signature. +// Helper to calculate the size of a listbox and display a label on the right. +// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty" +bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = GetStyle(); + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy. + + BeginGroup(); + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + BeginChildFrame(id, frame_bb.GetSize()); + return true; +} + +// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature. +bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) +{ + // Size default to hold ~7.25 items. + // We add +25% worth of item height to allow the user to see at a glance if there are more items up/down, without looking at the scrollbar. + // We don't add this extra bit if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. + // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. + if (height_in_items < 0) + height_in_items = ImMin(items_count, 7); + const ImGuiStyle& style = GetStyle(); + float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f); + + // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). + ImVec2 size; + size.x = 0.0f; + size.y = GetTextLineHeightWithSpacing() * height_in_items_f + style.FramePadding.y * 2.0f; + return ListBoxHeader(label, size); +} + +// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature. +void ImGui::ListBoxFooter() +{ + ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow; + const ImRect bb = parent_window->DC.LastItemRect; + const ImGuiStyle& style = GetStyle(); + + EndChildFrame(); + + // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) + // We call SameLine() to restore DC.CurrentLine* data + SameLine(); + parent_window->DC.CursorPos = bb.Min; + ItemSize(bb, style.FramePadding.y); + EndGroup(); +} + +bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items) +{ + const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); + return value_changed; +} + +bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + if (!ListBoxHeader(label, items_count, height_in_items)) + return false; + + // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. + ImGuiContext& g = *GImGui; + bool value_changed = false; + ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + + PushID(i); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + if (item_selected) + SetItemDefaultFocus(); + PopID(); + } + ListBoxFooter(); + if (value_changed) + MarkItemEdited(g.CurrentWindow->DC.LastItemId); + + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: PlotLines, PlotHistogram +//------------------------------------------------------------------------- +// - PlotEx() [Internal] +// - PlotLines() +// - PlotHistogram() +//------------------------------------------------------------------------- + +void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + if (graph_size.x == 0.0f) + graph_size.x = CalcItemWidth(); + if (graph_size.y == 0.0f) + graph_size.y = label_size.y + (style.FramePadding.y * 2); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, 0, &frame_bb)) + return; + const bool hovered = ItemHoverable(inner_bb, 0); + + // Determine scale from values if not specified + if (scale_min == FLT_MAX || scale_max == FLT_MAX) + { + float v_min = FLT_MAX; + float v_max = -FLT_MAX; + for (int i = 0; i < values_count; i++) + { + const float v = values_getter(data, i); + v_min = ImMin(v_min, v); + v_max = ImMax(v_max, v); + } + if (scale_min == FLT_MAX) + scale_min = v_min; + if (scale_max == FLT_MAX) + scale_max = v_max; + } + + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + if (values_count > 0) + { + int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + + // Tooltip on hover + int v_hovered = -1; + if (hovered) + { + const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); + const int v_idx = (int)(t * item_count); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); + const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); + if (plot_type == ImGuiPlotType_Lines) + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + else if (plot_type == ImGuiPlotType_Histogram) + SetTooltip("%d: %8.4g", v_idx, v0); + v_hovered = v_idx; + } + + const float t_step = 1.0f / (float)res_w; + const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); + + float v0 = values_getter(data, (0 + values_offset) % values_count); + float t0 = 0.0f; + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle + float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands + + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + + for (int n = 0; n < res_w; n++) + { + const float t1 = t0 + t_step; + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) ); + + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t)); + if (plot_type == ImGuiPlotType_Lines) + { + window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } + else if (plot_type == ImGuiPlotType_Histogram) + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } + + t0 = t1; + tp0 = tp1; + } + } + + // Text overlay + if (overlay_text) + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); +} + +struct ImGuiPlotArrayGetterData +{ + const float* Values; + int Stride; + + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } +}; + +static float Plot_ArrayGetter(void* data, int idx) +{ + ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; + const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); + return v; +} + +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Value helpers +// Those is not very useful, legacy API. +//------------------------------------------------------------------------- +// - Value() +//------------------------------------------------------------------------- + +void ImGui::Value(const char* prefix, bool b) +{ + Text("%s: %s", prefix, (b ? "true" : "false")); +} + +void ImGui::Value(const char* prefix, int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, unsigned int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, float v, const char* float_format) +{ + if (float_format) + { + char fmt[64]; + ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); + Text(fmt, prefix, v); + } + else + { + Text("%s: %.3f", prefix, v); + } +} + +//------------------------------------------------------------------------- +// [SECTION] MenuItem, BeginMenu, EndMenu, etc. +//------------------------------------------------------------------------- +// - ImGuiMenuColumns [Internal] +// - BeginMainMenuBar() +// - EndMainMenuBar() +// - BeginMenuBar() +// - EndMenuBar() +// - BeginMenu() +// - EndMenu() +// - MenuItem() +//------------------------------------------------------------------------- + +// Helpers for internal use +ImGuiMenuColumns::ImGuiMenuColumns() +{ + Count = 0; + Spacing = Width = NextWidth = 0.0f; + memset(Pos, 0, sizeof(Pos)); + memset(NextWidths, 0, sizeof(NextWidths)); +} + +void ImGuiMenuColumns::Update(int count, float spacing, bool clear) +{ + IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); + Count = count; + Width = NextWidth = 0.0f; + Spacing = spacing; + if (clear) memset(NextWidths, 0, sizeof(NextWidths)); + for (int i = 0; i < Count; i++) + { + if (i > 0 && NextWidths[i] > 0.0f) + Width += Spacing; + Pos[i] = (float)(int)Width; + Width += NextWidths[i]; + NextWidths[i] = 0.0f; + } +} + +float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double +{ + NextWidth = 0.0f; + NextWidths[0] = ImMax(NextWidths[0], w0); + NextWidths[1] = ImMax(NextWidths[1], w1); + NextWidths[2] = ImMax(NextWidths[2], w2); + for (int i = 0; i < 3; i++) + NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); + return ImMax(Width, NextWidth); +} + +float ImGuiMenuColumns::CalcExtraSpace(float avail_w) +{ + return ImMax(0.0f, avail_w - Width); +} + +// For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f)); + SetNextWindowPos(ImVec2(0.0f, 0.0f)); + SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.NextWindowData.MenuBarOffsetMinVal.y + g.FontBaseSize + g.Style.FramePadding.y)); + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; + bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar(); + PopStyleVar(2); + g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); + if (!is_open) + { + End(); + return false; + } + return true; +} + +void ImGui::EndMainMenuBar() +{ + EndMenuBar(); + + // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window + ImGuiContext& g = *GImGui; + if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0) + FocusPreviousWindowIgnoringOne(g.NavWindow); + + End(); +} + +bool ImGui::BeginMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Backup position on layer 0 + PushID("##menubar"); + + // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. + // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. + ImRect bar_rect = window->MenuBarRect(); + ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f)); + clip_rect.ClipWith(window->OuterRectClipped); + PushClipRect(clip_rect.Min, clip_rect.Max, false); + + window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.NavLayerCurrent++; + window->DC.NavLayerCurrentMask <<= 1; + window->DC.MenuBarAppending = true; + AlignTextToFramePadding(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. + if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) + { + ImGuiWindow* nav_earliest_child = g.NavWindow; + while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu)) + nav_earliest_child = nav_earliest_child->ParentWindow; + if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None) + { + // To do so we claim focus back, restore NavId and then process the movement request for yet another frame. + // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost) + IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check + FocusWindow(window); + SetNavIDWithRectRel(window->NavLastIds[1], 1, window->NavRectRel[1]); + g.NavLayer = 1; + g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection. + g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; + NavMoveRequestCancel(); + } + } + + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + PopClipRect(); + PopID(); + window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. + window->DC.GroupStack.back().AdvanceCursor = false; + EndGroup(); // Restore position on layer 0 + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.NavLayerCurrent--; + window->DC.NavLayerCurrentMask >>= 1; + window->DC.MenuBarAppending = false; +} + +bool ImGui::BeginMenu(const char* label, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + + bool pressed; + bool menu_is_open = IsPopupOpen(id); + bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].OpenParentId == window->IDStack.back()); + ImGuiWindow* backed_nav_window = g.NavWindow; + if (menuset_is_open) + g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent) + + // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestWindowPosForPopup). + ImVec2 popup_pos, pos = window->DC.CursorPos; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + // Menu inside an horizontal menu bar + // Selectable extend their highlight by half ItemSpacing in each direction. + // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() + popup_pos = ImVec2(pos.x - 1.0f - (float)(int)(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight()); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + float w = label_size.x; + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + PopStyleVar(); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). + } + else + { + // Menu inside a menu + popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); + float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right); + if (!enabled) PopStyleColor(); + } + + const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id); + if (menuset_is_open) + g.NavWindow = backed_nav_window; + + bool want_open = false, want_close = false; + if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_within_opened_triangle = false; + if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar)) + { + if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) + { + ImRect next_window_rect = next_window->Rect(); + ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; + ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); + moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); + //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug + } + } + + want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); + want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); + + if (g.NavActivateId == id) + { + want_close = menu_is_open; + want_open = !menu_is_open; + } + if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open + { + want_open = true; + NavMoveRequestCancel(); + } + } + else + { + // Menu bar + if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others + { + want_open = true; + } + else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open + { + want_open = true; + NavMoveRequestCancel(); + } + } + + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id)) + ClosePopupToLevel(g.CurrentPopupStack.Size); + + if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) + { + // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. + OpenPopup(label); + return false; + } + + menu_is_open |= want_open; + if (want_open) + OpenPopup(label); + + if (menu_is_open) + { + // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) + SetNextWindowPos(popup_pos, ImGuiCond_Always); + ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus; + if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + flags |= ImGuiWindowFlags_ChildWindow; + menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + } + + return menu_is_open; +} + +void ImGui::EndMenu() +{ + // Nav: When a left move request _within our child menu_ failed, close the menu. + // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs. + // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical) + { + ClosePopupToLevel(g.OpenPopupStack.Size - 1); + NavMoveRequestCancel(); + } + + EndPopup(); +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + + ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | (enabled ? 0 : ImGuiSelectableFlags_Disabled); + bool pressed; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful + // Note that in this situation we render neither the shortcut neither the selected tick mark + float w = label_size.x; + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + pressed = Selectable(label, false, flags, ImVec2(w, 0.0f)); + PopStyleVar(); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). + } + else + { + ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); + float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f)); + if (shortcut_size.x > 0.0f) + { + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); + } + if (selected) + RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f); + } + return pressed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +{ + if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) + { + if (p_selected) + *p_selected = !*p_selected; + return true; + } + return false; +} diff --git a/src/3rdparty/imgui/imstb_rectpack.h b/src/3rdparty/imgui/imstb_rectpack.h new file mode 100644 index 000000000..bedcdbe93 --- /dev/null +++ b/src/3rdparty/imgui/imstb_rectpack.h @@ -0,0 +1,623 @@ +// stb_rect_pack.h - v0.11 - public domain - rectangle packing +// Sean Barrett 2014 +// +// Useful for e.g. packing rectangular textures into an atlas. +// Does not do rotation. +// +// Not necessarily the awesomest packing method, but better than +// the totally naive one in stb_truetype (which is primarily what +// this is meant to replace). +// +// Has only had a few tests run, may have issues. +// +// More docs to come. +// +// No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. +// +// This library currently uses the Skyline Bottom-Left algorithm. +// +// Please note: better rectangle packers are welcome! Please +// implement them to the same API, but with a different init +// function. +// +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// github:IntellectualKitty +// +// Bugfixes / warning fixes +// Jeremy Jaussaud +// +// Version history: +// +// 0.11 (2017-03-03) return packing success/fail result +// 0.10 (2016-10-25) remove cast-away-const to avoid warnings +// 0.09 (2016-08-27) fix compiler warnings +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +// 0.05: added STBRP_ASSERT to allow replacing assert +// 0.04: fixed minor bug in STBRP_LARGE_RECTS support +// 0.01: initial release +// +// LICENSE +// +// See end of file for license information. + +////////////////////////////////////////////////////////////////////////////// +// +// INCLUDE SECTION +// + +#ifndef STB_INCLUDE_STB_RECT_PACK_H +#define STB_INCLUDE_STB_RECT_PACK_H + +#define STB_RECT_PACK_VERSION 1 + +#ifdef STBRP_STATIC +#define STBRP_DEF static +#else +#define STBRP_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct stbrp_context stbrp_context; +typedef struct stbrp_node stbrp_node; +typedef struct stbrp_rect stbrp_rect; + +#ifdef STBRP_LARGE_RECTS +typedef int stbrp_coord; +#else +typedef unsigned short stbrp_coord; +#endif + +STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); +// Assign packed locations to rectangles. The rectangles are of type +// 'stbrp_rect' defined below, stored in the array 'rects', and there +// are 'num_rects' many of them. +// +// Rectangles which are successfully packed have the 'was_packed' flag +// set to a non-zero value and 'x' and 'y' store the minimum location +// on each axis (i.e. bottom-left in cartesian coordinates, top-left +// if you imagine y increasing downwards). Rectangles which do not fit +// have the 'was_packed' flag set to 0. +// +// You should not try to access the 'rects' array from another thread +// while this function is running, as the function temporarily reorders +// the array while it executes. +// +// To pack into another rectangle, you need to call stbrp_init_target +// again. To continue packing into the same rectangle, you can call +// this function again. Calling this multiple times with multiple rect +// arrays will probably produce worse packing results than calling it +// a single time with the full rectangle array, but the option is +// available. +// +// The function returns 1 if all of the rectangles were successfully +// packed and 0 otherwise. + +struct stbrp_rect +{ + // reserved for your use: + int id; + + // input: + stbrp_coord w, h; + + // output: + stbrp_coord x, y; + int was_packed; // non-zero if valid packing + +}; // 16 bytes, nominally + + +STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); +// Initialize a rectangle packer to: +// pack a rectangle that is 'width' by 'height' in dimensions +// using temporary storage provided by the array 'nodes', which is 'num_nodes' long +// +// You must call this function every time you start packing into a new target. +// +// There is no "shutdown" function. The 'nodes' memory must stay valid for +// the following stbrp_pack_rects() call (or calls), but can be freed after +// the call (or calls) finish. +// +// Note: to guarantee best results, either: +// 1. make sure 'num_nodes' >= 'width' +// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' +// +// If you don't do either of the above things, widths will be quantized to multiples +// of small integers to guarantee the algorithm doesn't run out of temporary storage. +// +// If you do #2, then the non-quantized algorithm will be used, but the algorithm +// may run out of temporary storage and be unable to pack some rectangles. + +STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); +// Optionally call this function after init but before doing any packing to +// change the handling of the out-of-temp-memory scenario, described above. +// If you call init again, this will be reset to the default (false). + + +STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); +// Optionally select which packing heuristic the library should use. Different +// heuristics will produce better/worse results for different data sets. +// If you call init again, this will be reset to the default. + +enum +{ + STBRP_HEURISTIC_Skyline_default=0, + STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, + STBRP_HEURISTIC_Skyline_BF_sortHeight +}; + + +////////////////////////////////////////////////////////////////////////////// +// +// the details of the following structures don't matter to you, but they must +// be visible so you can handle the memory allocations for them + +struct stbrp_node +{ + stbrp_coord x,y; + stbrp_node *next; +}; + +struct stbrp_context +{ + int width; + int height; + int align; + int init_mode; + int heuristic; + int num_nodes; + stbrp_node *active_head; + stbrp_node *free_head; + stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' +}; + +#ifdef __cplusplus +} +#endif + +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// IMPLEMENTATION SECTION +// + +#ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT +#include +#define STBRP_SORT qsort +#endif + +#ifndef STBRP_ASSERT +#include +#define STBRP_ASSERT assert +#endif + +#ifdef _MSC_VER +#define STBRP__NOTUSED(v) (void)(v) +#define STBRP__CDECL __cdecl +#else +#define STBRP__NOTUSED(v) (void)sizeof(v) +#define STBRP__CDECL +#endif + +enum +{ + STBRP__INIT_skyline = 1 +}; + +STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) +{ + switch (context->init_mode) { + case STBRP__INIT_skyline: + STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); + context->heuristic = heuristic; + break; + default: + STBRP_ASSERT(0); + } +} + +STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) +{ + if (allow_out_of_mem) + // if it's ok to run out of memory, then don't bother aligning them; + // this gives better packing, but may fail due to OOM (even though + // the rectangles easily fit). @TODO a smarter approach would be to only + // quantize once we've hit OOM, then we could get rid of this parameter. + context->align = 1; + else { + // if it's not ok to run out of memory, then quantize the widths + // so that num_nodes is always enough nodes. + // + // I.e. num_nodes * align >= width + // align >= width / num_nodes + // align = ceil(width/num_nodes) + + context->align = (context->width + context->num_nodes-1) / context->num_nodes; + } +} + +STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) +{ + int i; +#ifndef STBRP_LARGE_RECTS + STBRP_ASSERT(width <= 0xffff && height <= 0xffff); +#endif + + for (i=0; i < num_nodes-1; ++i) + nodes[i].next = &nodes[i+1]; + nodes[i].next = NULL; + context->init_mode = STBRP__INIT_skyline; + context->heuristic = STBRP_HEURISTIC_Skyline_default; + context->free_head = &nodes[0]; + context->active_head = &context->extra[0]; + context->width = width; + context->height = height; + context->num_nodes = num_nodes; + stbrp_setup_allow_out_of_mem(context, 0); + + // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) + context->extra[0].x = 0; + context->extra[0].y = 0; + context->extra[0].next = &context->extra[1]; + context->extra[1].x = (stbrp_coord) width; +#ifdef STBRP_LARGE_RECTS + context->extra[1].y = (1<<30); +#else + context->extra[1].y = 65535; +#endif + context->extra[1].next = NULL; +} + +// find minimum y position if it starts at x1 +static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) +{ + stbrp_node *node = first; + int x1 = x0 + width; + int min_y, visited_width, waste_area; + + STBRP__NOTUSED(c); + + STBRP_ASSERT(first->x <= x0); + + #if 0 + // skip in case we're past the node + while (node->next->x <= x0) + ++node; + #else + STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency + #endif + + STBRP_ASSERT(node->x <= x0); + + min_y = 0; + waste_area = 0; + visited_width = 0; + while (node->x < x1) { + if (node->y > min_y) { + // raise min_y higher. + // we've accounted for all waste up to min_y, + // but we'll now add more waste for everything we've visted + waste_area += visited_width * (node->y - min_y); + min_y = node->y; + // the first time through, visited_width might be reduced + if (node->x < x0) + visited_width += node->next->x - x0; + else + visited_width += node->next->x - node->x; + } else { + // add waste area + int under_width = node->next->x - node->x; + if (under_width + visited_width > width) + under_width = width - visited_width; + waste_area += under_width * (min_y - node->y); + visited_width += under_width; + } + node = node->next; + } + + *pwaste = waste_area; + return min_y; +} + +typedef struct +{ + int x,y; + stbrp_node **prev_link; +} stbrp__findresult; + +static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) +{ + int best_waste = (1<<30), best_x, best_y = (1 << 30); + stbrp__findresult fr; + stbrp_node **prev, *node, *tail, **best = NULL; + + // align to multiple of c->align + width = (width + c->align - 1); + width -= width % c->align; + STBRP_ASSERT(width % c->align == 0); + + node = c->active_head; + prev = &c->active_head; + while (node->x + width <= c->width) { + int y,waste; + y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); + if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL + // bottom left + if (y < best_y) { + best_y = y; + best = prev; + } + } else { + // best-fit + if (y + height <= c->height) { + // can only use it if it first vertically + if (y < best_y || (y == best_y && waste < best_waste)) { + best_y = y; + best_waste = waste; + best = prev; + } + } + } + prev = &node->next; + node = node->next; + } + + best_x = (best == NULL) ? 0 : (*best)->x; + + // if doing best-fit (BF), we also have to try aligning right edge to each node position + // + // e.g, if fitting + // + // ____________________ + // |____________________| + // + // into + // + // | | + // | ____________| + // |____________| + // + // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned + // + // This makes BF take about 2x the time + + if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { + tail = c->active_head; + node = c->active_head; + prev = &c->active_head; + // find first node that's admissible + while (tail->x < width) + tail = tail->next; + while (tail) { + int xpos = tail->x - width; + int y,waste; + STBRP_ASSERT(xpos >= 0); + // find the left position that matches this + while (node->next->x <= xpos) { + prev = &node->next; + node = node->next; + } + STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); + y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); + if (y + height < c->height) { + if (y <= best_y) { + if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { + best_x = xpos; + STBRP_ASSERT(y <= best_y); + best_y = y; + best_waste = waste; + best = prev; + } + } + } + tail = tail->next; + } + } + + fr.prev_link = best; + fr.x = best_x; + fr.y = best_y; + return fr; +} + +static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) +{ + // find best position according to heuristic + stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); + stbrp_node *node, *cur; + + // bail if: + // 1. it failed + // 2. the best node doesn't fit (we don't always check this) + // 3. we're out of memory + if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { + res.prev_link = NULL; + return res; + } + + // on success, create new node + node = context->free_head; + node->x = (stbrp_coord) res.x; + node->y = (stbrp_coord) (res.y + height); + + context->free_head = node->next; + + // insert the new node into the right starting point, and + // let 'cur' point to the remaining nodes needing to be + // stiched back in + + cur = *res.prev_link; + if (cur->x < res.x) { + // preserve the existing one, so start testing with the next one + stbrp_node *next = cur->next; + cur->next = node; + cur = next; + } else { + *res.prev_link = node; + } + + // from here, traverse cur and free the nodes, until we get to one + // that shouldn't be freed + while (cur->next && cur->next->x <= res.x + width) { + stbrp_node *next = cur->next; + // move the current node to the free list + cur->next = context->free_head; + context->free_head = cur; + cur = next; + } + + // stitch the list back in + node->next = cur; + + if (cur->x < res.x + width) + cur->x = (stbrp_coord) (res.x + width); + +#ifdef _DEBUG + cur = context->active_head; + while (cur->x < context->width) { + STBRP_ASSERT(cur->x < cur->next->x); + cur = cur->next; + } + STBRP_ASSERT(cur->next == NULL); + + { + int count=0; + cur = context->active_head; + while (cur) { + cur = cur->next; + ++count; + } + cur = context->free_head; + while (cur) { + cur = cur->next; + ++count; + } + STBRP_ASSERT(count == context->num_nodes+2); + } +#endif + + return res; +} + +static int STBRP__CDECL rect_height_compare(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + if (p->h > q->h) + return -1; + if (p->h < q->h) + return 1; + return (p->w > q->w) ? -1 : (p->w < q->w); +} + +static int STBRP__CDECL rect_original_order(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); +} + +#ifdef STBRP_LARGE_RECTS +#define STBRP__MAXVAL 0xffffffff +#else +#define STBRP__MAXVAL 0xffff +#endif + +STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) +{ + int i, all_rects_packed = 1; + + // we use the 'was_packed' field internally to allow sorting/unsorting + for (i=0; i < num_rects; ++i) { + rects[i].was_packed = i; + #ifndef STBRP_LARGE_RECTS + STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff); + #endif + } + + // sort according to heuristic + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); + + for (i=0; i < num_rects; ++i) { + if (rects[i].w == 0 || rects[i].h == 0) { + rects[i].x = rects[i].y = 0; // empty rect needs no space + } else { + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) { + rects[i].x = (stbrp_coord) fr.x; + rects[i].y = (stbrp_coord) fr.y; + } else { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } + } + } + + // unsort + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); + + // set was_packed flags and all_rects_packed status + for (i=0; i < num_rects; ++i) { + rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); + if (!rects[i].was_packed) + all_rects_packed = 0; + } + + // return the all_rects_packed status + return all_rects_packed; +} +#endif + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/3rdparty/imgui/imstb_textedit.h b/src/3rdparty/imgui/imstb_textedit.h new file mode 100644 index 000000000..75eba3073 --- /dev/null +++ b/src/3rdparty/imgui/imstb_textedit.h @@ -0,0 +1,1409 @@ +// [ImGui] this is a slightly modified version of stb_textedit.h 1.12. Those changes would need to be pushed into nothings/stb +// [ImGui] - 2018-06: fixed undo/redo after pasting large amount of text (over 32 kb). Redo will still fail when undo buffers are exhausted, but text won't be corrupted (see nothings/stb issue #620) +// [ImGui] - 2018-06: fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +// [ImGui] - fixed some minor warnings + +// stb_textedit.h - v1.12 - public domain - Sean Barrett +// Development of this library was sponsored by RAD Game Tools +// +// This C header file implements the guts of a multi-line text-editing +// widget; you implement display, word-wrapping, and low-level string +// insertion/deletion, and stb_textedit will map user inputs into +// insertions & deletions, plus updates to the cursor position, +// selection state, and undo state. +// +// It is intended for use in games and other systems that need to build +// their own custom widgets and which do not have heavy text-editing +// requirements (this library is not recommended for use for editing large +// texts, as its performance does not scale and it has limited undo). +// +// Non-trivial behaviors are modelled after Windows text controls. +// +// +// LICENSE +// +// See end of file for license information. +// +// +// DEPENDENCIES +// +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. +// +// +// VERSION HISTORY +// +// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash +// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield +// 1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual +// 1.9 (2016-08-27) customizable move-by-word +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X +// 1.4 (2014-08-17) fix signed/unsigned warnings +// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +// 1.2 (2014-05-27) fix some RAD types that had crept into the new code +// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +// 1.0 (2012-07-26) improve documentation, initial public release +// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +// 0.2 (2011-11-28) fixes to undo/redo +// 0.1 (2010-07-08) initial version +// +// ADDITIONAL CONTRIBUTORS +// +// Ulf Winklemann: move-by-word in 1.1 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut +// Dan Thompson +// +// USAGE +// +// This file behaves differently depending on what symbols you define +// before including it. +// +// +// Header-file mode: +// +// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, +// it will operate in "header file" mode. In this mode, it declares a +// single public symbol, STB_TexteditState, which encapsulates the current +// state of a text widget (except for the string, which you will store +// separately). +// +// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a +// primitive type that defines a single character (e.g. char, wchar_t, etc). +// +// To save space or increase undo-ability, you can optionally define the +// following things that are used by the undo system: +// +// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// If you don't define these, they are set to permissive types and +// moderate sizes. The undo system does no memory allocations, so +// it grows STB_TexteditState by the worst-case storage which is (in bytes): +// +// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT +// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT +// +// +// Implementation mode: +// +// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it +// will compile the implementation of the text edit widget, depending +// on a large number of symbols which must be defined before the include. +// +// The implementation is defined only as static functions. You will then +// need to provide your own APIs in the same file which will access the +// static functions. +// +// The basic concept is that you provide a "string" object which +// behaves like an array of characters. stb_textedit uses indices to +// refer to positions in the string, implicitly representing positions +// in the displayed textedit. This is true for both plain text and +// rich text; even with rich text stb_truetype interacts with your +// code as if there was an array of all the displayed characters. +// +// Symbols that must be the same in header-file and implementation mode: +// +// STB_TEXTEDIT_CHARTYPE the character type +// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// Symbols you must define for implementation mode: +// +// STB_TEXTEDIT_STRING the type of object representing a string being edited, +// typically this is a wrapper object with other data you need +// +// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters +// starting from character #n (see discussion below) +// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +// to the xpos of the i+1'th char for a line of characters +// starting at character #n (i.e. accounts for kerning +// with previous char) +// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character +// (return type is int, -1 means not valid to insert) +// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based +// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +// as manually wordwrapping for end-of-line positioning +// +// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// +// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +// +// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +// STB_TEXTEDIT_K_UP keyboard input to move cursor up +// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME +// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END +// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME +// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END +// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +// STB_TEXTEDIT_K_UNDO keyboard input to perform undo +// STB_TEXTEDIT_K_REDO keyboard input to perform redo +// +// Optional: +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text +// +// Todo: +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +// +// Keyboard input must be encoded as a single integer value; e.g. a character code +// and some bitflags that represent shift states. to simplify the interface, SHIFT must +// be a bitflag, so we can test the shifted state of cursor movements to allow selection, +// i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// +// You can encode other things, such as CONTROL or ALT, in additional bits, and +// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, +// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN +// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, +// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the +// API below. The control keys will only match WM_KEYDOWN events because of the +// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN +// bit so it only decodes WM_CHAR events. +// +// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +// row of characters assuming they start on the i'th character--the width and +// the height and the number of characters consumed. This allows this library +// to traverse the entire layout incrementally. You need to compute word-wrapping +// here. +// +// Each textfield keeps its own insert mode state, which is not how normal +// applications work. To keep an app-wide insert mode, update/copy the +// "insert_mode" field of STB_TexteditState before/after calling API functions. +// +// API +// +// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +// +// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) +// +// Each of these functions potentially updates the string and updates the +// state. +// +// initialize_state: +// set the textedit state to a known good default state when initially +// constructing the textedit. +// +// click: +// call this with the mouse x,y on a mouse down; it will update the cursor +// and reset the selection start/end to the cursor point. the x,y must +// be relative to the text widget, with (0,0) being the top left. +// +// drag: +// call this with the mouse x,y on a mouse drag/up; it will update the +// cursor and the selection end point +// +// cut: +// call this to delete the current selection; returns true if there was +// one. you should FIRST copy the current selection to the system paste buffer. +// (To copy, just copy the current selection out of the string yourself.) +// +// paste: +// call this to paste text at the current cursor point or over the current +// selection if there is one. +// +// key: +// call this for keyboard inputs sent to the textfield. you can use it +// for "key down" events or for "translated" key events. if you need to +// do both (as in Win32), or distinguish Unicode characters from control +// inputs, set a high bit to distinguish the two; then you can define the +// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit +// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is +// clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to +// anything other type you wante before including. +// +// +// When rendering, you can read the cursor position and selection state from +// the STB_TexteditState. +// +// +// Notes: +// +// This is designed to be usable in IMGUI, so it allows for the possibility of +// running in an IMGUI that has NOT cached the multi-line layout. For this +// reason, it provides an interface that is compatible with computing the +// layout incrementally--we try to make sure we make as few passes through +// as possible. (For example, to locate the mouse pointer in the text, we +// could define functions that return the X and Y positions of characters +// and binary search Y and then X, but if we're doing dynamic layout this +// will run the layout algorithm many times, so instead we manually search +// forward in one pass. Similar logic applies to e.g. up-arrow and +// down-arrow movement.) +// +// If it's run in a widget that *has* cached the layout, then this is less +// efficient, but it's not horrible on modern computers. But you wouldn't +// want to edit million-line files with it. + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Header-file mode +//// +//// + +#ifndef INCLUDE_STB_TEXTEDIT_H +#define INCLUDE_STB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////// +// +// STB_TexteditState +// +// Definition of STB_TexteditState which you should store +// per-textfield; it includes cursor position, selection state, +// and undo state. +// + +#ifndef STB_TEXTEDIT_UNDOSTATECOUNT +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#endif +#ifndef STB_TEXTEDIT_UNDOCHARCOUNT +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 +#endif +#ifndef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_CHARTYPE int +#endif +#ifndef STB_TEXTEDIT_POSITIONTYPE +#define STB_TEXTEDIT_POSITIONTYPE int +#endif + +typedef struct +{ + // private data + STB_TEXTEDIT_POSITIONTYPE where; + STB_TEXTEDIT_POSITIONTYPE insert_length; + STB_TEXTEDIT_POSITIONTYPE delete_length; + int char_storage; +} StbUndoRecord; + +typedef struct +{ + // private data + StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; + STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; + short undo_point, redo_point; + int undo_char_point, redo_char_point; +} StbUndoState; + +typedef struct +{ + ///////////////////// + // + // public data + // + + int cursor; + // position of the text cursor within the string + + int select_start; // selection start point + int select_end; + // selection start and end point in characters; if equal, no selection. + // note that start may be less than or greater than end (e.g. when + // dragging the mouse, start is where the initial click was, and you + // can drag in either direction) + + unsigned char insert_mode; + // each textfield keeps its own insert mode state. to keep an app-wide + // insert mode, copy this value in/out of the app state + + ///////////////////// + // + // private data + // + unsigned char cursor_at_end_of_line; // not implemented yet + unsigned char initialized; + unsigned char has_preferred_x; + unsigned char single_line; + unsigned char padding1, padding2, padding3; + float preferred_x; // this determines where the cursor up/down tries to seek to along x + StbUndoState undostate; +} STB_TexteditState; + + +//////////////////////////////////////////////////////////////////////// +// +// StbTexteditRow +// +// Result of layout query, used by stb_textedit to determine where +// the text in each row is. + +// result of layout query +typedef struct +{ + float x0,x1; // starting x location, end x location (allows for align=right, etc) + float baseline_y_delta; // position of baseline relative to previous row's baseline + float ymin,ymax; // height of row above and below baseline + int num_chars; +} StbTexteditRow; +#endif //INCLUDE_STB_TEXTEDIT_H + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Implementation mode +//// +//// + + +// implementation isn't include-guarded, since it might have indirectly +// included just the "header" portion +#ifdef STB_TEXTEDIT_IMPLEMENTATION + +#ifndef STB_TEXTEDIT_memmove +#include +#define STB_TEXTEDIT_memmove memmove +#endif + + +///////////////////////////////////////////////////////////////////////////// +// +// Mouse input handling +// + +// traverse the layout to locate the nearest character to a display position +static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) +{ + StbTexteditRow r; + int n = STB_TEXTEDIT_STRINGLEN(str); + float base_y = 0, prev_x; + int i=0, k; + + r.x0 = r.x1 = 0; + r.ymin = r.ymax = 0; + r.num_chars = 0; + + // search rows to find one that straddles 'y' + while (i < n) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (r.num_chars <= 0) + return n; + + if (i==0 && y < base_y + r.ymin) + return 0; + + if (y < base_y + r.ymax) + break; + + i += r.num_chars; + base_y += r.baseline_y_delta; + } + + // below all text, return 'after' last character + if (i >= n) + return n; + + // check if it's before the beginning of the line + if (x < r.x0) + return i; + + // check if it's before the end of the line + if (x < r.x1) { + // search characters in row for one that straddles 'x' + prev_x = r.x0; + for (k=0; k < r.num_chars; ++k) { + float w = STB_TEXTEDIT_GETWIDTH(str, i, k); + if (x < prev_x+w) { + if (x < prev_x+w/2) + return k+i; + else + return k+i+1; + } + prev_x += w; + } + // shouldn't happen, but if it does, fall through to end-of-line case + } + + // if the last character is a newline, return that. otherwise return 'after' the last character + if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) + return i+r.num_chars-1; + else + return i+r.num_chars; +} + +// API click: on mouse down, move the cursor to the clicked location, and reset the selection +static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse + // goes off the top or bottom of the text + if( state->single_line ) + { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + state->cursor = stb_text_locate_coord(str, x, y); + state->select_start = state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; +} + +// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location +static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + int p = 0; + + // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse + // goes off the top or bottom of the text + if( state->single_line ) + { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + if (state->select_start == state->select_end) + state->select_start = state->cursor; + + p = stb_text_locate_coord(str, x, y); + state->cursor = state->select_end = p; +} + +///////////////////////////////////////////////////////////////////////////// +// +// Keyboard input handling +// + +// forward declarations +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); + +typedef struct +{ + float x,y; // position of n'th character + float height; // height of line + int first_char, length; // first char of row, and length + int prev_first; // first char of previous row +} StbFindState; + +// find the x/y location of a character, and remember info about the previous row in +// case we get a move-up event (for page up, we'll have to rescan) +static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) +{ + StbTexteditRow r; + int prev_start = 0; + int z = STB_TEXTEDIT_STRINGLEN(str); + int i=0, first; + + if (n == z) { + // if it's at the end, then find the last line -- simpler than trying to + // explicitly handle this case in the regular code + if (single_line) { + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + } else { + find->y = 0; + find->x = 0; + find->height = 1; + while (i < z) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + prev_start = i; + i += r.num_chars; + } + find->first_char = i; + find->length = 0; + find->prev_first = prev_start; + } + return; + } + + // search rows to find the one that straddles character n + find->y = 0; + + for(;;) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (n < i + r.num_chars) + break; + prev_start = i; + i += r.num_chars; + find->y += r.baseline_y_delta; + } + + find->first_char = first = i; + find->length = r.num_chars; + find->height = r.ymax - r.ymin; + find->prev_first = prev_start; + + // now scan to find xpos + find->x = r.x0; + i = 0; + for (i=0; first+i < n; ++i) + find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); +} + +#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) + +// make the selection/cursor state valid if client altered the string +static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start > n) state->select_start = n; + if (state->select_end > n) state->select_end = n; + // if clamping forced them to be equal, move the cursor to match + if (state->select_start == state->select_end) + state->cursor = state->select_start; + } + if (state->cursor > n) state->cursor = n; +} + +// delete characters while updating undo +static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) +{ + stb_text_makeundo_delete(str, state, where, len); + STB_TEXTEDIT_DELETECHARS(str, where, len); + state->has_preferred_x = 0; +} + +// delete the section +static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + stb_textedit_clamp(str, state); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start < state->select_end) { + stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); + state->select_end = state->cursor = state->select_start; + } else { + stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); + state->select_start = state->cursor = state->select_end; + } + state->has_preferred_x = 0; + } +} + +// canoncialize the selection so start <= end +static void stb_textedit_sortselection(STB_TexteditState *state) +{ + if (state->select_end < state->select_start) { + int temp = state->select_end; + state->select_end = state->select_start; + state->select_start = temp; + } +} + +// move cursor to first character of selection +static void stb_textedit_move_to_first(STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + state->cursor = state->select_start; + state->select_end = state->select_start; + state->has_preferred_x = 0; + } +} + +// move cursor to last character of selection +static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->select_start = state->select_end; + state->has_preferred_x = 0; + } +} + +#ifdef STB_TEXTEDIT_IS_SPACE +static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) +{ + return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; +} + +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) +{ + --c; // always move at least one character + while( c >= 0 && !is_word_boundary( str, c ) ) + --c; + + if( c < 0 ) + c = 0; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif + +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c ) +{ + const int len = STB_TEXTEDIT_STRINGLEN(str); + ++c; // always move at least one character + while( c < len && !is_word_boundary( str, c ) ) + ++c; + + if( c > len ) + c = len; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + +#endif + +// update selection and cursor to match each other +static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) +{ + if (!STB_TEXT_HAS_SELECTION(state)) + state->select_start = state->select_end = state->cursor; + else + state->cursor = state->select_end; +} + +// API cut: delete selection +static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_delete_selection(str,state); // implicity clamps + state->has_preferred_x = 0; + return 1; + } + return 0; +} + +// API paste: replace existing selection with passed-in text +static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +{ + // if there's a selection, the paste should delete it + stb_textedit_clamp(str, state); + stb_textedit_delete_selection(str,state); + // try to insert the characters + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { + stb_text_makeundo_insert(state, state->cursor, len); + state->cursor += len; + state->has_preferred_x = 0; + return 1; + } + // remove the undo since we didn't actually insert the characters + if (state->undostate.undo_point) + --state->undostate.undo_point; + return 0; +} + +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + +// API key: process a keyboard input +static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) +{ +retry: + switch (key) { + default: { + int c = STB_TEXTEDIT_KEYTOTEXT(key); + if (c > 0) { + STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; + + // can't add newline in single-line mode + if (c == '\n' && state->single_line) + break; + + if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { + stb_text_makeundo_replace(str, state, state->cursor, 1, 1); + STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + ++state->cursor; + state->has_preferred_x = 0; + } + } else { + stb_textedit_delete_selection(str,state); // implicity clamps + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + stb_text_makeundo_insert(state, state->cursor, 1); + ++state->cursor; + state->has_preferred_x = 0; + } + } + } + break; + } + +#ifdef STB_TEXTEDIT_K_INSERT + case STB_TEXTEDIT_K_INSERT: + state->insert_mode = !state->insert_mode; + break; +#endif + + case STB_TEXTEDIT_K_UNDO: + stb_text_undo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_REDO: + stb_text_redo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT: + // if currently there's a selection, move cursor to start of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else + if (state->cursor > 0) + --state->cursor; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_RIGHT: + // if currently there's a selection, move cursor to end of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else + ++state->cursor; + stb_textedit_clamp(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + // move selection left + if (state->select_end > 0) + --state->select_end; + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_MOVEWORDLEFT + case STB_TEXTEDIT_K_WORDLEFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + + case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + // move selection right + ++state->select_end; + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_DOWN: + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + + if (state->single_line) { + // on windows, up&down in single-line behave like left&right + key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str,state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + // now find character position down a row + if (find.length) { + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; + float x; + int start = find.first_char + find.length; + state->cursor = start; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + } + break; + } + + case STB_TEXTEDIT_K_UP: + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + + if (state->single_line) { + // on windows, up&down become left&right + key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + // can only go up if there's a previous row + if (find.prev_first != find.first_char) { + // now find character position up a row + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; + float x; + state->cursor = find.prev_first; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + } + break; + } + + case STB_TEXTEDIT_K_DELETE: + case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->cursor < n) + stb_textedit_delete(str, state, state->cursor, 1); + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_BACKSPACE: + case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + stb_textedit_clamp(str, state); + if (state->cursor > 0) { + stb_textedit_delete(str, state, state->cursor-1, 1); + --state->cursor; + } + } + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif + case STB_TEXTEDIT_K_TEXTSTART: + state->cursor = state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif + case STB_TEXTEDIT_K_TEXTEND: + state->cursor = STB_TEXTEDIT_STRINGLEN(str); + state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); + state->has_preferred_x = 0; + break; + + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif + case STB_TEXTEDIT_K_LINESTART: + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif + case STB_TEXTEDIT_K_LINEEND: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->has_preferred_x = 0; + break; + } + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + } + +// @TODO: +// STB_TEXTEDIT_K_PGUP - move cursor up a page +// STB_TEXTEDIT_K_PGDOWN - move cursor down a page + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// Undo processing +// +// @OPTIMIZE: the undo/redo buffer should be circular + +static void stb_textedit_flush_redo(StbUndoState *state) +{ + state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; +} + +// discard the oldest entry in the undo list +static void stb_textedit_discard_undo(StbUndoState *state) +{ + if (state->undo_point > 0) { + // if the 0th undo state has characters, clean those up + if (state->undo_rec[0].char_storage >= 0) { + int n = state->undo_rec[0].insert_length, i; + // delete n characters from all other records + state->undo_char_point -= n; + STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i=0; i < state->undo_point; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it + } + --state->undo_point; + STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0]))); + } +} + +// discard the oldest entry in the redo list--it's bad if this +// ever happens, but because undo & redo have to store the actual +// characters in different cases, the redo character buffer can +// fill up even though the undo buffer didn't +static void stb_textedit_discard_redo(StbUndoState *state) +{ + int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; + + if (state->redo_point <= k) { + // if the k'th undo state has characters, clean those up + if (state->undo_rec[k].char_storage >= 0) { + int n = state->undo_rec[k].insert_length, i; + // move the remaining redo character data to the end of the buffer + state->redo_char_point += n; + STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + // adjust the position of all the other records to account for above memmove + for (i=state->redo_point; i < k; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage += n; + } + // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, (size_t) ((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); + // now move redo_point to point to the new one + ++state->redo_point; + } +} + +static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) +{ + // any time we create a new undo record, we discard redo + stb_textedit_flush_redo(state); + + // if we have no free records, we have to make room, by sliding the + // existing records down + if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + stb_textedit_discard_undo(state); + + // if the characters to store won't possibly fit in the buffer, we can't undo + if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { + state->undo_point = 0; + state->undo_char_point = 0; + return NULL; + } + + // if we don't have enough free characters in the buffer, we have to make room + while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) + stb_textedit_discard_undo(state); + + return &state->undo_rec[state->undo_point++]; +} + +static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) +{ + StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); + if (r == NULL) + return NULL; + + r->where = pos; + r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len; + r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len; + + if (insert_len == 0) { + r->char_storage = -1; + return NULL; + } else { + r->char_storage = state->undo_char_point; + state->undo_char_point += insert_len; + return &state->undo_char[r->char_storage]; + } +} + +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord u, *r; + if (s->undo_point == 0) + return; + + // we need to do two things: apply the undo record, and create a redo record + u = s->undo_rec[s->undo_point-1]; + r = &s->undo_rec[s->redo_point-1]; + r->char_storage = -1; + + r->insert_length = u.delete_length; + r->delete_length = u.insert_length; + r->where = u.where; + + if (u.delete_length) { + // if the undo record says to delete characters, then the redo record will + // need to re-insert the characters that get deleted, so we need to store + // them. + + // there are three cases: + // there's enough room to store the characters + // characters stored for *redoing* don't leave room for redo + // characters stored for *undoing* don't leave room for redo + // if the last is true, we have to bail + + if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { + // the undo records take up too much character space; there's no space to store the redo characters + r->insert_length = 0; + } else { + int i; + + // there's definitely room to store the characters eventually + while (s->undo_char_point + u.delete_length > s->redo_char_point) { + // should never happen: + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + // there's currently not enough room, so discard a redo record + stb_textedit_discard_redo(s); + } + r = &s->undo_rec[s->redo_point-1]; + + r->char_storage = s->redo_char_point - u.delete_length; + s->redo_char_point = s->redo_char_point - u.delete_length; + + // now save the characters + for (i=0; i < u.delete_length; ++i) + s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); + } + + // now we can carry out the deletion + STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); + } + + // check type of recorded action: + if (u.insert_length) { + // easy case: was a deletion, so we need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); + s->undo_char_point -= u.insert_length; + } + + state->cursor = u.where + u.insert_length; + + s->undo_point--; + s->redo_point--; +} + +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord *u, r; + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + + // we need to do two things: apply the redo record, and create an undo record + u = &s->undo_rec[s->undo_point]; + r = s->undo_rec[s->redo_point]; + + // we KNOW there must be room for the undo record, because the redo record + // was derived from an undo record + + u->delete_length = r.insert_length; + u->insert_length = r.delete_length; + u->where = r.where; + u->char_storage = -1; + + if (r.delete_length) { + // the redo record requires us to delete characters, so the undo record + // needs to store the characters + + if (s->undo_char_point + u->insert_length > s->redo_char_point) { + u->insert_length = 0; + u->delete_length = 0; + } else { + int i; + u->char_storage = s->undo_char_point; + s->undo_char_point = s->undo_char_point + u->insert_length; + + // now save the characters + for (i=0; i < u->insert_length; ++i) + s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); + } + + STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); + } + + if (r.insert_length) { + // easy case: need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + s->redo_char_point += r.insert_length; + } + + state->cursor = r.where + r.insert_length; + + s->undo_point++; + s->redo_point++; +} + +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) +{ + stb_text_createundo(&state->undostate, where, 0, length); +} + +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); + if (p) { + for (i=0; i < length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); + if (p) { + for (i=0; i < old_length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +// reset the state to default +static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) +{ + state->undostate.undo_point = 0; + state->undostate.undo_char_point = 0; + state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; + state->select_end = state->select_start = 0; + state->cursor = 0; + state->has_preferred_x = 0; + state->preferred_x = 0; + state->cursor_at_end_of_line = 0; + state->initialized = 1; + state->single_line = (unsigned char) is_single_line; + state->insert_mode = 0; +} + +// API initialize +static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +{ + stb_textedit_clear_state(state, is_single_line); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) +{ + return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif//STB_TEXTEDIT_IMPLEMENTATION + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/3rdparty/imgui/imstb_truetype.h b/src/3rdparty/imgui/imstb_truetype.h new file mode 100644 index 000000000..c8734486b --- /dev/null +++ b/src/3rdparty/imgui/imstb_truetype.h @@ -0,0 +1,4854 @@ +// stb_truetype.h - v1.19 - public domain +// authored from 2009-2016 by Sean Barrett / RAD Game Tools +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// render glyphs to one-channel SDF bitmaps (signed-distance field/function) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// Daniel Ribeiro Maciel: basic GPOS-based kerning +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// Imanol Celaya +// Daniel Ribeiro Maciel +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket Fabian "ryg" Giesen +// Cass Everitt Martins Mozeiko +// stoiko (Haemimont Games) Cap Petschulat +// Brian Hook Omar Cornut +// Walter van Niftrik github:aloucks +// David Gow Peter LaValle +// David Given Sergey Popov +// Ivan-Assen Ivanov Giumo X. Clanjor +// Anthony Pesch Higor Euripedes +// Johan Duparc Thomas Fields +// Hou Qiming Derek Vinyard +// Rob Loach Cort Stratton +// Kenney Phillis Jr. github:oyvindjam +// Brian Costabile github:vassvik +// +// VERSION HISTORY +// +// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// See end of file for license information. +// +// USAGE +// +// Include this file in whatever places neeed to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversampling() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetFontVMetricsOS2() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// DETAILED USAGE: +// +// Scale: +// Select how high you want the font to be, in points or pixels. +// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute +// a scale factor SF that will be used by all other functions. +// +// Baseline: +// You need to select a y-coordinate that is the baseline of where +// your text will appear. Call GetFontBoundingBox to get the baseline-relative +// bounding box for all characters. SF*-y0 will be the distance in pixels +// that the worst-case character could extend above the baseline, so if +// you want the top edge of characters to appear at the top of the +// screen where y=0, then you would set the baseline to SF*-y0. +// +// Current point: +// Set the current point where the first character will appear. The +// first character could extend left of the current point; this is font +// dependent. You can either choose a current point that is the leftmost +// point and hope, or add some padding, or check the bounding box or +// left-side-bearing of the first character to be displayed and set +// the current point based on that. +// +// Displaying a character: +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to = 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program (this compiles): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype, e.g. if you don't +//// link with the C runtime library. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #define STBTT_pow(x,y) pow(x,y) + #endif + + #ifndef STBTT_fmod + #include + #define STBTT_fmod(x,y) fmod(x,y) + #endif + + #ifndef STBTT_cos + #include + #define STBTT_cos(x) cos(x) + #define STBTT_acos(x) acos(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + #ifndef STBTT_assert + #include + #define STBTT_assert(x) assert(x) + #endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publically so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSIOn + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); +// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 +// table (specific to MS/Windows TTF files). +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of countours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); +// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering +// is performed (see stbtt_PackSetOversampling) + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Signed Distance Function (or Field) rendering + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); +// frees the SDF bitmap allocated below + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +// These functions compute a discretized SDF field for a single character, suitable for storing +// in a single-channel texture, sampling with bilinear filtering, and testing against +// larger than some threshhold to produce scalable fonts. +// info -- the font +// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap +// glyph/codepoint -- the character to generate the SDF for +// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), +// which allows effects like bit outlines +// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) +// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) +// if positive, > onedge_value is inside; if negative, < onedge_value is inside +// width,height -- output height & width of the SDF bitmap (including padding) +// xoff,yoff -- output origin of the character +// return value -- a 2D array of bytes 0..255, width*height in size +// +// pixel_dist_scale & onedge_value are a scale & bias that allows you to make +// optimal use of the limited 0..255 for your application, trading off precision +// and special effects. SDF values outside the range 0..255 are clamped to 0..255. +// +// Example: +// scale = stbtt_ScaleForPixelHeight(22) +// padding = 5 +// onedge_value = 180 +// pixel_dist_scale = 180/5.0 = 36.0 +// +// This will create an SDF bitmap in which the character is about 22 pixels +// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled +// shape, sample the SDF at each pixel and fill the pixel if the SDF value +// is greater than or equal to 180/255. (You'll actually want to antialias, +// which is beyond the scope of this example.) Additionally, you can compute +// offset outlines (e.g. to stroke the character border inside & outside, +// or only outside). For example, to fill outside the character up to 3 SDF +// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above +// choice of variables maps a range from 5 pixels outside the shape to +// 2 pixels inside the shape to 0..255; this is intended primarily for apply +// outside effects only (the interior range is needed to allow proper +// antialiasing of the font at *smaller* sizes) +// +// The function computes the SDF analytically at each SDF pixel, not by e.g. +// building a higher-res bitmap and approximating it. In theory the quality +// should be as high as possible for an SDF of this size & representation, but +// unclear if this is true in practice (perhaps building a higher-res bitmap +// and computing from that can allow drop-out prevention). +// +// The algorithm has not been optimized at all, so expect it to be slow +// if computing lots of characters or very large sizes. + + + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + for (i=0; i < num_tables; ++i) { + stbtt_uint32 loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + for (i=0; i < numTables; ++i) { + stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + stbtt_uint8 *data = info->data; + stbtt_uint32 index_map = info->index_map; + + stbtt_uint16 format = ttUSHORT(data + index_map + 0); + if (format == 0) { // apple byte encoding + stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + if (unicode_codepoint < bytes-6) + return ttBYTE(data + index_map + 6 + unicode_codepoint); + return 0; + } else if (format == 6) { + stbtt_uint32 first = ttUSHORT(data + index_map + 6); + stbtt_uint32 count = ttUSHORT(data + index_map + 8); + if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) + return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); + return 0; + } else if (format == 2) { + STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean + return 0; + } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges + stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; + stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); + stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + + // do a binary search of the segments + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (unicode_codepoint > 0xffff) + return 0; + + // they lie from endCount .. endCount + segCount + // but searchRange is the nearest power of two, so... + if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) + search += rangeShift*2; + + // now decrement to bias correctly to find smallest + search -= 2; + while (entrySelector) { + stbtt_uint16 end; + searchRange >>= 1; + end = ttUSHORT(data + search + searchRange*2); + if (unicode_codepoint > end) + search += searchRange*2; + --entrySelector; + } + search += 2; + + { + stbtt_uint16 offset, start; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + + STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + if (unicode_codepoint < start) + return 0; + + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } + } else if (format == 12 || format == 13) { + stbtt_uint32 ngroups = ttULONG(data+index_map+12); + stbtt_int32 low,high; + low = 0; high = (stbtt_int32)ngroups; + // Binary search the right group. + while (low < high) { + stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + if ((stbtt_uint32) unicode_codepoint < start_char) + high = mid; + else if ((stbtt_uint32) unicode_codepoint > end_char) + low = mid+1; + else { + stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + if (format == 12) + return start_glyph + unicode_codepoint-start_char; + else // format == 13 + return start_glyph; + } + } + return 0; // not found + } + // @TODO + STBTT_assert(0); + return 0; +} + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + stbtt_int16 dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + stbtt_int16 dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one + start_off = !(flags & 1); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours == -1) { + // Compound shapes. + int more = 1; + stbtt_uint8 *comp = data + g + 10; + num_vertices = 0; + vertices = 0; + while (more) { + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices. + for (i = 0; i < comp_num_verts; ++i) { + stbtt_vertex* v = &comp_verts[i]; + stbtt_vertex_type x,y; + x=v->x; y=v->y; + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + x=v->cx; y=v->cy; + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else if (numberOfContours < 0) { + // @TODO other compound variations? + STBTT_assert(0); + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // fallthrough + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) *x0 = r ? c.min_x : 0; + if (y0) *y0 = r ? c.min_y : 0; + if (x1) *x1 = r ? c.max_x : 0; + if (y1) *y1 = r ? c.max_y : 0; + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) +{ + stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + switch(coverageFormat) { + case 1: { + stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + + // Binary search. + stbtt_int32 l=0, r=glyphCount-1, m; + int straw, needle=glyph; + while (l <= r) { + stbtt_uint8 *glyphArray = coverageTable + 4; + stbtt_uint16 glyphID; + m = (l + r) >> 1; + glyphID = ttUSHORT(glyphArray + 2 * m); + straw = glyphID; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + return m; + } + } + } break; + + case 2: { + stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + stbtt_uint8 *rangeArray = coverageTable + 4; + + // Binary search. + stbtt_int32 l=0, r=rangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *rangeRecord; + m = (l + r) >> 1; + rangeRecord = rangeArray + 6 * m; + strawStart = ttUSHORT(rangeRecord); + strawEnd = ttUSHORT(rangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else { + stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + return startCoverageIndex + glyph - strawStart; + } + } + } break; + + default: { + // There are no other cases. + STBTT_assert(0); + } break; + } + + return -1; +} + +static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) +{ + stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + switch(classDefFormat) + { + case 1: { + stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + stbtt_uint8 *classDef1ValueArray = classDefTable + 6; + + if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) + return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); + + classDefTable = classDef1ValueArray + 2 * glyphCount; + } break; + + case 2: { + stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + stbtt_uint8 *classRangeRecords = classDefTable + 4; + + // Binary search. + stbtt_int32 l=0, r=classRangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *classRangeRecord; + m = (l + r) >> 1; + classRangeRecord = classRangeRecords + 6 * m; + strawStart = ttUSHORT(classRangeRecord); + strawEnd = ttUSHORT(classRangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else + return (stbtt_int32)ttUSHORT(classRangeRecord + 4); + } + + classDefTable = classRangeRecords + 6 * classRangeCount; + } break; + + default: { + // There are no other cases. + STBTT_assert(0); + } break; + } + + return -1; +} + +// Define to STBTT_assert(x) if you want to break on unimplemented formats. +#define STBTT_GPOS_TODO_assert(x) + +static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint16 lookupListOffset; + stbtt_uint8 *lookupList; + stbtt_uint16 lookupCount; + stbtt_uint8 *data; + stbtt_int32 i; + + if (!info->gpos) return 0; + + data = info->data + info->gpos; + + if (ttUSHORT(data+0) != 1) return 0; // Major version 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 + + lookupListOffset = ttUSHORT(data+8); + lookupList = data + lookupListOffset; + lookupCount = ttUSHORT(lookupList); + + for (i=0; i> 1; + pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; + secondGlyph = ttUSHORT(pairValue); + straw = secondGlyph; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + stbtt_int16 xAdvance = ttSHORT(pairValue + 2); + return xAdvance; + } + } + } break; + + case 2: { + stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); + stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); + + stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); + stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); + int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + + stbtt_uint16 class1Count = ttUSHORT(table + 12); + stbtt_uint16 class2Count = ttUSHORT(table + 14); + STBTT_assert(glyph1class < class1Count); + STBTT_assert(glyph2class < class2Count); + + // TODO: Support more formats. + STBTT_GPOS_TODO_assert(valueFormat1 == 4); + if (valueFormat1 != 4) return 0; + STBTT_GPOS_TODO_assert(valueFormat2 == 0); + if (valueFormat2 != 0) return 0; + + if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) { + stbtt_uint8 *class1Records = table + 16; + stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count); + stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class); + return xAdvance; + } + } break; + + default: { + // There are no other cases. + STBTT_assert(0); + break; + }; + } + } + break; + }; + + default: + // TODO: Implement other stuff. + break; + } + } + + return 0; +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) +{ + int xAdvance = 0; + + if (info->gpos) + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + + if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + + return xAdvance; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + if (!tab) + return 0; + if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); + if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); + if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); + return 1; +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + int x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + float scan_y = y + 0.5f; + stbtt__active_edge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + int changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + stbtt__active_edge *t = *step; + stbtt__active_edge *q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = sy1 - sy0; + STBTT_assert(x >= 0 && x < len); + scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; + scanline_fill[x] += e->direction * height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = (x1+1 - x0) * dy + y_top; + + sign = e->direction; + // area of the rectangle covered from y0..y_crossing + area = sign * (y_crossing-sy0); + // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) + scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); + + step = sign * dy; + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; + area += step; + } + y_crossing += dy * (x2 - (x1+1)); + + STBTT_assert(STBTT_fabs(area) <= 1.01f); + + scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); + + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clearly-defined pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + float y1 = (x - x0) / dx + y_top; + float y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + STBTT_assert(z->ey >= scan_y_top); + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshhold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + int a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + float x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count = 0; + int *winding_lengths = NULL; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + STBTT_assert(x+gw < pw); + STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k; + + k=0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + int x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + ++k; + } + } + + return k; +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, + output, + out_w - (prefilter_x - 1), + out_h - (prefilter_y - 1), + out_stride, + scale_x, + scale_y, + shift_x, + shift_y, + glyph); + + if (prefilter_x > 1) + stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); + + if (prefilter_y > 1) + stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); + + *sub_x = stbtt__oversample_shift(prefilter_x); + *sub_y = stbtt__oversample_shift(prefilter_y); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + + k = 0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + int advance, lsb, x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i,j,n, return_value = 1; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// sdf computation +// + +#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) +#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) + +static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) +{ + float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + + float a = q0perp - 2*q1perp + q2perp; + float b = q1perp - q0perp; + float c = q0perp - roperp; + + float s0 = 0., s1 = 0.; + int num_s = 0; + + if (a != 0.0) { + float discr = b*b - a*c; + if (discr > 0.0) { + float rcpna = -1 / a; + float d = (float) STBTT_sqrt(discr); + s0 = (b+d) * rcpna; + s1 = (b-d) * rcpna; + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { + if (num_s == 0) s0 = s1; + ++num_s; + } + } + } else { + // 2*b*s + c = 0 + // s = -c / (2*b) + s0 = c / (-2 * b); + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + } + + if (num_s == 0) + return 0; + else { + float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; + + float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + float rod = orig[0]*rayn_x + orig[1]*rayn_y; + + float q10d = q1d - q0d; + float q20d = q2d - q0d; + float q0rd = q0d - rod; + + hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; + hits[0][1] = a*s0+b; + + if (num_s > 1) { + hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; + hits[1][1] = a*s1+b; + return 2; + } else { + return 1; + } + } +} + +static int equal(float *a, float *b) +{ + return (a[0] == b[0] && a[1] == b[1]); +} + +static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) +{ + int i; + float orig[2], ray[2] = { 1, 0 }; + float y_frac; + int winding = 0; + + orig[0] = x; + orig[1] = y; + + // make sure y never passes through a vertex of the shape + y_frac = (float) STBTT_fmod(y, 1.0f); + if (y_frac < 0.01f) + y += 0.01f; + else if (y_frac > 0.99f) + y -= 0.01f; + orig[1] = y; + + // test a ray from (-infinity,y) to (x,y) + for (i=0; i < nverts; ++i) { + if (verts[i].type == STBTT_vline) { + int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; + int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } + if (verts[i].type == STBTT_vcurve) { + int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; + int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; + int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; + int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); + int by = STBTT_max(y0,STBTT_max(y1,y2)); + if (y > ay && y < by && x > ax) { + float q0[2],q1[2],q2[2]; + float hits[2][2]; + q0[0] = (float)x0; + q0[1] = (float)y0; + q1[0] = (float)x1; + q1[1] = (float)y1; + q2[0] = (float)x2; + q2[1] = (float)y2; + if (equal(q0,q1) || equal(q1,q2)) { + x0 = (int)verts[i-1].x; + y0 = (int)verts[i-1].y; + x1 = (int)verts[i ].x; + y1 = (int)verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } else { + int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + if (num_hits >= 1) + if (hits[0][0] < 0) + winding += (hits[0][1] < 0 ? -1 : 1); + if (num_hits >= 2) + if (hits[1][0] < 0) + winding += (hits[1][1] < 0 ? -1 : 1); + } + } + } + } + return winding; +} + +static float stbtt__cuberoot( float x ) +{ + if (x<0) + return -(float) STBTT_pow(-x,1.0f/3.0f); + else + return (float) STBTT_pow( x,1.0f/3.0f); +} + +// x^3 + c*x^2 + b*x + a = 0 +static int stbtt__solve_cubic(float a, float b, float c, float* r) +{ + float s = -a / 3; + float p = b - a*a / 3; + float q = a * (2*a*a - 9*b) / 27 + c; + float p3 = p*p*p; + float d = q*q + 4*p3 / 27; + if (d >= 0) { + float z = (float) STBTT_sqrt(d); + float u = (-q + z) / 2; + float v = (-q - z) / 2; + u = stbtt__cuberoot(u); + v = stbtt__cuberoot(v); + r[0] = s + u + v; + return 1; + } else { + float u = (float) STBTT_sqrt(-p/3); + float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + float m = (float) STBTT_cos(v); + float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + r[0] = s + u * 2 * m; + r[1] = s - u * (m + n); + r[2] = s - u * (m - n); + + //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? + //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); + //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); + return 3; + } +} + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + float scale_x = scale, scale_y = scale; + int ix0,iy0,ix1,iy1; + int w,h; + unsigned char *data; + + // if one scale is 0, use same scale for both + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) return NULL; // if both scales are 0, return NULL + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); + + // if empty, return NULL + if (ix0 == ix1 || iy0 == iy1) + return NULL; + + ix0 -= padding; + iy0 -= padding; + ix1 += padding; + iy1 += padding; + + w = (ix1 - ix0); + h = (iy1 - iy0); + + if (width ) *width = w; + if (height) *height = h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + // invert for y-downwards bitmaps + scale_y = -scale_y; + + { + int x,y,i,j; + float *precompute; + stbtt_vertex *verts; + int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); + data = (unsigned char *) STBTT_malloc(w * h, info->userdata); + precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); + + for (i=0,j=num_verts-1; i < num_verts; j=i++) { + if (verts[i].type == STBTT_vline) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; + float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); + precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; + float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; + float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float len2 = bx*bx + by*by; + if (len2 != 0.0f) + precompute[i] = 1.0f / (bx*bx + by*by); + else + precompute[i] = 0.0f; + } else + precompute[i] = 0.0f; + } + + for (y=iy0; y < iy1; ++y) { + for (x=ix0; x < ix1; ++x) { + float val; + float min_dist = 999999.0f; + float sx = (float) x + 0.5f; + float sy = (float) y + 0.5f; + float x_gspace = (sx / scale_x); + float y_gspace = (sy / scale_y); + + int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path + + for (i=0; i < num_verts; ++i) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + + // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve + float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + if (verts[i].type == STBTT_vline) { + float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; + + // coarse culling against bbox + //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && + // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) + float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; + STBTT_assert(i != 0); + if (dist < min_dist) { + // check position along line + // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) + // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) + float dx = x1-x0, dy = y1-y0; + float px = x0-sx, py = y0-sy; + // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy + // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve + float t = -(px*dx + py*dy) / (dx*dx + dy*dy); + if (t >= 0.0f && t <= 1.0f) + min_dist = dist; + } + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; + float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; + float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); + float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); + float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); + float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); + // coarse culling against bbox to avoid computing cubic unnecessarily + if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { + int num=0; + float ax = x1-x0, ay = y1-y0; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float mx = x0 - sx, my = y0 - sy; + float res[3],px,py,t,it; + float a_inv = precompute[i]; + if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula + float a = 3*(ax*bx + ay*by); + float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); + float c = mx*ax+my*ay; + if (a == 0.0) { // if a is 0, it's linear + if (b != 0.0) { + res[num++] = -c/b; + } + } else { + float discriminant = b*b - 4*a*c; + if (discriminant < 0) + num = 0; + else { + float root = (float) STBTT_sqrt(discriminant); + res[0] = (-b - root)/(2*a); + res[1] = (-b + root)/(2*a); + num = 2; // don't bother distinguishing 1-solution case, as code below will still work + } + } + } else { + float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point + float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; + float d = (mx*ax+my*ay) * a_inv; + num = stbtt__solve_cubic(b, c, d, res); + } + if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { + t = res[0], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { + t = res[1], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { + t = res[2], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + } + } + } + if (winding == 0) + min_dist = -min_dist; // if outside the shape, value is negative + val = onedge_value + pixel_dist_scale * min_dist; + if (val < 0) + val = 0; + else if (val > 255) + val = 255; + data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; + } + } + STBTT_free(precompute, info->userdata); + STBTT_free(verts, info->userdata); + } + return data; +} + +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + stbtt_uint16 ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + stbtt_int32 id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); + + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + stbtt_int32 slen = ttUSHORT(fc+loc+8); + stbtt_int32 off = ttUSHORT(fc+loc+10); + + // check if there's a prefix match + stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i; + for (i=0;;++i) { + stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/3rdparty/imgui/qt_attribution.json b/src/3rdparty/imgui/qt_attribution.json new file mode 100644 index 000000000..80d8adbcf --- /dev/null +++ b/src/3rdparty/imgui/qt_attribution.json @@ -0,0 +1,16 @@ +[ + { + "Id": "imgui", + "Name": "Dear ImGui", + "QDocModule": "qtrhi", + "Description": "Dear ImGui", + "QtUsage": "Used in tests to demonstrate and verify the integration of an external GUI library.", + + "Homepage": "https://github.com/ocornut/imgui", + "Version": "v1.66b", + "License": "MIT License", + "LicenseId": "MIT", + "LicenseFile": "LICENSE.txt", + "Copyright": "Copyright (c) 2014-2018 Omar Cornut" + } +] diff --git a/src/extras/defaults/qforwardrenderer.cpp b/src/extras/defaults/qforwardrenderer.cpp index f1306e787..9aef5aa84 100644 --- a/src/extras/defaults/qforwardrenderer.cpp +++ b/src/extras/defaults/qforwardrenderer.cpp @@ -47,6 +47,7 @@ #include #include #include +#include static void initResources() { @@ -68,6 +69,7 @@ QForwardRendererPrivate::QForwardRendererPrivate() , m_cameraSelector(new QCameraSelector()) , m_clearBuffer(new QClearBuffers()) , m_frustumCulling(new QFrustumCulling()) + , m_debugOverlay(new QDebugOverlay()) { } @@ -77,13 +79,14 @@ void QForwardRendererPrivate::init() initResources(); + m_debugOverlay->setParent(m_frustumCulling); m_frustumCulling->setParent(m_clearBuffer); m_clearBuffer->setParent(m_cameraSelector); m_cameraSelector->setParent(m_viewport); m_viewport->setParent(m_surfaceSelector); m_surfaceSelector->setParent(q); - m_viewport->setNormalizedRect(QRectF(0.0f, 0.0f, 1.0f, 1.0f)); + m_viewport->setNormalizedRect(QRectF(0.0, 0.0, 1.0, 1.0)); m_clearBuffer->setClearColor(Qt::white); m_clearBuffer->setBuffers(QClearBuffers::ColorDepthBuffer); @@ -146,6 +149,7 @@ QForwardRenderer::QForwardRenderer(QNode *parent) QObject::connect(d->m_surfaceSelector, &QRenderSurfaceSelector::externalRenderTargetSizeChanged, this, &QForwardRenderer::externalRenderTargetSizeChanged); QObject::connect(d->m_frustumCulling, &QFrustumCulling::enabledChanged, this, &QForwardRenderer::frustumCullingEnabledChanged); QObject::connect(d->m_viewport, &QViewport::gammaChanged, this, &QForwardRenderer::gammaChanged); + QObject::connect(d->m_debugOverlay, &QDebugOverlay::enabledChanged, this, &QForwardRenderer::showDebugOverlayChanged); d->init(); } @@ -201,6 +205,12 @@ void QForwardRenderer::setGamma(float gamma) d->m_viewport->setGamma(gamma); } +void QForwardRenderer::setShowDebugOverlay(bool showDebugOverlay) +{ + Q_D(QForwardRenderer); + d->m_debugOverlay->setEnabled(showDebugOverlay); +} + /*! \qmlproperty rect ForwardRenderer::viewportRect @@ -356,6 +366,12 @@ float QForwardRenderer::gamma() const return d->m_viewport->gamma(); } +bool QForwardRenderer::showDebugOverlay() const +{ + Q_D(const QForwardRenderer); + return d->m_debugOverlay->isEnabled(); +} + } // namespace Qt3DExtras QT_END_NAMESPACE diff --git a/src/extras/defaults/qforwardrenderer.h b/src/extras/defaults/qforwardrenderer.h index a34d39560..22334373c 100644 --- a/src/extras/defaults/qforwardrenderer.h +++ b/src/extras/defaults/qforwardrenderer.h @@ -66,6 +66,7 @@ class Q_3DEXTRASSHARED_EXPORT QForwardRenderer : public Qt3DRender::QTechniqueFi Q_PROPERTY(QSize externalRenderTargetSize READ externalRenderTargetSize WRITE setExternalRenderTargetSize NOTIFY externalRenderTargetSizeChanged) Q_PROPERTY(bool frustumCulling READ isFrustumCullingEnabled WRITE setFrustumCullingEnabled NOTIFY frustumCullingEnabledChanged) Q_PROPERTY(float gamma READ gamma WRITE setGamma NOTIFY gammaChanged REVISION 9) + Q_PROPERTY(bool showDebugOverlay READ showDebugOverlay WRITE setShowDebugOverlay NOTIFY showDebugOverlayChanged REVISION 15) public: explicit QForwardRenderer(Qt3DCore::QNode *parent = nullptr); ~QForwardRenderer(); @@ -78,6 +79,7 @@ public: QSize externalRenderTargetSize() const; bool isFrustumCullingEnabled() const; float gamma() const; + bool showDebugOverlay() const; public Q_SLOTS: void setViewportRect(const QRectF &viewportRect); @@ -88,6 +90,7 @@ public Q_SLOTS: void setExternalRenderTargetSize(const QSize &size); void setFrustumCullingEnabled(bool enabled); void setGamma(float gamma); + void setShowDebugOverlay(bool showDebugOverlay); Q_SIGNALS: void viewportRectChanged(const QRectF &viewportRect); @@ -98,6 +101,7 @@ Q_SIGNALS: void externalRenderTargetSizeChanged(const QSize &size); void frustumCullingEnabledChanged(bool enabled); void gammaChanged(float gamma); + void showDebugOverlayChanged(bool showDebugOverlay); private: Q_DECLARE_PRIVATE(QForwardRenderer) diff --git a/src/extras/defaults/qforwardrenderer_p.h b/src/extras/defaults/qforwardrenderer_p.h index 56d66a542..f1c95e132 100644 --- a/src/extras/defaults/qforwardrenderer_p.h +++ b/src/extras/defaults/qforwardrenderer_p.h @@ -63,6 +63,7 @@ class QClearBuffers; class QCameraSelector; class QFrustumCulling; class QRenderSurfaceSelector; +class QDebugOverlay; } // namespace Qt3DRender @@ -78,6 +79,7 @@ public: Qt3DRender::QCameraSelector *m_cameraSelector; Qt3DRender::QClearBuffers *m_clearBuffer; Qt3DRender::QFrustumCulling *m_frustumCulling; + Qt3DRender::QDebugOverlay *m_debugOverlay; void init(); diff --git a/src/quick3d/imports/extras/qt3dquick3dextrasplugin.cpp b/src/quick3d/imports/extras/qt3dquick3dextrasplugin.cpp index b675ec283..9739b6604 100644 --- a/src/quick3d/imports/extras/qt3dquick3dextrasplugin.cpp +++ b/src/quick3d/imports/extras/qt3dquick3dextrasplugin.cpp @@ -88,6 +88,7 @@ void Qt3DQuick3DExtrasPlugin::registerTypes(const char *uri) qmlRegisterType(uri, 2, 0, "ForwardRenderer"); qmlRegisterType(uri, 2, 9, "ForwardRenderer"); qmlRegisterType(uri, 2, 14, "ForwardRenderer"); + qmlRegisterType(uri, 2, 15, "ForwardRenderer"); // Entities qmlRegisterType(uri, 2, 0, "SkyboxEntity"); diff --git a/src/render/framegraph/debugoverlay.cpp b/src/render/framegraph/debugoverlay.cpp new file mode 100644 index 000000000..2d2a1e63b --- /dev/null +++ b/src/render/framegraph/debugoverlay.cpp @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +DebugOverlay::DebugOverlay() + : FrameGraphNode(FrameGraphNode::DebugOverlay, QBackendNode::ReadWrite) +{ + +} + +} //Render + +} //Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/framegraph/debugoverlay_p.h b/src/render/framegraph/debugoverlay_p.h new file mode 100644 index 000000000..a2045ffbe --- /dev/null +++ b/src/render/framegraph/debugoverlay_p.h @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DEBUGOVERLAY_P_H +#define DEBUGOVERLAY_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT DebugOverlay : public FrameGraphNode +{ +public: + DebugOverlay(); +}; + +} //Render + +} //Qt3DRender + +QT_END_NAMESPACE + +#endif // DEBUGOVERLAY_P_H diff --git a/src/render/framegraph/framegraph.pri b/src/render/framegraph/framegraph.pri index bb833422f..a622bd281 100644 --- a/src/render/framegraph/framegraph.pri +++ b/src/render/framegraph/framegraph.pri @@ -69,7 +69,10 @@ HEADERS += \ $$PWD/nopicking_p.h \ $$PWD/qsubtreeenabler.h \ $$PWD/qsubtreeenabler_p.h \ - $$PWD/subtreeenabler_p.h + $$PWD/subtreeenabler_p.h \ + $$PWD/qdebugoverlay.h \ + $$PWD/qdebugoverlay_p.h \ + $$PWD/debugoverlay_p.h SOURCES += \ $$PWD/cameraselectornode.cpp \ @@ -119,4 +122,6 @@ SOURCES += \ $$PWD/qnopicking.cpp \ $$PWD/nopicking.cpp \ $$PWD/qsubtreeenabler.cpp \ - $$PWD/subtreeenabler.cpp + $$PWD/subtreeenabler.cpp \ + $$PWD/qdebugoverlay.cpp \ + $$PWD/debugoverlay.cpp diff --git a/src/render/framegraph/framegraphnode_p.h b/src/render/framegraph/framegraphnode_p.h index 846dc8060..55bede5fd 100644 --- a/src/render/framegraph/framegraphnode_p.h +++ b/src/render/framegraph/framegraphnode_p.h @@ -104,7 +104,8 @@ public: BlitFramebuffer, SetFence, WaitFence, - NoPicking + NoPicking, + DebugOverlay, }; FrameGraphNodeType nodeType() const { return m_nodeType; } diff --git a/src/render/framegraph/qdebugoverlay.cpp b/src/render/framegraph/qdebugoverlay.cpp new file mode 100644 index 000000000..d82ae88ba --- /dev/null +++ b/src/render/framegraph/qdebugoverlay.cpp @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qdebugoverlay.h" +#include "qdebugoverlay_p.h" + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +/*! + * \internal + */ +QDebugOverlayPrivate::QDebugOverlayPrivate() + : QFrameGraphNodePrivate() +{ +} + +/*! + * \internal + */ +QDebugOverlayPrivate::~QDebugOverlayPrivate() = default; + +/*! + * The constructor creates an instance with the specified \a parent. + */ +QDebugOverlay::QDebugOverlay(Qt3DCore::QNode *parent) + : QFrameGraphNode(*new QDebugOverlayPrivate, parent) +{ +} + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/framegraph/qdebugoverlay.h b/src/render/framegraph/qdebugoverlay.h new file mode 100644 index 000000000..1d115fc2e --- /dev/null +++ b/src/render/framegraph/qdebugoverlay.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QDEBUGOVERLOAY_H +#define QDEBUGOVERLOAY_H + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class QDebugOverlayPrivate; + +class Q_3DRENDERSHARED_EXPORT QDebugOverlay : public QFrameGraphNode +{ + Q_OBJECT +public: + explicit QDebugOverlay(Qt3DCore::QNode *parent = nullptr); + +private: + Q_DECLARE_PRIVATE(QDebugOverlay) +}; + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QDEBUGOVERLOAY_H diff --git a/src/render/framegraph/qdebugoverlay_p.h b/src/render/framegraph/qdebugoverlay_p.h new file mode 100644 index 000000000..f8c34655a --- /dev/null +++ b/src/render/framegraph/qdebugoverlay_p.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QDEBUGOVERLAY_P_H +#define QDEBUGOVERLAY_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class QDebugOverlayPrivate : public QFrameGraphNodePrivate +{ +public: + QDebugOverlayPrivate(); + ~QDebugOverlayPrivate(); + + Q_DECLARE_PUBLIC(QDebugOverlay) +}; + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QDEBUGOVERLAY_P_H diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index d48eb4dd3..a65f66fd7 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -92,6 +92,7 @@ #include #include #include +#include #include #include #include @@ -159,6 +160,7 @@ #include #include #include +#include #include #include @@ -330,6 +332,7 @@ void QRenderAspectPrivate::registerBackendTypes() q->registerBackendType(QSharedPointer >::create(m_renderer)); q->registerBackendType(QSharedPointer >::create(m_renderer)); q->registerBackendType(QSharedPointer >::create(m_renderer)); + q->registerBackendType(QSharedPointer >::create(m_renderer)); // Picking q->registerBackendType(QSharedPointer >::create(m_renderer)); @@ -404,6 +407,7 @@ void QRenderAspectPrivate::unregisterBackendTypes() unregisterBackendType(); unregisterBackendType(); unregisterBackendType(); + unregisterBackendType(); // Picking unregisterBackendType(); @@ -565,7 +569,6 @@ QVariant QRenderAspect::executeCommand(const QStringList &args) } if (args.front() == QLatin1String("scenegraph")) return droot->dumpSceneGraph(); - return {}; } return d->m_renderer->executeCommand(args); diff --git a/src/render/renderers/opengl/debug/debug.pri b/src/render/renderers/opengl/debug/debug.pri new file mode 100644 index 000000000..c5153bbf7 --- /dev/null +++ b/src/render/renderers/opengl/debug/debug.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD + +include($$QT3D_ROOT/src/3rdparty/imgui/imgui.pri) + +HEADERS += \ + $$PWD/imguirenderer_p.h \ + $$PWD/imconfig.h + +SOURCES += \ + $$PWD/imguirenderer.cpp diff --git a/src/render/renderers/opengl/debug/imguirenderer.cpp b/src/render/renderers/opengl/debug/imguirenderer.cpp new file mode 100644 index 000000000..d2a1cb925 --- /dev/null +++ b/src/render/renderers/opengl/debug/imguirenderer.cpp @@ -0,0 +1,717 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + * Based on https://github.com/seanchas116/qtimgui/ + * + * MIT License https://github.com/seanchas116/qtimgui/blob/master/LICENSE + * + */ + +#include "imguirenderer_p.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "imgui.h" + +#ifndef GL_VERTEX_ARRAY_BINDING +// just for building on some platforms, won't run anyway as this requires GL/ES > 2 +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#endif + +QT_BEGIN_NAMESPACE + +using namespace Qt3DRender; +using namespace Render; +using namespace Render::Debug; + +namespace { + + const QHash keyMap = { + { Qt::Key_Tab, ImGuiKey_Tab }, + { Qt::Key_Left, ImGuiKey_LeftArrow }, + { Qt::Key_Right, ImGuiKey_RightArrow }, + { Qt::Key_Up, ImGuiKey_UpArrow }, + { Qt::Key_Down, ImGuiKey_DownArrow }, + { Qt::Key_PageUp, ImGuiKey_PageUp }, + { Qt::Key_PageDown, ImGuiKey_PageDown }, + { Qt::Key_Home, ImGuiKey_Home }, + { Qt::Key_End, ImGuiKey_End }, + { Qt::Key_Delete, ImGuiKey_Delete }, + { Qt::Key_Backspace, ImGuiKey_Backspace }, + { Qt::Key_Enter, ImGuiKey_Enter }, + { Qt::Key_Escape, ImGuiKey_Escape }, + { Qt::Key_A, ImGuiKey_A }, + { Qt::Key_C, ImGuiKey_C }, + { Qt::Key_V, ImGuiKey_V }, + { Qt::Key_X, ImGuiKey_X }, + { Qt::Key_Y, ImGuiKey_Y }, + { Qt::Key_Z, ImGuiKey_Z }, + }; + + QByteArray g_currentClipboardText; + + // doesn't handle primitive restart when using indexes + int vertexToPrimitiveCount(Qt3DRender::QGeometryRenderer::PrimitiveType primitiveType, int numVertices) { + int nPrimitives = 0; + switch (primitiveType) { + case QGeometryRenderer::Points: + case QGeometryRenderer::LineLoop: nPrimitives += numVertices; break; + case QGeometryRenderer::Triangles: nPrimitives += numVertices / 3; break; + case QGeometryRenderer::Lines: nPrimitives += numVertices / 2; break; + case QGeometryRenderer::TriangleFan: + case QGeometryRenderer::TriangleStrip: + case QGeometryRenderer::LineStrip: nPrimitives += numVertices - 1; break; + case QGeometryRenderer::TrianglesAdjacency: nPrimitives += numVertices / 6; break; + case QGeometryRenderer::TriangleStripAdjacency: + case QGeometryRenderer::LineStripAdjacency: nPrimitives += numVertices / 2 - 1; break; + case QGeometryRenderer::LinesAdjacency: nPrimitives += numVertices / 4; break; + case QGeometryRenderer::Patches: nPrimitives += 1; + } + return nPrimitives; + } + + const char *primitiveTypeName(Qt3DRender::QGeometryRenderer::PrimitiveType primitiveType) { + switch (primitiveType) { + case QGeometryRenderer::Points: return "Points"; + case QGeometryRenderer::LineLoop: return "LineLoop"; + case QGeometryRenderer::Triangles: return "Triangles"; + case QGeometryRenderer::TrianglesAdjacency: return "TriangleAdjacency"; + case QGeometryRenderer::TriangleFan: return "TriangleFan"; + case QGeometryRenderer::TriangleStrip: return "TriangleStrip"; + case QGeometryRenderer::TriangleStripAdjacency: return "TriangleStringAdjacency"; + case QGeometryRenderer::LineStrip: return "LineStrip"; + case QGeometryRenderer::LineStripAdjacency: return "LineStripAdjacency"; + case QGeometryRenderer::Lines: return "Lines"; + case QGeometryRenderer::LinesAdjacency: return "LinesAdjacency"; + case QGeometryRenderer::Patches: return "Patches"; + } + return ""; + } +} + +ImGuiRenderer::ImGuiRenderer(Renderer *renderer) + : m_renderer(renderer) +{ + ImGui::CreateContext(); + + ImGuiIO &io = ImGui::GetIO(); + for (ImGuiKey key : keyMap.values()) + io.KeyMap[key] = key; + +#ifndef QT_NO_CLIPBOARD + io.SetClipboardTextFn = [](void *user_data, const char *text) { + Q_UNUSED(user_data) + QGuiApplication::clipboard()->setText(QString::fromLatin1(text)); + }; + io.GetClipboardTextFn = [](void *user_data) { + Q_UNUSED(user_data) + g_currentClipboardText = QGuiApplication::clipboard()->text().toUtf8(); + return static_cast(g_currentClipboardText.data()); + }; +#endif + + std::fill(std::begin(m_fpsLog), std::end(m_fpsLog), 0.f); + std::fill(std::begin(m_jobsLog), std::end(m_jobsLog), 0.f); + m_fpsRange.first = m_fpsRange.second = 0.f; + m_jobsRange.first = m_jobsRange.second = 0.f; +} + +void ImGuiRenderer::renderDebugOverlay(const QVector &renderViews, const RenderView *renderView, int jobsInLastFrame) +{ + if (!newFrame(renderView)) + return; + + const int renderViewsCount = renderViews.size(); + + int logIndex = qMin(IMGUI_PERF_LOG_SIZE - 1, ImGui::GetFrameCount()); + if (logIndex == IMGUI_PERF_LOG_SIZE - 1) { + std::rotate(std::begin(m_fpsLog), std::begin(m_fpsLog) + 1, std::end(m_fpsLog)); + std::rotate(std::begin(m_jobsLog), std::begin(m_jobsLog) + 1, std::end(m_jobsLog)); + } + m_fpsLog[logIndex] = ImGui::GetIO().Framerate; + m_fpsRange.first = m_fpsRange.second = 0.f; + for (float v: m_fpsLog) { + m_fpsRange.first = qMin(m_fpsRange.first, qMax(v - 5.f, 0.f)); + m_fpsRange.second = qMax(m_fpsRange.second, v + 2.f); + } + m_jobsLog[logIndex] = jobsInLastFrame; + m_jobsRange.first = m_jobsRange.second = 0.f; + for (float v: m_jobsLog) { + m_jobsRange.first = qMin(m_jobsRange.first, qMax(v - 5.f, 0.f)); + m_jobsRange.second = qMax(m_jobsRange.second, v + 2.f); + } + + { + bool pj = m_renderer->services()->systemInformation()->isTraceEnabled(); + bool pg = m_renderer->services()->systemInformation()->isGraphicsTraceEnabled(); + + ImGui::Begin("Qt3D Profiling"); + char caption[50]; + sprintf(caption, "Avg %.3f ms/frame (%.1f FPS)", static_cast(1000.0f / ImGui::GetIO().Framerate), static_cast(ImGui::GetIO().Framerate)); + ImGui::PlotLines("FPS", m_fpsLog, logIndex + 1, 0, caption, m_fpsRange.first, m_fpsRange.second, ImVec2(0, 80)); + ImGui::PlotHistogram("Jobs", m_jobsLog, logIndex + 1, 0, nullptr, m_jobsRange.first, m_jobsRange.second, ImVec2(0, 80)); + ImGui::Text("Profiling: "); + ImGui::SameLine(); + if (ImGui::Checkbox("Jobs", &pj)) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "setTraceEnabled", Qt::QueuedConnection, Q_ARG(bool, pj)); + ImGui::SameLine(); + if (ImGui::Checkbox("GL", &pg)) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "setGraphicsTraceEnabled", Qt::QueuedConnection, Q_ARG(bool, pg)); + ImGui::SameLine(); + if (ImGui::Button("Reveal")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "revealLogFolder", Qt::QueuedConnection); + + int nCommands = 0; + int nVertices = 0; + int nPrimitives = 0; + QSet inUseGeometries; + QSet inUseTextures; + for (int j=0; jcommands(); + nCommands += commands.size(); + for (int k=0; knodeManagers()->renderNodesManager()->count()); + column2Numbers(inUseGeometries.size(), m_renderer->nodeManagers()->geometryRendererManager()->count()); + column2Numbers(inUseTextures.size(), m_renderer->nodeManagers()->textureManager()->count()); + + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::AlignTextToFramePadding(); + ImGui::Text("Show:"); + ImGui::SameLine(); + if (ImGui::Button("GL Info")) + m_showGLInfoWindow = !m_showGLInfoWindow; + ImGui::SameLine(); + if (ImGui::Button("Render Views")) + m_showRenderDetailsWindow = !m_showRenderDetailsWindow; + + ImGui::AlignTextToFramePadding(); + ImGui::Text("Dump:"); + ImGui::SameLine(); + if (ImGui::Button("SceneGraph##1")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render scenegraph"))); + ImGui::SameLine(); + if (ImGui::Button("FrameGraph##1")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render framegraph"))); + ImGui::SameLine(); + if (ImGui::Button("FrameGraph Paths##1")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render framepaths"))); + + ImGui::End(); + + if (m_showGLInfoWindow) + showGLInfo(); + if (m_showRenderDetailsWindow) + showRenderDetails(renderViews); + } + + ImGui::Render(); + renderDrawList(ImGui::GetDrawData()); +} + +void ImGuiRenderer::showGLInfo() +{ + const GraphicsApiFilterData *contextInfo = m_renderer->submissionContext()->contextInfo(); + + ImGui::Begin("Open GL Details", &m_showGLInfoWindow); + + ImGui::Text("API: %s %d.%d", contextInfo->m_api == QGraphicsApiFilter::OpenGL ? "OpenGL" : "OpenGLES" + , contextInfo->m_major, contextInfo->m_minor); + if (contextInfo->m_api == QGraphicsApiFilter::OpenGL) + ImGui::Text("Profile: %s", contextInfo->m_profile == QGraphicsApiFilter::CoreProfile ? "Core" : + contextInfo->m_profile == QGraphicsApiFilter::CompatibilityProfile ? "Compatibity" : "Node"); + + // TODO show capabilities + GLint maxTextureSize, maxTextureUnits; + m_funcs->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); + m_funcs->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits); + ImGui::Text("Texture max size: %d Units: %d", maxTextureSize, maxTextureUnits); + + if (ImGui::Button("Dump")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render glinfo"))); + + ImGui::End(); +} + +void ImGuiRenderer::showRenderDetails(const QVector &renderViews) +{ + ImGui::Begin("Render Views", &m_showRenderDetailsWindow); + + int i = 1; + for (const RenderView *view: renderViews) { + QString label(QLatin1String("View ") + QString::number(i++)); + if (ImGui::TreeNode(label.toLatin1().data())) { + ImGui::Text("Viewport: (%.1f, %.1f, %.1f, %.1f)", view->viewport().x(), view->viewport().y(), + view->viewport().width(), view->viewport().height()); + ImGui::Text("Surface Size: (%d, %d)", view->surfaceSize().width(), view->surfaceSize().height()); + ImGui::Text("Pixel Ratio: %.1f", view->devicePixelRatio()); + ImGui::Text("No Draw: %s", view->noDraw() ? "TRUE" : "FALSE"); + ImGui::Text("Frustum Culling: %s", view->frustumCulling() ? "TRUE" : "FALSE"); + ImGui::Text("Compute: %s", view->isCompute() ? "TRUE" : "FALSE"); + ImGui::Text("Clear Depth Value: %f", static_cast(view->clearDepthValue())); + ImGui::Text("Clear Stencil Value: %d", view->clearStencilValue()); + int j = 1; + const auto commands = view->commands(); + for (const RenderCommand &command: commands) { + QString label(QLatin1String("Command ") + QString::number(j++)); + if (ImGui::TreeNode(label.toLatin1().data())) { + ImGui::Text("Primitive Type: %s %s", primitiveTypeName(command.m_primitiveType), + command.m_drawIndexed ? "(indexed)" : ""); + ImGui::Text("# Vertices: %d", command.m_primitiveCount); + ImGui::Text("# Primitives: %d", vertexToPrimitiveCount(command.m_primitiveType, command.m_primitiveCount)); + ImGui::Text("# Instances: %d", command.m_instanceCount); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + ImGui::Separator(); + } + } + + if (ImGui::Button("Dump")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render rendercommands"))); + ImGui::End(); +} + +void ImGuiRenderer::renderDrawList(ImDrawData *draw_data) +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + ImGuiIO& io = ImGui::GetIO(); + int fb_width = int(io.DisplaySize.x * io.DisplayFramebufferScale.x); + int fb_height = int(io.DisplaySize.y * io.DisplayFramebufferScale.y); + if (fb_width == 0 || fb_height == 0) + return; + draw_data->ScaleClipRects(io.DisplayFramebufferScale); + + // Backup GL state + GLint last_active_texture; m_funcs->glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); + m_funcs->glActiveTexture(GL_TEXTURE0); + GLint last_program; m_funcs->glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); + GLint last_texture; m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLint last_array_buffer; m_funcs->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + GLint last_element_array_buffer; m_funcs->glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); + GLint last_vertex_array; m_funcs->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + GLint last_blend_src_rgb; m_funcs->glGetIntegerv(GL_BLEND_SRC_RGB, &last_blend_src_rgb); + GLint last_blend_dst_rgb; m_funcs->glGetIntegerv(GL_BLEND_DST_RGB, &last_blend_dst_rgb); + GLint last_blend_src_alpha; m_funcs->glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha); + GLint last_blend_dst_alpha; m_funcs->glGetIntegerv(GL_BLEND_DST_ALPHA, &last_blend_dst_alpha); + GLint last_blend_equation_rgb; m_funcs->glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); + GLint last_blend_equation_alpha; m_funcs->glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); + GLint last_viewport[4]; m_funcs->glGetIntegerv(GL_VIEWPORT, last_viewport); + GLint last_scissor_box[4]; m_funcs->glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); + GLboolean last_enable_blend = m_funcs->glIsEnabled(GL_BLEND); + GLboolean last_enable_cull_face = m_funcs->glIsEnabled(GL_CULL_FACE); + GLboolean last_enable_depth_test = m_funcs->glIsEnabled(GL_DEPTH_TEST); + GLboolean last_enable_scissor_test = m_funcs->glIsEnabled(GL_SCISSOR_TEST); + + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled + m_funcs->glEnable(GL_BLEND); + m_funcs->glBlendEquation(GL_FUNC_ADD); + m_funcs->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + m_funcs->glDisable(GL_CULL_FACE); + m_funcs->glDisable(GL_DEPTH_TEST); + m_funcs->glEnable(GL_SCISSOR_TEST); + + // Setup viewport, orthographic projection matrix + m_funcs->glViewport(0, 0, static_cast(fb_width), static_cast(fb_height)); + const float ortho_projection[4][4] = { + { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + {-1.0f, 1.0f, 0.0f, 1.0f }, + }; + m_funcs->glUseProgram(m_shaderHandle); + m_funcs->glUniform1i(m_attribLocationTex, 0); + m_funcs->glUniformMatrix4fv(m_attribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); + m_funcs->glBindVertexArray(m_vaoHandle); + + for (int n = 0; n < draw_data->CmdListsCount; n++) { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawIdx* idx_buffer_offset = nullptr; + + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle); + m_funcs->glBufferData(GL_ARRAY_BUFFER, static_cast(cmd_list->VtxBuffer.Size) * sizeof(ImDrawVert), static_cast(cmd_list->VtxBuffer.Data), GL_STREAM_DRAW); + + m_funcs->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementsHandle); + m_funcs->glBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast(cmd_list->IdxBuffer.Size) * sizeof(ImDrawIdx), static_cast(cmd_list->IdxBuffer.Data), GL_STREAM_DRAW); + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) { + pcmd->UserCallback(cmd_list, pcmd); + } else { + m_funcs->glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); + m_funcs->glScissor(static_cast(pcmd->ClipRect.x), static_cast(fb_height - pcmd->ClipRect.w), + static_cast(pcmd->ClipRect.z - pcmd->ClipRect.x), static_cast(pcmd->ClipRect.w - pcmd->ClipRect.y)); + m_funcs->glDrawElements(GL_TRIANGLES, static_cast(pcmd->ElemCount), sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + } + idx_buffer_offset += pcmd->ElemCount; + } + } + + // Restore modified GL state + m_funcs->glUseProgram(last_program); + m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); + m_funcs->glActiveTexture(last_active_texture); + m_funcs->glBindVertexArray(last_vertex_array); + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); + m_funcs->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); + m_funcs->glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); + m_funcs->glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); + if (last_enable_blend) + m_funcs->glEnable(GL_BLEND); else m_funcs->glDisable(GL_BLEND); + if (last_enable_cull_face) + m_funcs->glEnable(GL_CULL_FACE); else m_funcs->glDisable(GL_CULL_FACE); + if (last_enable_depth_test) + m_funcs->glEnable(GL_DEPTH_TEST); else m_funcs->glDisable(GL_DEPTH_TEST); + if (last_enable_scissor_test) + m_funcs->glEnable(GL_SCISSOR_TEST); else m_funcs->glDisable(GL_SCISSOR_TEST); + m_funcs->glViewport(last_viewport[0], last_viewport[1], static_cast(last_viewport[2]), static_cast(last_viewport[3])); + m_funcs->glScissor(last_scissor_box[0], last_scissor_box[1], static_cast(last_scissor_box[2]), static_cast(last_scissor_box[3])); +} + +bool ImGuiRenderer::createFontsTexture() +{ + // Build texture atlas + ImGuiIO& io = ImGui::GetIO(); + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. + + // Upload texture to graphics system + GLint last_texture; + m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + m_funcs->glGenTextures(1, &m_fontTexture); + m_funcs->glBindTexture(GL_TEXTURE_2D, m_fontTexture); + m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + + // Store our identifier + io.Fonts->TexID = (void *)(intptr_t)m_fontTexture; + + // Restore state + m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); + + return true; +} + +bool ImGuiRenderer::createDeviceObjects() +{ + auto *glContext = m_renderer->submissionContext()->openGLContext(); + if (glContext->format().majorVersion() < 3) { + qWarning() << "Qt3D Profiling overlay requires GL or GL ES >= 3"; + return false; + } + + // Backup GL state + GLint last_texture, last_array_buffer, last_vertex_array; + m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + m_funcs->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + m_funcs->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + + const GLchar *vertex_shader = + "#version 330\n" + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n"; + + const GLchar* fragment_shader = + "#version 330\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main()\n" + "{\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n"; + + const GLchar *vertex_shader_es3 = + "#version 110\n" + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n"; + + const GLchar* fragment_shader_es3 = + "#version 110\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" + "}\n"; + +// m_shaderHandle = m_funcs->glCreateProgram(); +// m_vertHandle = m_funcs->glCreateShader(GL_VERTEX_SHADER); +// m_fragHandle = m_funcs->glCreateShader(GL_FRAGMENT_SHADER); +// auto *glContext = m_renderer->submissionContext()->openGLContext(); +// m_funcs->glShaderSource(m_vertHandle, 1, &vertex_shader, nullptr); +// m_funcs->glShaderSource(m_fragHandle, 1, &fragment_shader, nullptr); +// m_funcs->glCompileShader(m_vertHandle); +// m_funcs->glCompileShader(m_fragHandle); +// m_funcs->glAttachShader(m_shaderHandle, m_vertHandle); +// m_funcs->glAttachShader(m_shaderHandle, m_fragHandle); +// m_funcs->glLinkProgram(m_shaderHandle); + + QString logs; + m_shader = new QOpenGLShaderProgram(this); + if (glContext->isOpenGLES()) { + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader_es3)) + logs += m_shader->log(); + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader_es3)) + logs += m_shader->log(); + } else { + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader)) + logs += m_shader->log(); + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader)) + logs += m_shader->log(); + } + m_shader->link(); + logs += m_shader->log(); + if (!logs.isEmpty()) + qWarning() << logs; + m_shaderHandle = m_shader->programId(); + + m_attribLocationTex = m_funcs->glGetUniformLocation(m_shaderHandle, "Texture"); + m_attribLocationProjMtx = m_funcs->glGetUniformLocation(m_shaderHandle, "ProjMtx"); + m_attribLocationPosition = m_funcs->glGetAttribLocation(m_shaderHandle, "Position"); + m_attribLocationUV = m_funcs->glGetAttribLocation(m_shaderHandle, "UV"); + m_attribLocationColor = m_funcs->glGetAttribLocation(m_shaderHandle, "Color"); + + m_funcs->glGenBuffers(1, &m_vboHandle); + m_funcs->glGenBuffers(1, &m_elementsHandle); + + m_funcs->glGenVertexArrays(1, &m_vaoHandle); + m_funcs->glBindVertexArray(m_vaoHandle); + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle); + m_funcs->glEnableVertexAttribArray(m_attribLocationPosition); + m_funcs->glEnableVertexAttribArray(m_attribLocationUV); + m_funcs->glEnableVertexAttribArray(m_attribLocationColor); + +#define OFFSETOF(TYPE, ELEMENT) (reinterpret_cast(&((static_cast(nullptr))->ELEMENT))) + m_funcs->glVertexAttribPointer(m_attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, pos))); + m_funcs->glVertexAttribPointer(m_attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, uv))); + m_funcs->glVertexAttribPointer(m_attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, col))); +#undef OFFSETOF + + createFontsTexture(); + + // Restore modified GL state + m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); + m_funcs->glBindVertexArray(last_vertex_array); + + return true; +} + +bool ImGuiRenderer::newFrame(const RenderView *renderView) +{ + if (!m_funcs) + m_funcs = m_renderer->submissionContext()->openGLContext()->extraFunctions(); + if (!m_fontTexture) + createDeviceObjects(); + if (!m_shader) + return false; + + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + io.DisplaySize = ImVec2(renderView->surfaceSize().width() / renderView->devicePixelRatio(), renderView->surfaceSize().height() / renderView->devicePixelRatio()); + io.DisplayFramebufferScale = ImVec2(renderView->devicePixelRatio(), renderView->devicePixelRatio()); + + // Setup time step + double current_time = QDateTime::currentMSecsSinceEpoch() / 1000.; + io.DeltaTime = m_time > 0.0 ? static_cast(current_time - m_time) : 1.0f / 60.0f; + if (io.DeltaTime == 0.f) + io.DeltaTime = 1.0f / 60.0f; + m_time = current_time; + + // Setup inputs + for (int i = 0; i < 3; i++) + io.MouseDown[i] = m_mousePressed[i]; + + io.MouseWheelH = m_mouseWheelH; + io.MouseWheel = m_mouseWheel; + m_mouseWheelH = 0; + m_mouseWheel = 0; + + // Start the frame + ImGui::NewFrame(); + return true; +} + +void ImGuiRenderer::onMouseChange(QMouseEvent *event) +{ + ImGuiIO& io = ImGui::GetIO(); + io.MousePos = ImVec2(event->pos().x(), event->pos().y()); + m_mousePressed[0] = event->buttons() & Qt::LeftButton; + m_mousePressed[1] = event->buttons() & Qt::RightButton; + m_mousePressed[2] = event->buttons() & Qt::MiddleButton; +} + +void ImGuiRenderer::onWheel(QWheelEvent *event) +{ + // 5 lines per unit + m_mouseWheelH += event->pixelDelta().x() / (ImGui::GetTextLineHeight()); + m_mouseWheel += event->pixelDelta().y() / (5.f * ImGui::GetTextLineHeight()); +} + +void ImGuiRenderer::onKeyPressRelease(QKeyEvent *event) +{ + ImGuiIO& io = ImGui::GetIO(); + if (keyMap.contains(event->key())) + io.KeysDown[keyMap[event->key()]] = event->type() == QEvent::KeyPress; + + if (event->type() == QEvent::KeyPress) { + QString text = event->text(); + if (text.size() == 1) + io.AddInputCharacter(static_cast(text.at(0).unicode())); + } + +#ifdef Q_OS_DARWIN + io.KeyCtrl = event->modifiers() & Qt::MetaModifier; + io.KeyShift = event->modifiers() & Qt::ShiftModifier; + io.KeyAlt = event->modifiers() & Qt::AltModifier; + io.KeySuper = event->modifiers() & Qt::ControlModifier; // Command key +#else + io.KeyCtrl = event->modifiers() & Qt::ControlModifier; + io.KeyShift = event->modifiers() & Qt::ShiftModifier; + io.KeyAlt = event->modifiers() & Qt::AltModifier; + io.KeySuper = event->modifiers() & Qt::MetaModifier; +#endif +} + +void ImGuiRenderer::processEvent(QEvent *event) +{ + switch (event->type()) { + case QEvent::MouseMove: + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + this->onMouseChange(static_cast(event)); + break; + case QEvent::Wheel: + this->onWheel(static_cast(event)); + break; + case QEvent::KeyPress: + case QEvent::KeyRelease: + this->onKeyPressRelease(static_cast(event)); + break; + default: + break; + } +} + +QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/debug/imguirenderer_p.h b/src/render/renderers/opengl/debug/imguirenderer_p.h new file mode 100644 index 000000000..091e53897 --- /dev/null +++ b/src/render/renderers/opengl/debug/imguirenderer_p.h @@ -0,0 +1,132 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3D_RENDER_GL_IMGUIRENDER_H_ +#define QT3D_RENDER_GL_IMGUIRENDER_H_ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include + +struct ImDrawData; + +QT_BEGIN_NAMESPACE + +class QMouseEvent; +class QWheelEvent; +class QKeyEvent; +class QOpenGLExtraFunctions; +class QOpenGLShaderProgram; + +namespace Qt3DCore { +class QServiceLocator; +} + +namespace Qt3DRender { +namespace Render { + +class RenderView; +class Renderer; + +namespace Debug { + +#define IMGUI_PERF_LOG_SIZE 30 + +class ImGuiRenderer : public QObject { + Q_OBJECT +public: + ImGuiRenderer(Qt3DRender::Render::Renderer *renderer); + + void processEvent(QEvent *event); + void renderDebugOverlay(const QVector &renderViews, const Render::RenderView *renderView, int jobsInLastFrame); + +private: + bool newFrame(const RenderView *renderView); + void renderDrawList(ImDrawData *draw_data); + void onMouseChange(QMouseEvent *event); + void onWheel(QWheelEvent *event); + void onKeyPressRelease(QKeyEvent *event); + void showGLInfo(); + void showRenderDetails(const QVector &renderViews); + + bool createFontsTexture(); + bool createDeviceObjects(); + + double m_time = 0.; + bool m_mousePressed[3] = { false, false, false }; + float m_mouseWheel; + float m_mouseWheelH; + GLuint m_fontTexture = 0; + GLuint m_shaderHandle = 0, m_vertHandle = 0, m_fragHandle = 0; + int m_attribLocationTex = 0, m_attribLocationProjMtx = 0; + int m_attribLocationPosition = 0, m_attribLocationUV = 0, m_attribLocationColor = 0; + unsigned int m_vboHandle = 0, m_vaoHandle = 0, m_elementsHandle = 0; + + Renderer *m_renderer; + QOpenGLExtraFunctions *m_funcs = nullptr; + QOpenGLShaderProgram *m_shader = nullptr; + + bool m_showGLInfoWindow = false; + bool m_showRenderDetailsWindow = false; + + float m_fpsLog[IMGUI_PERF_LOG_SIZE]; + float m_jobsLog[IMGUI_PERF_LOG_SIZE]; + std::pair m_fpsRange; + std::pair m_jobsRange; +}; + +} // namespace Debug +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3D_RENDER_GL_IMGUIRENDER_H_ diff --git a/src/render/renderers/opengl/jobs/renderviewjobutils.cpp b/src/render/renderers/opengl/jobs/renderviewjobutils.cpp index 39917fb58..16d449d4a 100644 --- a/src/render/renderers/opengl/jobs/renderviewjobutils.cpp +++ b/src/render/renderers/opengl/jobs/renderviewjobutils.cpp @@ -236,6 +236,11 @@ void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, const FrameGraphN } break; } + + case FrameGraphNode::DebugOverlay: + rv->setShowDebugOverlay(true); + break; + case FrameGraphNode::RenderCapture: { auto *renderCapture = const_cast( static_cast(node)); diff --git a/src/render/renderers/opengl/opengl.pri b/src/render/renderers/opengl/opengl.pri index 908c23c80..f72f2d1a5 100644 --- a/src/render/renderers/opengl/opengl.pri +++ b/src/render/renderers/opengl/opengl.pri @@ -6,6 +6,8 @@ include (textures/textures.pri) include (graphicshelpers/graphicshelpers.pri) include (renderstates/renderstates.pri) +!integrity: include (debug/debug.pri) + gcov { QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage QMAKE_LFLAGS += -fprofile-arcs -ftest-coverage diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index bc8e5b205..b5b61b027 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -95,6 +95,9 @@ #include #include #include +#ifndef Q_OS_INTEGRITY +#include +#endif #include #include @@ -279,6 +282,8 @@ Renderer::Renderer(QRenderAspect::RenderType type) , m_offscreenHelper(nullptr) , m_commandExecuter(new Qt3DRender::Debug::CommandExecuter(this)) , m_shouldSwapBuffers(true) + , m_imGuiRenderer(nullptr) + , m_jobsInLastFrame(0) { // Set renderer as running - it will wait in the context of the // RenderThread for RenderViews to be submitted @@ -330,6 +335,10 @@ Renderer::~Renderer() if (!m_ownedContext) QObject::disconnect(m_contextConnection); + +#ifndef Q_OS_INTEGRITY + delete m_imGuiRenderer; +#endif } void Renderer::dumpInfo() const @@ -1485,6 +1494,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVectorshowDebugOverlay()) { + imGuiOverlayShown = true; + if (!m_imGuiRenderer) + m_imGuiRenderer = new Debug::ImGuiRenderer(this); + + { + QMutexLocker l(&m_frameEventsMutex); + for (auto &keyEvent: m_frameKeyEvents) + m_imGuiRenderer->processEvent(&keyEvent); + for (auto &mouseEvent: m_frameMouseEvents) + m_imGuiRenderer->processEvent(&mouseEvent.second); + } + m_imGuiRenderer->renderDebugOverlay(renderViews, renderView, m_jobsInLastFrame); + } +#endif frameElapsed = timer.elapsed() - frameElapsed; qCDebug(Rendering) << Q_FUNC_INFO << "Submitted Renderview " << i + 1 << "/" << renderViewsCount << "in " << frameElapsed << "ms"; @@ -1742,6 +1768,7 @@ void Renderer::skipNextFrame() void Renderer::jobsDone(Qt3DCore::QAspectManager *manager) { // called in main thread once all jobs are done running + m_jobsInLastFrame = manager->jobsInLastFrame(); // sync captured renders to frontend const QVector pendingCaptureIds = std::move(m_pendingRenderCaptureSendRequests); @@ -1761,6 +1788,24 @@ void Renderer::jobsDone(Qt3DCore::QAspectManager *manager) // Jobs we may have to run even if no rendering will happen QVector Renderer::preRenderingJobs() { + { + QMutexLocker l(&m_frameEventsMutex); + m_frameMouseEvents = m_pickEventFilter->pendingMouseEvents(); + m_frameKeyEvents = m_pickEventFilter->pendingKeyEvents(); + } + + // Set values on picking jobs + RenderSettings *renderSetting = settings(); + if (renderSetting != nullptr) { + m_pickBoundingVolumeJob->setRenderSettings(renderSetting); + m_pickBoundingVolumeJob->setFrameGraphRoot(frameGraphRoot()); + m_pickBoundingVolumeJob->setMouseEvents(m_frameMouseEvents); + m_pickBoundingVolumeJob->setKeyEvents(m_frameKeyEvents); + + m_rayCastingJob->setRenderSettings(renderSetting); + m_rayCastingJob->setFrameGraphRoot(frameGraphRoot()); + } + QVector jobs; // Do we need to notify frontend about fence change? @@ -1941,27 +1986,11 @@ QVector Renderer::renderBinJobs() QAspectJobPtr Renderer::pickBoundingVolumeJob() { - // Set values on pickBoundingVolumeJob - RenderSettings *renderSetting = settings(); - if (renderSetting != nullptr) { - m_pickBoundingVolumeJob->setRenderSettings(renderSetting); - m_pickBoundingVolumeJob->setFrameGraphRoot(frameGraphRoot()); - m_pickBoundingVolumeJob->setMouseEvents(pendingPickingEvents()); - m_pickBoundingVolumeJob->setKeyEvents(pendingKeyEvents()); - } - return m_pickBoundingVolumeJob; } QAspectJobPtr Renderer::rayCastingJob() { - // Set values on rayCastingJob - RenderSettings *renderSetting = settings(); - if (renderSetting != nullptr) { - m_rayCastingJob->setRenderSettings(renderSetting); - m_rayCastingJob->setFrameGraphRoot(frameGraphRoot()); - } - return m_rayCastingJob; } @@ -2311,16 +2340,6 @@ void Renderer::cleanGraphicsResources() } } -QList> Renderer::pendingPickingEvents() const -{ - return m_pickEventFilter->pendingMouseEvents(); -} - -QList Renderer::pendingKeyEvents() const -{ - return m_pickEventFilter->pendingKeyEvents(); -} - const GraphicsApiFilterData *Renderer::contextInfo() const { return m_submissionContext->contextInfo(); diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index a281eb28b..48e4a5e3d 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -167,6 +167,10 @@ using FilterEntityByComponentJobPtr = QSharedPointer; using RenderableEntityFilterPtr = FilterEntityByComponentJobPtr; +namespace Debug { +class ImGuiRenderer; +} + class Q_3DRENDERSHARED_PRIVATE_EXPORT Renderer : public AbstractRenderer { public: @@ -282,9 +286,6 @@ public: inline RenderStateSet *defaultRenderState() const { return m_defaultRenderStateSet; } - QList> pendingPickingEvents() const; - QList pendingKeyEvents() const; - void enqueueRenderView(RenderView *renderView, int submitOrder); bool isReadyToSubmit(); @@ -445,6 +446,12 @@ private: QVector m_frameGraphLeaves; QScreen *m_screen = nullptr; + + Debug::ImGuiRenderer *m_imGuiRenderer; + QList> m_frameMouseEvents; + QList m_frameKeyEvents; + QMutex m_frameEventsMutex; + int m_jobsInLastFrame; }; } // namespace Render diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp index 60ebc2193..f34015455 100644 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ b/src/render/renderers/opengl/renderer/renderview.cpp @@ -250,6 +250,7 @@ RenderView::RenderView() , m_noDraw(false) , m_compute(false) , m_frustumCulling(false) + , m_showDebugOverlay(false) , m_memoryBarrier(QMemoryBarrier::None) , m_environmentLight(nullptr) { diff --git a/src/render/renderers/opengl/renderer/renderview_p.h b/src/render/renderers/opengl/renderer/renderview_p.h index c7dc37a2c..6f31e40ef 100644 --- a/src/render/renderers/opengl/renderer/renderview_p.h +++ b/src/render/renderers/opengl/renderer/renderview_p.h @@ -201,6 +201,8 @@ public: const int *computeWorkGroups() const Q_DECL_NOTHROW { return m_workGroups; } inline bool frustumCulling() const Q_DECL_NOTHROW { return m_frustumCulling; } void setFrustumCulling(bool frustumCulling) Q_DECL_NOTHROW { m_frustumCulling = frustumCulling; } + bool showDebugOverlay() const Q_DECL_NOTHROW { return m_showDebugOverlay; } + void setShowDebugOverlay(bool showDebugOverlay) Q_DECL_NOTHROW { m_showDebugOverlay = showDebugOverlay; } inline void setMaterialParameterTable(const MaterialParameterGathererData ¶meters) Q_DECL_NOTHROW { m_parameters = parameters; } @@ -334,6 +336,7 @@ private: bool m_noDraw:1; bool m_compute:1; bool m_frustumCulling:1; + bool m_showDebugOverlay:1; int m_workGroups[3]; QMemoryBarrier::Operations m_memoryBarrier; QVector m_insertFenceIds; diff --git a/sync.profile b/sync.profile index 88c777606..71ba945d3 100644 --- a/sync.profile +++ b/sync.profile @@ -16,5 +16,7 @@ %moduleheaders = ( # restrict the module headers to those found in relative path ); +@ignore_headers = ( "imconfig.h", "imgui.h", "imgui_internal.h", "imstb_rectpack.h", "imstb_textedit.h", "imstb_truetype.h" ); + # Force generation of camel case headers for classes inside Qt3D* namespaces $publicclassregexp = "Qt3D.*::.+"; -- cgit v1.2.3 From 4ae7cc93b503cc31272f0b55c84410af30aea8b9 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Thu, 16 Jan 2020 16:48:21 +0000 Subject: Add QRenderCapabilities to query GL about what is supported Change-Id: I7981e7e4b514e5d15d66c82351f1ab2fe160d20d Reviewed-by: Paul Lemire --- examples/qt3d/scene3d/AnimatedEntity.qml | 4 +- examples/qt3d/scene3d/main.cpp | 2 +- examples/qt3d/scene3d/main.qml | 50 ++- .../imports/render/qt3dquick3drenderplugin.cpp | 3 + src/render/backend/rendersettings.cpp | 12 +- src/render/backend/rendersettings_p.h | 2 + src/render/frontend/qrendercapabilities.cpp | 431 +++++++++++++++++++++ src/render/frontend/qrendercapabilities.h | 144 +++++++ src/render/frontend/qrendercapabilities_p.h | 105 +++++ src/render/frontend/qrendersettings.cpp | 21 + src/render/frontend/qrendersettings.h | 4 +- src/render/frontend/qrendersettings_p.h | 2 + src/render/frontend/render-frontend.pri | 7 +- .../renderers/opengl/debug/imguirenderer.cpp | 25 +- .../renderers/opengl/debug/imguirenderer_p.h | 4 + src/render/renderers/opengl/renderer/renderer.cpp | 5 +- 16 files changed, 791 insertions(+), 30 deletions(-) create mode 100644 src/render/frontend/qrendercapabilities.cpp create mode 100644 src/render/frontend/qrendercapabilities.h create mode 100644 src/render/frontend/qrendercapabilities_p.h diff --git a/examples/qt3d/scene3d/AnimatedEntity.qml b/examples/qt3d/scene3d/AnimatedEntity.qml index 2cfeeb73a..77cc15aa3 100644 --- a/examples/qt3d/scene3d/AnimatedEntity.qml +++ b/examples/qt3d/scene3d/AnimatedEntity.qml @@ -49,7 +49,7 @@ ****************************************************************************/ import Qt3D.Core 2.0 -import Qt3D.Render 2.0 +import Qt3D.Render 2.15 import Qt3D.Input 2.0 import Qt3D.Extras 2.15 @@ -58,6 +58,7 @@ import QtQuick 2.0 as QQ2 Entity { id: sceneRoot + property RenderCapabilities capabilities : renderSettings.renderCapabilities Camera { id: camera @@ -74,6 +75,7 @@ Entity { components: [ RenderSettings { + id: renderSettings activeFrameGraph: ForwardRenderer { camera: camera clearColor: "transparent" diff --git a/examples/qt3d/scene3d/main.cpp b/examples/qt3d/scene3d/main.cpp index 8d8bc581e..2a988a271 100644 --- a/examples/qt3d/scene3d/main.cpp +++ b/examples/qt3d/scene3d/main.cpp @@ -71,7 +71,7 @@ int main(int argc, char **argv) QQuickView view; - view.resize(500, 500); + view.resize(1024, 768); view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource(QUrl("qrc:/main.qml")); view.show(); diff --git a/examples/qt3d/scene3d/main.qml b/examples/qt3d/scene3d/main.qml index f50528a13..6d5617ca3 100644 --- a/examples/qt3d/scene3d/main.qml +++ b/examples/qt3d/scene3d/main.qml @@ -50,6 +50,7 @@ import QtQuick 2.0 import QtQuick.Scene3D 2.0 +import Qt3D.Render 2.15 Item { Text { @@ -99,7 +100,54 @@ Item { aspects: ["input", "logic"] cameraAspectRatioMode: Scene3D.AutomaticAspectRatio - AnimatedEntity {} + AnimatedEntity { + id: rootEntity + } + } + } + + Rectangle { + radius: 10 + color: "#aaffffff" + border.width: 1 + border.color: "black" + width: childrenRect.width + anchors.margins + height: childrenRect.height + anchors.margins + anchors.bottom: parent.bottom + anchors.right: parent.right + anchors.margins: 20 + + Column { + x: parent.anchors.margins / 2 + y: x + + Text { text: "Vendor: " + rootEntity.capabilities.vendor } + Text { text: "Renderer: " + rootEntity.capabilities.renderer } + Text { text: "Driver Version: " + rootEntity.capabilities.driverVersion } + Text { text: "GL Version: " + rootEntity.capabilities.majorVersion + "." + rootEntity.capabilities.minorVersion } + Text { text: "Profile: " + (rootEntity.capabilities.profile === RenderCapabilities.CoreProfile ? "Core" : (rootEntity.capabilities.profile === RenderCapabilities.CompatibilityProfile ? "Compatibility" : "Unknown")) } + Text { text: "GLSL Version: " + rootEntity.capabilities.glslVersion } + Text { text: "Extensions: " + (rootEntity.capabilities.extensions.length ? "" : "None") } + ListView { + model: rootEntity.capabilities.extensions + delegate: Text { text: " " + model.modelData } + width: parent.width + height: 100 + visible: rootEntity.capabilities.extensions.length > 0 + clip: true + } + Text { text: "Max Texture Size: " + rootEntity.capabilities.maxTextureSize + "\nMax Texture Units: " + rootEntity.capabilities.maxTextureUnits + "\nMax Texture Layers: " + rootEntity.capabilities.maxTextureLayers } + Text { text: "Supports UBO: " + rootEntity.capabilities.supportsUBO } + Text { text: " Max UBO Size: " + rootEntity.capabilities.maxUBOSize + "\n Max UBO Bindings: " + rootEntity.capabilities.maxUBOBindings; visible: rootEntity.capabilities.supportsUBO } + Text { text: "Supports SSBO: " + rootEntity.capabilities.supportsSSBO } + Text { text: " Max SSBO Size: " + rootEntity.capabilities.maxSSBOSize + "\n Max SSBO Bindings: " + rootEntity.capabilities.maxSSBOBindings; visible: rootEntity.capabilities.supportsSSBO } + Text { text: "Supports Image Store: " + rootEntity.capabilities.supportsImageStore } + Text { text: " Max Image Units: " + rootEntity.capabilities.maxImageUnits; visible: rootEntity.capabilities.supportsImageStore } + Text { text: "Supports Compute Shaders: " + rootEntity.capabilities.supportsCompute } + Text { text: " Max Work Group Size: " + rootEntity.capabilities.maxWorkGroupSizeX + ", " + rootEntity.capabilities.maxWorkGroupSizeY + ", " + rootEntity.capabilities.maxWorkGroupSizeZ; visible: rootEntity.capabilities.supportsCompute } + Text { text: " Max Work Group Count: " + rootEntity.capabilities.maxWorkGroupCountX + ", " + rootEntity.capabilities.maxWorkGroupCountY + ", " + rootEntity.capabilities.maxWorkGroupCountZ; visible: rootEntity.capabilities.supportsCompute } + Text { text: " Max Invocations: " + rootEntity.capabilities.maxComputeInvocations; visible: rootEntity.capabilities.supportsCompute } + Text { text: " Max Shared Memory: " + rootEntity.capabilities.maxComputeSharedMemorySize; visible: rootEntity.capabilities.supportsCompute } } } diff --git a/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp b/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp index e16314c8e..e47d28f7c 100644 --- a/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp +++ b/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp @@ -119,6 +119,7 @@ #include #include #include +#include #include @@ -169,7 +170,9 @@ void Qt3DQuick3DRenderPlugin::registerTypes(const char *uri) // Renderer setttings qmlRegisterType(uri, 2, 0, "RenderSettings"); + qmlRegisterType(uri, 2, 15, "RenderSettings"); qmlRegisterType(uri, 2, 0, "PickingSettings"); + qmlRegisterUncreatableType(uri, 2, 15, "RenderCapabilities", "Only available as a property of RenderSettings"); // @uri Qt3D.Render Qt3DRender::Quick::registerExtendedType("QSceneLoader", "Qt3D.Render/SceneLoader", uri, 2, 0, "SceneLoader"); diff --git a/src/render/backend/rendersettings.cpp b/src/render/backend/rendersettings.cpp index 5aeaa2563..3af617bfc 100644 --- a/src/render/backend/rendersettings.cpp +++ b/src/render/backend/rendersettings.cpp @@ -42,6 +42,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -87,7 +88,7 @@ void RenderSettings::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs m_pickResultMode = ncnode->pickingSettings()->pickResultMode(); } - if (ncnode->pickingSettings()->worldSpaceTolerance() != m_pickWorldSpaceTolerance) { + if (!qFuzzyCompare(ncnode->pickingSettings()->worldSpaceTolerance(), m_pickWorldSpaceTolerance)) { m_pickWorldSpaceTolerance = ncnode->pickingSettings()->worldSpaceTolerance(); } @@ -95,6 +96,9 @@ void RenderSettings::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs m_faceOrientationPickingMode = ncnode->pickingSettings()->faceOrientationPickingMode(); } + if (firstTime) + m_capabilities = QRenderCapabilitiesPrivate::get(const_cast(node)->renderCapabilities())->toString(); + // Either because something above as changed or if QRenderSettingsPrivate::invalidFrame() // was called markDirty(AbstractRenderer::AllDirty); @@ -107,7 +111,7 @@ RenderSettingsFunctor::RenderSettingsFunctor(AbstractRenderer *renderer) Qt3DCore::QBackendNode *RenderSettingsFunctor::create(const Qt3DCore::QNodeCreatedChangeBasePtr &change) const { - Q_UNUSED(change); + Q_UNUSED(change) if (m_renderer->settings() != nullptr) { qWarning() << "Renderer settings already exists"; return nullptr; @@ -121,13 +125,13 @@ Qt3DCore::QBackendNode *RenderSettingsFunctor::create(const Qt3DCore::QNodeCreat Qt3DCore::QBackendNode *RenderSettingsFunctor::get(Qt3DCore::QNodeId id) const { - Q_UNUSED(id); + Q_UNUSED(id) return m_renderer->settings(); } void RenderSettingsFunctor::destroy(Qt3DCore::QNodeId id) const { - Q_UNUSED(id); + Q_UNUSED(id) // Deletes the old settings object auto settings = m_renderer->settings(); if (settings && settings->peerId() == id) { diff --git a/src/render/backend/rendersettings_p.h b/src/render/backend/rendersettings_p.h index 1c8c0ca72..317fca957 100644 --- a/src/render/backend/rendersettings_p.h +++ b/src/render/backend/rendersettings_p.h @@ -75,6 +75,7 @@ public: QPickingSettings::PickResultMode pickResultMode() const { return m_pickResultMode; } QPickingSettings::FaceOrientationPickingMode faceOrientationPickingMode() const { return m_faceOrientationPickingMode; } float pickWorldSpaceTolerance() const { return m_pickWorldSpaceTolerance; } + QString capabilities() const { return m_capabilities; } // For unit test purposes void setActiveFrameGraphId(Qt3DCore::QNodeId frameGraphNodeId) { m_activeFrameGraph = frameGraphNodeId; } @@ -86,6 +87,7 @@ private: QPickingSettings::FaceOrientationPickingMode m_faceOrientationPickingMode; float m_pickWorldSpaceTolerance; Qt3DCore::QNodeId m_activeFrameGraph; + QString m_capabilities; }; class RenderSettingsFunctor : public Qt3DCore::QBackendNodeMapper diff --git a/src/render/frontend/qrendercapabilities.cpp b/src/render/frontend/qrendercapabilities.cpp new file mode 100644 index 000000000..f614a528c --- /dev/null +++ b/src/render/frontend/qrendercapabilities.cpp @@ -0,0 +1,431 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qrendercapabilities.h" +#include "qrendercapabilities_p.h" + +#include +#include +#include +#include +#include +#include + +#ifndef GL_MAX_UNIFORM_BLOCK_SIZE +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#endif + +#ifndef GL_MAX_UNIFORM_BLOCK_SIZE +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#endif + +#ifndef GL_MAX_SAMPLES +#define GL_MAX_SAMPLES 0x8D57 +#endif + +#ifndef GL_MAX_UNIFORM_BUFFER_BINDINGS +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#endif + +#ifndef GL_MAX_UNIFORM_BLOCK_SIZE +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#endif + +#ifndef GL_MAX_ARRAY_TEXTURE_LAYERS +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#endif + +#ifndef GL_MAX_IMAGE_UNITS +#define GL_MAX_IMAGE_UNITS 0x8F38 +#endif + +#ifndef GL_MAX_SHADER_STORAGE_BLOCK_SIZE +#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE +#endif + +#ifndef GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS +#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD +#endif + +#ifndef GL_MAX_COMPUTE_WORK_GROUP_SIZE +#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF +#endif + +#ifndef GL_MAX_COMPUTE_WORK_GROUP_COUNT +#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE +#endif + +#ifndef GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS +#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB +#endif + +#ifndef GL_MAX_COMPUTE_SHARED_MEMORY_SIZE +#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 +#endif + + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +/*! + \class Qt3DRender::QRenderCapabilities + \brief The QRenderCapabilities class holds settings related to available rendering engines + */ + +/*! + \qmltype RenderCapabilities + \brief The QRenderCapabilities class holds settings related to available rendering engines + \since 5.15 + \inqmlmodule Qt3D.Render + \instantiates Qt3DRender::QRenderCapabilities + */ + + +/*! \internal */ +QRenderCapabilitiesPrivate::QRenderCapabilitiesPrivate() + : QObjectPrivate() + , m_valid(false) +{ + QOffscreenSurface offscreen; + QOpenGLContext ctx; + + offscreen.setFormat(QSurfaceFormat::defaultFormat()); + offscreen.create(); + Q_ASSERT_X(offscreen.isValid(), Q_FUNC_INFO, "Unable to create offscreen surface to gather capabilities"); + + ctx.setFormat(QSurfaceFormat::defaultFormat()); + if (ctx.create()) { + m_valid = true; + ctx.makeCurrent(&offscreen); + const QSurfaceFormat format = ctx.format(); + auto funcs = ctx.functions(); + + if (ctx.isOpenGLES()) + m_api = QRenderCapabilities::OpenGLES; + else + m_api = QRenderCapabilities::OpenGL; + m_profile = static_cast(format.profile()); + m_majorVersion = format.majorVersion(); + m_minorVersion = format.minorVersion(); + const QSet extensions = ctx.extensions(); + std::transform(std::begin(extensions), std::end(extensions), std::back_inserter(m_extensions), [](const QByteArray &e) { + return QLatin1String(e.data()); + }); + std::sort(std::begin(m_extensions), std::end(m_extensions)); + m_vendor = QString::fromUtf8(reinterpret_cast(funcs->glGetString(GL_VENDOR))); + m_renderer = QString::fromUtf8(reinterpret_cast(funcs->glGetString(GL_RENDERER))); + m_version = QString::fromUtf8(reinterpret_cast(funcs->glGetString(GL_VERSION))); + m_glslVersion = QString::fromUtf8(reinterpret_cast(funcs->glGetString(GL_SHADING_LANGUAGE_VERSION))); + + funcs->glGetIntegerv(GL_MAX_SAMPLES, &m_maxSamples); + funcs->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &m_maxTextureSize); + funcs->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &m_maxTextureUnits); + + if (m_majorVersion >= 3) { + if (m_minorVersion >= 1) { + m_supportsUBO = true; + funcs->glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &m_maxUBOSize); + funcs->glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &m_maxUBOBindings); + } + + funcs->glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &m_maxTextureLayers); + } + if ((m_api == QRenderCapabilities::OpenGL && m_majorVersion >= 4 && m_minorVersion >= 3) || + (m_api == QRenderCapabilities::OpenGLES && m_majorVersion >= 3 && m_minorVersion >= 2)) { + m_supportsSSBO = true; + m_supportCompute = true; + m_supportsImageStore = true; + funcs->glGetIntegerv(GL_MAX_IMAGE_UNITS, &m_maxImageUnits); + m_supportsSSBO = true; + funcs->glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &m_maxSSBOSize); + funcs->glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, &m_maxSSBOBindings); + + QOpenGLExtraFunctions *exfunc = nullptr; + if ((exfunc = ctx.extraFunctions()) != nullptr) { + for (int i = 0; i < 3; ++i) { + exfunc->glGetIntegeri_v( GL_MAX_COMPUTE_WORK_GROUP_SIZE, i, &m_maxWorkGroupSize[i] ); + exfunc->glGetIntegeri_v( GL_MAX_COMPUTE_WORK_GROUP_COUNT, i, &m_maxWorkGroupCount[i] ); + } + } + + funcs->glGetIntegerv( GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &m_maxComputeInvocations ); + funcs->glGetIntegerv( GL_MAX_COMPUTE_SHARED_MEMORY_SIZE, &m_maxComputeSharedMemorySize ); + } + + // TextureUnitCount, ImageUnitCount, ComputeSupport, ImageSupport, SSBO Support, UBO Support, extensions, Max RenderTargetCount would be a good start + } +} + +const QRenderCapabilitiesPrivate *QRenderCapabilitiesPrivate::get(const QRenderCapabilities *q) +{ + return q->d_func(); +} + +QString QRenderCapabilitiesPrivate::toString() const +{ + QString res; + + res += QString(QLatin1String("Vendor: %1\nRenderer: %2\nDriver Version: %3\nGL Version: %4.%5 (%6 Profile)\nGLSL Version: %7\n")) + .arg(m_vendor, m_renderer, m_version) + .arg(m_majorVersion).arg(m_minorVersion) + .arg(m_profile == QRenderCapabilities::CoreProfile ? QLatin1String("Core") : (m_profile == QRenderCapabilities::CompatibilityProfile ? QLatin1String("Compatibility") : QLatin1String("No"))) + .arg(m_glslVersion); + res += QString(QLatin1String("Extensions:\n %1\n")).arg(m_extensions.join(QLatin1String("\n "))); + res += QString(QLatin1String("Max Texture Size: %1\nMax Texture Units: %2\nMax Texture Layers: %3\n")).arg(m_maxTextureSize).arg(m_maxTextureUnits).arg(m_maxTextureLayers); + res += QString(QLatin1String("Supports UBO: %1\n")).arg(m_supportsUBO ? QLatin1String("True") : QLatin1String("False")); + if (m_supportsUBO) + res += QString(QLatin1String(" Max UBO Size: %1\n Max UBO Bindings: %2\n")).arg(m_maxUBOSize).arg(m_maxUBOBindings); + res += QString(QLatin1String("Supports SSBO: %1\n")).arg(m_supportsSSBO ? QLatin1String("True") : QLatin1String("False")); + if (m_supportsSSBO) + res += QString(QLatin1String(" Max SSBO Size: %1\n Max SSBO Bindings: %2\n")).arg(m_maxSSBOSize).arg(m_maxSSBOBindings); + res += QString(QLatin1String("Supports Image Store: %1\n")).arg(m_supportsImageStore ? QLatin1String("True") : QLatin1String("False")); + if (m_supportsImageStore) + res += QString(QLatin1String(" Max Image Units: %1\n")).arg(m_maxImageUnits); + res += QString(QLatin1String("Supports Compute Shaders: %1\n")).arg(m_supportCompute ? QLatin1String("True") : QLatin1String("False")); + if (m_supportCompute) + res += QString(QLatin1String(" Max Work Group Size: %1, %2, %3\n Max Work Group Count: %4, %5, %6\n Max Invocations: %6\n Max Shared Memory Size: %7\n")) + .arg(m_maxWorkGroupSize[0]).arg(m_maxWorkGroupSize[1]).arg(m_maxWorkGroupSize[2]) + .arg(m_maxWorkGroupCount[0]).arg(m_maxWorkGroupCount[1]).arg(m_maxWorkGroupCount[2]) + .arg(m_maxComputeInvocations).arg(m_maxComputeSharedMemorySize); + return res; +} + + +QRenderCapabilities::QRenderCapabilities(QObject *parent) + : QObject(*new QRenderCapabilitiesPrivate, parent) +{ + +} + +/*! \internal */ +QRenderCapabilities::~QRenderCapabilities() +{ +} + + +bool QRenderCapabilities::isValid() const +{ + Q_D(const QRenderCapabilities); + return d->m_valid; +} + +QRenderCapabilities::API QRenderCapabilities::api() const +{ + Q_D(const QRenderCapabilities); + return d->m_api; +} + +QRenderCapabilities::Profile QRenderCapabilities::profile() const +{ + Q_D(const QRenderCapabilities); + return d->m_profile; +} + +int QRenderCapabilities::majorVersion() const +{ + Q_D(const QRenderCapabilities); + return d->m_majorVersion; +} + +int QRenderCapabilities::minorVersion() const +{ + Q_D(const QRenderCapabilities); + return d->m_minorVersion; +} + +QStringList QRenderCapabilities::extensions() const +{ + Q_D(const QRenderCapabilities); + return d->m_extensions; +} + +QString QRenderCapabilities::vendor() const +{ + Q_D(const QRenderCapabilities); + return d->m_vendor; +} + +QString QRenderCapabilities::renderer() const +{ + Q_D(const QRenderCapabilities); + return d->m_renderer; +} + +QString QRenderCapabilities::driverVersion() const +{ + Q_D(const QRenderCapabilities); + return d->m_version; +} + +QString QRenderCapabilities::glslVersion() const +{ + Q_D(const QRenderCapabilities); + return d->m_glslVersion; +} + +int QRenderCapabilities::maxSamples() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxSamples; +} + +int QRenderCapabilities::maxTextureSize() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxTextureSize; +} + +int QRenderCapabilities::maxTextureUnits() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxTextureUnits; +} + +int QRenderCapabilities::maxTextureLayers() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxTextureLayers; +} + +bool QRenderCapabilities::supportsUBO() const +{ + Q_D(const QRenderCapabilities); + return d->m_supportsUBO; +} + +int QRenderCapabilities::maxUBOSize() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxUBOSize; +} + +int QRenderCapabilities::maxUBOBindings() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxUBOBindings; +} + +bool QRenderCapabilities::supportsSSBO() const +{ + Q_D(const QRenderCapabilities); + return d->m_supportsSSBO; +} + +int QRenderCapabilities::maxSSBOSize() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxSSBOSize; +} + +int QRenderCapabilities::maxSSBOBindings() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxSSBOBindings; +} + +bool QRenderCapabilities::supportsImageStore() const +{ + Q_D(const QRenderCapabilities); + return d->m_supportsImageStore; +} + +int QRenderCapabilities::maxImageUnits() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxImageUnits; +} + +bool QRenderCapabilities::supportsCompute() const +{ + Q_D(const QRenderCapabilities); + return d->m_supportCompute; +} + +int QRenderCapabilities::maxWorkGroupCountX() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxWorkGroupCount[0]; +} + +int QRenderCapabilities::maxWorkGroupCountY() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxWorkGroupCount[1]; +} + +int QRenderCapabilities::maxWorkGroupCountZ() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxWorkGroupCount[2]; +} + +int QRenderCapabilities::maxWorkGroupSizeX() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxWorkGroupSize[0]; +} + +int QRenderCapabilities::maxWorkGroupSizeY() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxWorkGroupSize[1]; +} + +int QRenderCapabilities::maxWorkGroupSizeZ() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxWorkGroupSize[2]; +} + +int QRenderCapabilities::maxComputeInvocations() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxComputeInvocations; +} + +int QRenderCapabilities::maxComputeSharedMemorySize() const +{ + Q_D(const QRenderCapabilities); + return d->m_maxComputeSharedMemorySize; +} + +} // namespace Qt3Drender + +QT_END_NAMESPACE diff --git a/src/render/frontend/qrendercapabilities.h b/src/render/frontend/qrendercapabilities.h new file mode 100644 index 000000000..cbbb5a23d --- /dev/null +++ b/src/render/frontend/qrendercapabilities.h @@ -0,0 +1,144 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_QRENDERCAPABILITIES_H +#define QT3DRENDER_QRENDERCAPABILITIES_H + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class QRenderCapabilitiesPrivate; + +class Q_3DRENDERSHARED_EXPORT QRenderCapabilities : public QObject +{ + Q_OBJECT + Q_PROPERTY(bool valid READ isValid CONSTANT) + Q_PROPERTY(API api READ api CONSTANT) + Q_PROPERTY(Profile profile READ profile CONSTANT) + Q_PROPERTY(int majorVersion READ majorVersion CONSTANT) + Q_PROPERTY(int minorVersion READ minorVersion CONSTANT) + Q_PROPERTY(QStringList extensions READ extensions CONSTANT) + Q_PROPERTY(QString vendor READ vendor CONSTANT) + Q_PROPERTY(QString renderer READ renderer CONSTANT) + Q_PROPERTY(QString driverVersion READ driverVersion CONSTANT) + Q_PROPERTY(QString glslVersion READ glslVersion CONSTANT) + Q_PROPERTY(int maxSamples READ maxSamples CONSTANT) + Q_PROPERTY(int maxTextureSize READ maxTextureSize CONSTANT) + Q_PROPERTY(int maxTextureUnits READ maxTextureUnits CONSTANT) + Q_PROPERTY(int maxTextureLayers READ maxTextureLayers CONSTANT) + Q_PROPERTY(bool supportsUBO READ supportsUBO CONSTANT) + Q_PROPERTY(int maxUBOSize READ maxUBOSize CONSTANT) + Q_PROPERTY(int maxUBOBindings READ maxUBOBindings CONSTANT) + Q_PROPERTY(bool supportsSSBO READ supportsSSBO CONSTANT) + Q_PROPERTY(int maxSSBOSize READ maxSSBOSize CONSTANT) + Q_PROPERTY(int maxSSBOBindings READ maxSSBOBindings CONSTANT) + Q_PROPERTY(bool supportsImageStore READ supportsImageStore CONSTANT) + Q_PROPERTY(int maxImageUnits READ maxImageUnits CONSTANT) + Q_PROPERTY(bool supportsCompute READ supportsCompute CONSTANT) + Q_PROPERTY(int maxWorkGroupCountX READ maxWorkGroupCountX CONSTANT) + Q_PROPERTY(int maxWorkGroupCountY READ maxWorkGroupCountY CONSTANT) + Q_PROPERTY(int maxWorkGroupCountZ READ maxWorkGroupCountZ CONSTANT) + Q_PROPERTY(int maxWorkGroupSizeX READ maxWorkGroupSizeX CONSTANT) + Q_PROPERTY(int maxWorkGroupSizeY READ maxWorkGroupSizeY CONSTANT) + Q_PROPERTY(int maxWorkGroupSizeZ READ maxWorkGroupSizeZ CONSTANT) + Q_PROPERTY(int maxComputeInvocations READ maxComputeInvocations CONSTANT) + Q_PROPERTY(int maxComputeSharedMemorySize READ maxComputeSharedMemorySize CONSTANT) +public: + enum API { + OpenGL = QSurfaceFormat::OpenGL, + OpenGLES = QSurfaceFormat::OpenGLES, + }; + Q_ENUM(API) + + enum Profile { + NoProfile = QSurfaceFormat::NoProfile, + CoreProfile = QSurfaceFormat::CoreProfile, + CompatibilityProfile = QSurfaceFormat::CompatibilityProfile + }; + Q_ENUM(Profile) + + explicit QRenderCapabilities(QObject *parent = nullptr); + ~QRenderCapabilities(); + + bool isValid() const; + API api() const; + Profile profile() const; + int majorVersion() const; + int minorVersion() const; + QStringList extensions() const; + QString vendor() const; + QString renderer() const; + QString driverVersion() const; + QString glslVersion() const; + int maxSamples() const; + int maxTextureSize() const; + int maxTextureUnits() const; + int maxTextureLayers() const; + bool supportsUBO() const; + int maxUBOSize() const; + int maxUBOBindings() const; + bool supportsSSBO() const; + int maxSSBOSize() const; + int maxSSBOBindings() const; + bool supportsImageStore() const; + int maxImageUnits() const; + bool supportsCompute() const; + int maxWorkGroupCountX() const; + int maxWorkGroupCountY() const; + int maxWorkGroupCountZ() const; + int maxWorkGroupSizeX() const; + int maxWorkGroupSizeY() const; + int maxWorkGroupSizeZ() const; + int maxComputeInvocations() const; + int maxComputeSharedMemorySize() const; + +protected: + Q_DECLARE_PRIVATE(QRenderCapabilities) +}; + +} // namespace Qt3Drender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_QRENDERCAPABILITIES_H diff --git a/src/render/frontend/qrendercapabilities_p.h b/src/render/frontend/qrendercapabilities_p.h new file mode 100644 index 000000000..0a91808d2 --- /dev/null +++ b/src/render/frontend/qrendercapabilities_p.h @@ -0,0 +1,105 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_QRENDERCAPABILITIES_P_H +#define QT3DRENDER_QRENDERCAPABILITIES_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class Q_3DRENDERSHARED_PRIVATE_EXPORT QRenderCapabilitiesPrivate : public QObjectPrivate +{ +public: + QRenderCapabilitiesPrivate(); + + Q_DECLARE_PUBLIC(QRenderCapabilities) + static const QRenderCapabilitiesPrivate *get(const QRenderCapabilities *q); + + bool m_valid; + QRenderCapabilities::API m_api = QRenderCapabilities::OpenGL; + QRenderCapabilities::Profile m_profile = QRenderCapabilities::NoProfile; + int m_majorVersion = 0; + int m_minorVersion = 0; + QStringList m_extensions; + QString m_vendor; + QString m_renderer; + QString m_version; + QString m_glslVersion; + int m_maxSamples = 0; + int m_maxTextureSize = 0; + int m_maxTextureUnits = 0; + int m_maxTextureLayers = 0; + bool m_supportsUBO = false; + int m_maxUBOSize = 0; + int m_maxUBOBindings = 0; + bool m_supportsSSBO = false; + int m_maxSSBOSize = 0; + int m_maxSSBOBindings = 0; + bool m_supportsImageStore = false; + int m_maxImageUnits = 0; + bool m_supportCompute = false; + int m_maxWorkGroupCount[3] = { 0, 0, 0 }; + int m_maxWorkGroupSize[3] = { 0, 0, 0 }; + int m_maxComputeInvocations = 0; + int m_maxComputeSharedMemorySize = 0; + + QString toString() const; +}; + +} // namespace Qt3Drender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_QRENDERCAPABILITIES_P_H diff --git a/src/render/frontend/qrendersettings.cpp b/src/render/frontend/qrendersettings.cpp index 491d3e442..179df151a 100644 --- a/src/render/frontend/qrendersettings.cpp +++ b/src/render/frontend/qrendersettings.cpp @@ -39,6 +39,7 @@ #include "qrendersettings.h" #include "qrendersettings_p.h" +#include "qrendercapabilities.h" #include "qframegraphnode.h" #include "qrendersurfaceselector.h" #include "qrendersurfaceselector_p.h" @@ -141,6 +142,26 @@ QRenderSettings::~QRenderSettings() { } +/*! + \qmlproperty RenderCapabilities RenderSettings::renderCapabilities + + Holds the details of the supported rendering engine + + \readonly +*/ +/*! + \property QRenderSettings::renderCapabilities + + Holds the details of the supported rendering engine + + \readonly +*/ +QRenderCapabilities *QRenderSettings::renderCapabilities() +{ + Q_D(QRenderSettings); + return &(d->m_renderCapabilities); +} + /*! \qmlproperty PickingSettings RenderSettings::pickingSettings diff --git a/src/render/frontend/qrendersettings.h b/src/render/frontend/qrendersettings.h index 9d2baa58b..1b4d68de9 100644 --- a/src/render/frontend/qrendersettings.h +++ b/src/render/frontend/qrendersettings.h @@ -49,12 +49,13 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { class QFrameGraphNode; +class QRenderCapabilities; class QRenderSettingsPrivate; class Q_3DRENDERSHARED_EXPORT QRenderSettings : public Qt3DCore::QComponent { Q_OBJECT - + Q_PROPERTY(Qt3DRender::QRenderCapabilities* renderCapabilities READ renderCapabilities CONSTANT REVISION 15) Q_PROPERTY(Qt3DRender::QPickingSettings* pickingSettings READ pickingSettings CONSTANT) Q_PROPERTY(RenderPolicy renderPolicy READ renderPolicy WRITE setRenderPolicy NOTIFY renderPolicyChanged) Q_PROPERTY(Qt3DRender::QFrameGraphNode *activeFrameGraph READ activeFrameGraph WRITE setActiveFrameGraph NOTIFY activeFrameGraphChanged) @@ -70,6 +71,7 @@ public: }; Q_ENUM(RenderPolicy) // LCOV_EXCL_LINE + QRenderCapabilities* renderCapabilities(); QPickingSettings* pickingSettings(); QFrameGraphNode *activeFrameGraph() const; RenderPolicy renderPolicy() const; diff --git a/src/render/frontend/qrendersettings_p.h b/src/render/frontend/qrendersettings_p.h index 88f91810a..85ba2d7cf 100644 --- a/src/render/frontend/qrendersettings_p.h +++ b/src/render/frontend/qrendersettings_p.h @@ -54,6 +54,7 @@ #include #include #include +#include #include QT_BEGIN_NAMESPACE @@ -70,6 +71,7 @@ public: QPickingSettings m_pickingSettings; QFrameGraphNode *m_activeFrameGraph; QRenderSettings::RenderPolicy m_renderPolicy; + QRenderCapabilities m_renderCapabilities; void invalidateFrame(); diff --git a/src/render/frontend/render-frontend.pri b/src/render/frontend/render-frontend.pri index 0153e9c97..694b5cfc1 100644 --- a/src/render/frontend/render-frontend.pri +++ b/src/render/frontend/render-frontend.pri @@ -28,7 +28,9 @@ HEADERS += \ $$PWD/qrenderplugin_p.h \ $$PWD/qrenderpluginfactory_p.h \ $$PWD/qrenderpluginfactoryif_p.h \ - $$PWD/qlevelofdetailboundingsphere.h + $$PWD/qlevelofdetailboundingsphere.h \ + $$PWD/qrendercapabilities.h \ + $$PWD/qrendercapabilities_p.h SOURCES += \ $$PWD/qabstractfunctor.cpp \ @@ -46,5 +48,6 @@ SOURCES += \ $$PWD/qcomputecommand.cpp \ $$PWD/qrenderpluginfactory.cpp \ $$PWD/qrenderpluginfactoryif.cpp \ - $$PWD/qlevelofdetailboundingsphere.cpp + $$PWD/qlevelofdetailboundingsphere.cpp \ + $$PWD/qrendercapabilities.cpp diff --git a/src/render/renderers/opengl/debug/imguirenderer.cpp b/src/render/renderers/opengl/debug/imguirenderer.cpp index d2a1cb925..f432970e4 100644 --- a/src/render/renderers/opengl/debug/imguirenderer.cpp +++ b/src/render/renderers/opengl/debug/imguirenderer.cpp @@ -300,28 +300,15 @@ void ImGuiRenderer::renderDebugOverlay(const QVector &renderViews, renderDrawList(ImGui::GetDrawData()); } -void ImGuiRenderer::showGLInfo() +void ImGuiRenderer::setCapabilities(const QString &capabilities) { - const GraphicsApiFilterData *contextInfo = m_renderer->submissionContext()->contextInfo(); + m_capabilities = capabilities.toLatin1(); +} +void ImGuiRenderer::showGLInfo() +{ ImGui::Begin("Open GL Details", &m_showGLInfoWindow); - - ImGui::Text("API: %s %d.%d", contextInfo->m_api == QGraphicsApiFilter::OpenGL ? "OpenGL" : "OpenGLES" - , contextInfo->m_major, contextInfo->m_minor); - if (contextInfo->m_api == QGraphicsApiFilter::OpenGL) - ImGui::Text("Profile: %s", contextInfo->m_profile == QGraphicsApiFilter::CoreProfile ? "Core" : - contextInfo->m_profile == QGraphicsApiFilter::CompatibilityProfile ? "Compatibity" : "Node"); - - // TODO show capabilities - GLint maxTextureSize, maxTextureUnits; - m_funcs->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); - m_funcs->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits); - ImGui::Text("Texture max size: %d Units: %d", maxTextureSize, maxTextureUnits); - - if (ImGui::Button("Dump")) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", - Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render glinfo"))); - + ImGui::Text("%s", m_capabilities.data()); ImGui::End(); } diff --git a/src/render/renderers/opengl/debug/imguirenderer_p.h b/src/render/renderers/opengl/debug/imguirenderer_p.h index 091e53897..e574574be 100644 --- a/src/render/renderers/opengl/debug/imguirenderer_p.h +++ b/src/render/renderers/opengl/debug/imguirenderer_p.h @@ -88,6 +88,8 @@ public: void processEvent(QEvent *event); void renderDebugOverlay(const QVector &renderViews, const Render::RenderView *renderView, int jobsInLastFrame); + void setCapabilities(const QString &capabilities); + private: bool newFrame(const RenderView *renderView); void renderDrawList(ImDrawData *draw_data); @@ -121,6 +123,8 @@ private: float m_jobsLog[IMGUI_PERF_LOG_SIZE]; std::pair m_fpsRange; std::pair m_jobsRange; + + QByteArray m_capabilities; }; } // namespace Debug diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index b5b61b027..a65e3c7ff 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -1681,8 +1681,11 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVectorshowDebugOverlay()) { imGuiOverlayShown = true; - if (!m_imGuiRenderer) + if (!m_imGuiRenderer) { m_imGuiRenderer = new Debug::ImGuiRenderer(this); + if (m_settings) + m_imGuiRenderer->setCapabilities(m_settings->capabilities()); + } { QMutexLocker l(&m_frameEventsMutex); -- cgit v1.2.3 From 7c1894cdf50b646a8733bf08d0b21a042aa147e6 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Tue, 21 Jan 2020 08:59:25 +0000 Subject: Make sure debug overlay is disabled by default Change-Id: If86115308a403e7fa7950488a8ca6c8dac966c1e Reviewed-by: Paul Lemire --- src/extras/defaults/qforwardrenderer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/extras/defaults/qforwardrenderer.cpp b/src/extras/defaults/qforwardrenderer.cpp index 9aef5aa84..1268ab03d 100644 --- a/src/extras/defaults/qforwardrenderer.cpp +++ b/src/extras/defaults/qforwardrenderer.cpp @@ -80,6 +80,7 @@ void QForwardRendererPrivate::init() initResources(); m_debugOverlay->setParent(m_frustumCulling); + m_debugOverlay->setEnabled(false); m_frustumCulling->setParent(m_clearBuffer); m_clearBuffer->setParent(m_cameraSelector); m_cameraSelector->setParent(m_viewport); -- cgit v1.2.3 From 4cd35e87b63d2ff4bc4ee88b6080f812de45d239 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Fri, 24 Jan 2020 11:08:48 +0000 Subject: Clean up tracing code - Removed some old optional timing code. - Separated jobsDone into 2 parts since, on single threaded rendering mode (ie macOS), the render aspect blocks until the next vsync which confuses tracing Change-Id: Icb641e3f8079da2cb9af0416b0f7c4dc4dd36c3c Reviewed-by: Paul Lemire --- src/core/aspects/aspects.pri | 2 -- src/core/aspects/qabstractaspect.cpp | 7 +++++-- src/core/aspects/qabstractaspect_p.h | 3 ++- src/core/aspects/qaspectmanager.cpp | 17 +++++------------ src/core/jobs/qaspectjobproviderinterface_p.h | 4 ++-- src/core/qscheduler.cpp | 5 +---- src/render/backend/abstractrenderer_p.h | 1 + src/render/frontend/qrenderaspect.cpp | 10 ++++++++-- src/render/frontend/qrenderaspect_p.h | 3 ++- src/render/renderers/opengl/renderer/renderer.cpp | 6 +++++- src/render/renderers/opengl/renderer/renderer_p.h | 1 + tests/auto/render/commons/testrenderer.h | 1 + 12 files changed, 33 insertions(+), 27 deletions(-) diff --git a/src/core/aspects/aspects.pri b/src/core/aspects/aspects.pri index 068f74389..268a2fc37 100644 --- a/src/core/aspects/aspects.pri +++ b/src/core/aspects/aspects.pri @@ -1,5 +1,3 @@ -#DEFINES += QT3D_CORE_JOB_TIMING - SOURCES += \ $$PWD/qabstractaspect.cpp \ $$PWD/qaspectengine.cpp \ diff --git a/src/core/aspects/qabstractaspect.cpp b/src/core/aspects/qabstractaspect.cpp index a2aed732b..824434ce6 100644 --- a/src/core/aspects/qabstractaspect.cpp +++ b/src/core/aspects/qabstractaspect.cpp @@ -508,9 +508,12 @@ QVector QAbstractAspectPrivate::jobsToExecute(qint64 time) return res; } -void QAbstractAspectPrivate::jobsDone(QAspectManager *manager) +void QAbstractAspectPrivate::jobsDone() +{ +} + +void QAbstractAspectPrivate::frameDone() { - Q_UNUSED(manager) } /*! diff --git a/src/core/aspects/qabstractaspect_p.h b/src/core/aspects/qabstractaspect_p.h index 9435f2bc6..dd13ac5bf 100644 --- a/src/core/aspects/qabstractaspect_p.h +++ b/src/core/aspects/qabstractaspect_p.h @@ -127,7 +127,8 @@ public: QAbstractAspectJobManager *jobManager() const; QVector jobsToExecute(qint64 time) override; - void jobsDone(Qt3DCore::QAspectManager *manager) override; + void jobsDone() override; // called when all the jobs are completed + void frameDone() override; // called when frame is completed (after the jobs), safe to wait until next frame here QBackendNode *createBackendNode(const NodeTreeChange &change) const; void clearBackendNode(const NodeTreeChange &change) const; diff --git a/src/core/aspects/qaspectmanager.cpp b/src/core/aspects/qaspectmanager.cpp index 662860db2..f0dc366b2 100644 --- a/src/core/aspects/qaspectmanager.cpp +++ b/src/core/aspects/qaspectmanager.cpp @@ -68,10 +68,6 @@ #include #include -#if defined(QT3D_CORE_JOB_TIMING) -#include -#endif - QT_BEGIN_NAMESPACE namespace Qt3DCore { @@ -496,7 +492,7 @@ void QAspectManager::processFrame() // without any such data race. { // scope for QTaskLogger - QTaskLogger logger(m_serviceLocator->systemInformation(), 4096, 0); + QTaskLogger logger(m_serviceLocator->systemInformation(), 4096, 0, QTaskLogger::AspectJob); // Tell the NodePostConstructorInit to process any pending nodes which will add them to our list of // tree changes @@ -541,14 +537,11 @@ void QAspectManager::processFrame() // For each Aspect // Ask them to launch set of jobs for the current frame // Updates matrices, bounding volumes, render bins ... -#if defined(QT3D_CORE_JOB_TIMING) - QElapsedTimer timer; - timer.start(); -#endif m_jobsInLastFrame = m_scheduler->scheduleAndWaitForFrameAspectJobs(t); -#if defined(QT3D_CORE_JOB_TIMING) - qDebug() << "Jobs took" << timer.nsecsElapsed() / 1.0e6; -#endif + + // Tell the aspect the frame is complete (except rendering) + for (QAbstractAspect *aspect : qAsConst(m_aspects)) + QAbstractAspectPrivate::get(aspect)->frameDone(); } } // namespace Qt3DCore diff --git a/src/core/jobs/qaspectjobproviderinterface_p.h b/src/core/jobs/qaspectjobproviderinterface_p.h index b521fea68..bb2c5ed88 100644 --- a/src/core/jobs/qaspectjobproviderinterface_p.h +++ b/src/core/jobs/qaspectjobproviderinterface_p.h @@ -61,7 +61,6 @@ QT_BEGIN_NAMESPACE namespace Qt3DCore { class QScheduler; -class QAspectManager; class QAspectJobProviderInterface { @@ -70,7 +69,8 @@ public: private: virtual QVector jobsToExecute(qint64 time) = 0; - virtual void jobsDone(QAspectManager *manager) = 0; + virtual void jobsDone() = 0; + virtual void frameDone() = 0; friend class QScheduler; }; diff --git a/src/core/qscheduler.cpp b/src/core/qscheduler.cpp index 2294976ca..b371a5fb1 100644 --- a/src/core/qscheduler.cpp +++ b/src/core/qscheduler.cpp @@ -94,13 +94,10 @@ int QScheduler::scheduleAndWaitForFrameAspectJobs(qint64 time) m_aspectManager->jobManager()->waitForAllJobs(); { - QTaskLogger logger(m_aspectManager->serviceLocator()->systemInformation(), 4097, 0); + QTaskLogger logger(m_aspectManager->serviceLocator()->systemInformation(), 4097, 0, QTaskLogger::AspectJob); for (auto &job : qAsConst(jobQueue)) QAspectJobPrivate::get(job.data())->postFrame(m_aspectManager); - - for (QAbstractAspect *aspect : aspects) - QAbstractAspectPrivate::get(aspect)->jobsDone(m_aspectManager); } return jobQueue.size(); diff --git a/src/render/backend/abstractrenderer_p.h b/src/render/backend/abstractrenderer_p.h index 8bbfcd548..74457e79f 100644 --- a/src/render/backend/abstractrenderer_p.h +++ b/src/render/backend/abstractrenderer_p.h @@ -126,6 +126,7 @@ public: virtual qint64 time() const = 0; virtual void setTime(qint64 time) = 0; + virtual void setJobsInLastFrame(int jobsInLastFrame) = 0; virtual void setNodeManagers(NodeManagers *managers) = 0; virtual void setServices(Qt3DCore::QServiceLocator *services) = 0; diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index a65f66fd7..1ce9f172f 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -173,6 +173,7 @@ #include #include #include +#include #include #include @@ -246,9 +247,14 @@ void QRenderAspectPrivate::syncDirtyFrontEndNode(QNode *node, QBackendNode *back renderBackend->syncFromFrontEnd(node, firstTime); } -void QRenderAspectPrivate::jobsDone(QAspectManager *manager) +void QRenderAspectPrivate::jobsDone() { - m_renderer->jobsDone(manager); + m_renderer->jobsDone(m_aspectManager); +} + +void QRenderAspectPrivate::frameDone() +{ + m_renderer->setJobsInLastFrame(m_aspectManager->jobsInLastFrame()); if (m_renderAfterJobs) m_renderer->doRender(true); } diff --git a/src/render/frontend/qrenderaspect_p.h b/src/render/frontend/qrenderaspect_p.h index 8723180ab..0a9f4ec46 100644 --- a/src/render/frontend/qrenderaspect_p.h +++ b/src/render/frontend/qrenderaspect_p.h @@ -87,7 +87,8 @@ public: static QRenderAspectPrivate* findPrivate(Qt3DCore::QAspectEngine *engine); void syncDirtyFrontEndNode(Qt3DCore::QNode *node, Qt3DCore::QBackendNode *backend, bool firstTime) const override; - void jobsDone(Qt3DCore::QAspectManager *manager) override; + void jobsDone() override; + void frameDone() override; void registerBackendTypes(); void unregisterBackendTypes(); diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index a65e3c7ff..c0549a8fd 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -368,6 +368,11 @@ void Renderer::setTime(qint64 time) m_time = time; } +void Renderer::setJobsInLastFrame(int jobsInLastFrame) +{ + m_jobsInLastFrame = jobsInLastFrame; +} + void Renderer::setNodeManagers(NodeManagers *managers) { m_nodesManager = managers; @@ -1771,7 +1776,6 @@ void Renderer::skipNextFrame() void Renderer::jobsDone(Qt3DCore::QAspectManager *manager) { // called in main thread once all jobs are done running - m_jobsInLastFrame = manager->jobsInLastFrame(); // sync captured renders to frontend const QVector pendingCaptureIds = std::move(m_pendingRenderCaptureSendRequests); diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index 48e4a5e3d..4b8574252 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -182,6 +182,7 @@ public: qint64 time() const override; void setTime(qint64 time) override; + void setJobsInLastFrame(int jobsInLastFrame) override; void setNodeManagers(NodeManagers *managers) override; void setServices(Qt3DCore::QServiceLocator *services) override; diff --git a/tests/auto/render/commons/testrenderer.h b/tests/auto/render/commons/testrenderer.h index 05ef4c130..1241bb0e0 100644 --- a/tests/auto/render/commons/testrenderer.h +++ b/tests/auto/render/commons/testrenderer.h @@ -43,6 +43,7 @@ public: API api() const override { return AbstractRenderer::OpenGL; } qint64 time() const override { return 0; } void setTime(qint64 time) override { Q_UNUSED(time) } + void setJobsInLastFrame(int jobsInLastFrame) override { Q_UNUSED(jobsInLastFrame) } void setNodeManagers(Qt3DRender::Render::NodeManagers *m) override { m_managers = m; } void setServices(Qt3DCore::QServiceLocator *services) override { Q_UNUSED(services) } void setSurfaceExposed(bool exposed) override { Q_UNUSED(exposed) } -- cgit v1.2.3 From 650d065d3b03825ff97600902c164d447cbb771a Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Mon, 27 Jan 2020 10:54:01 +0000 Subject: Fix potential crash when logic aspect exits Logic aspect does work in response to posted event. By that time the aspect may be gone (due to normal shutdown) and the scene pointer be invalid. Change-Id: Ia9454532a7c95cd3c00e8b225b8d95c178471a67 Reviewed-by: Paul Lemire --- src/logic/executor.cpp | 4 +++- src/logic/qlogicaspect.cpp | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/logic/executor.cpp b/src/logic/executor.cpp index 1c428db47..41d2f2e31 100644 --- a/src/logic/executor.cpp +++ b/src/logic/executor.cpp @@ -89,7 +89,9 @@ bool Executor::event(QEvent *e) */ void Executor::processLogicFrameUpdates(float dt) { - Q_ASSERT(m_scene); + if (!m_scene || m_nodeIds.isEmpty()) + return; + const QVector nodes = m_scene->lookupNodes(m_nodeIds); for (QNode *node : nodes) { QFrameAction *frameAction = qobject_cast(node); diff --git a/src/logic/qlogicaspect.cpp b/src/logic/qlogicaspect.cpp index 649a14f25..c4459a84d 100644 --- a/src/logic/qlogicaspect.cpp +++ b/src/logic/qlogicaspect.cpp @@ -84,6 +84,7 @@ void QLogicAspectPrivate::onEngineAboutToShutdown() // Throw away any pending work that may deadlock during the shutdown procedure // when the main thread waits for any queued jobs to finish. m_executor->clearQueueAndProceed(); + m_executor->setScene(nullptr); } void QLogicAspectPrivate::registerBackendTypes() -- cgit v1.2.3 From 0a48c9fb631cb1c0616cb61e43898f19ac4b2278 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Mon, 27 Jan 2020 12:51:25 +0100 Subject: QRenderCapabilities: Fix include directives Add the missing module, which broke the Qt for Python build. Amends 4ae7cc93b503cc31272f0b55c84410af30aea8b9. Change-Id: I7b50432c4c2f0fb8eadcd3445f2de66d21caafde Reviewed-by: Mike Krus --- src/render/frontend/qrendercapabilities.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/render/frontend/qrendercapabilities.h b/src/render/frontend/qrendercapabilities.h index cbbb5a23d..14e233f59 100644 --- a/src/render/frontend/qrendercapabilities.h +++ b/src/render/frontend/qrendercapabilities.h @@ -40,8 +40,8 @@ #ifndef QT3DRENDER_QRENDERCAPABILITIES_H #define QT3DRENDER_QRENDERCAPABILITIES_H -#include -#include +#include +#include #include QT_BEGIN_NAMESPACE -- cgit v1.2.3 From 97c534b60f21d232dd814534fd9b53f77bc73fa3 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 27 Jan 2020 13:37:11 +0100 Subject: QScheduler: restore jobsDone() call at the end Mistakenly removed in a cleanup commit Change-Id: Icfb7c370017facf6ce990430c3df1535a0a72973 Reviewed-by: Mike Krus --- src/core/qscheduler.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/qscheduler.cpp b/src/core/qscheduler.cpp index b371a5fb1..17ca1fbfd 100644 --- a/src/core/qscheduler.cpp +++ b/src/core/qscheduler.cpp @@ -98,6 +98,9 @@ int QScheduler::scheduleAndWaitForFrameAspectJobs(qint64 time) for (auto &job : qAsConst(jobQueue)) QAspectJobPrivate::get(job.data())->postFrame(m_aspectManager); + + for (QAbstractAspect *aspect : aspects) + QAbstractAspectPrivate::get(aspect)->jobsDone(); } return jobQueue.size(); -- cgit v1.2.3 From 64f983af68440ff73b985b133a73bd66178557da Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 13 Jan 2020 07:53:41 +0100 Subject: QMouseDevice: add updateAxesContinuously property The default behavior is to only update axes when one of the mouse buttons is pressed. This property, when enabled, allows to record X/Y axes value changes regardless of the state of the mouse buttons. [ChangeLog] QMouseDevice add updateAxesContinuously property Change-Id: Ib54a1e54c6c278ea08722760c2d317ec46437b2f Reviewed-by: Mike Krus --- src/input/backend/mousedevice.cpp | 11 +++- src/input/backend/mousedevice_p.h | 2 + src/input/frontend/qmousedevice.cpp | 38 +++++++++++ src/input/frontend/qmousedevice.h | 4 ++ src/input/frontend/qmousedevice_p.h | 1 + .../imports/input/qt3dquick3dinputplugin.cpp | 1 + tests/auto/input/mousedevice/tst_mousedevice.cpp | 73 ++++++++++++++++++++-- tests/auto/input/qmousedevice/tst_qmousedevice.cpp | 45 +++++++++++++ 8 files changed, 169 insertions(+), 6 deletions(-) diff --git a/src/input/backend/mousedevice.cpp b/src/input/backend/mousedevice.cpp index 47045a1a1..c5b2a22ce 100644 --- a/src/input/backend/mousedevice.cpp +++ b/src/input/backend/mousedevice.cpp @@ -57,6 +57,7 @@ MouseDevice::MouseDevice() , m_inputHandler(nullptr) , m_wasPressed(false) , m_sensitivity(0.1f) + , m_updateAxesContinuously(false) { } @@ -126,6 +127,11 @@ float MouseDevice::sensitivity() const return m_sensitivity; } +bool MouseDevice::updateAxesContinuously() const +{ + return m_updateAxesContinuously; +} + #if QT_CONFIG(wheelevent) void MouseDevice::updateWheelEvents(const QList &events) { @@ -153,8 +159,8 @@ void MouseDevice::updateMouseEvents(const QListsensitivity(); + m_updateAxesContinuously = node->updateAxesContinuously(); } MouseDeviceFunctor::MouseDeviceFunctor(QInputAspect *inputAspect, InputHandler *handler) diff --git a/src/input/backend/mousedevice_p.h b/src/input/backend/mousedevice_p.h index 283eeaeaf..d41bb527b 100644 --- a/src/input/backend/mousedevice_p.h +++ b/src/input/backend/mousedevice_p.h @@ -107,6 +107,7 @@ public: QPointF previousPos() const; bool wasPressed() const; float sensitivity() const; + bool updateAxesContinuously() const; void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) override; @@ -117,6 +118,7 @@ private: QPointF m_previousPos; bool m_wasPressed; float m_sensitivity; + bool m_updateAxesContinuously; }; class MouseDeviceFunctor : public Qt3DCore::QBackendNodeMapper diff --git a/src/input/frontend/qmousedevice.cpp b/src/input/frontend/qmousedevice.cpp index 4a78b3b21..5872fbcd2 100644 --- a/src/input/frontend/qmousedevice.cpp +++ b/src/input/frontend/qmousedevice.cpp @@ -52,6 +52,7 @@ namespace Qt3DInput { QMouseDevicePrivate::QMouseDevicePrivate() : QAbstractPhysicalDevicePrivate() , m_sensitivity(0.1f) + , m_updateContinuously(false) { } @@ -106,6 +107,27 @@ QMouseDevicePrivate::QMouseDevicePrivate() Default is 0.1. */ +/*! + \property Qt3DInput::QMouseDevice::updateAxesContinously + + If true, axes will be updated anytime they change regardless of whether + any mouse button is being pressed. Otherwise, axes are updated only when + one of the mouse buttons is being pressed. + + \since 5.15 + \default false +*/ + +/*! + \qmlproperty bool MouseDevice::updateAxesContinously + + If true, axes will be updated anytime they change regardless of whether + any mouse button is being pressed. Otherwise, axes are updated only when + one of the mouse buttons is being pressed. + + \since 5.15 + \default false +*/ /*! Constructs a new QMouseDevice instance with parent \a parent. @@ -211,6 +233,12 @@ float QMouseDevice::sensitivity() const return d->m_sensitivity; } +bool QMouseDevice::updateAxesContinuously() const +{ + Q_D(const QMouseDevice); + return d->m_updateContinuously; +} + void QMouseDevice::setSensitivity(float value) { Q_D(QMouseDevice); @@ -221,6 +249,16 @@ void QMouseDevice::setSensitivity(float value) emit sensitivityChanged(value); } +void QMouseDevice::setUpdateAxesContinuously(bool updateAxesContinuously) +{ + Q_D(QMouseDevice); + if (d->m_updateContinuously == updateAxesContinuously) + return; + + d->m_updateContinuously = updateAxesContinuously; + emit updateAxesContinuouslyChanged(updateAxesContinuously); +} + /*! \internal */ void QMouseDevice::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) { diff --git a/src/input/frontend/qmousedevice.h b/src/input/frontend/qmousedevice.h index 01e243790..7754c2e29 100644 --- a/src/input/frontend/qmousedevice.h +++ b/src/input/frontend/qmousedevice.h @@ -57,6 +57,7 @@ class Q_3DINPUTSHARED_EXPORT QMouseDevice : public Qt3DInput::QAbstractPhysicalD { Q_OBJECT Q_PROPERTY(float sensitivity READ sensitivity WRITE setSensitivity NOTIFY sensitivityChanged) + Q_PROPERTY(bool updateAxesContinuously READ updateAxesContinuously WRITE setUpdateAxesContinuously NOTIFY updateAxesContinuouslyChanged REVISION 15) public: explicit QMouseDevice(Qt3DCore::QNode *parent = nullptr); ~QMouseDevice(); @@ -77,12 +78,15 @@ public: int buttonIdentifier(const QString &name) const final; float sensitivity() const; + bool updateAxesContinuously() const; public Q_SLOTS: void setSensitivity(float value); + void setUpdateAxesContinuously(bool updateAxesContinuously); Q_SIGNALS: void sensitivityChanged(float value); + void updateAxesContinuouslyChanged(bool updateAxesContinuously); protected: void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override; diff --git a/src/input/frontend/qmousedevice_p.h b/src/input/frontend/qmousedevice_p.h index 49c1c6191..91daccb6f 100644 --- a/src/input/frontend/qmousedevice_p.h +++ b/src/input/frontend/qmousedevice_p.h @@ -67,6 +67,7 @@ public: Q_DECLARE_PUBLIC(QMouseDevice) float m_sensitivity; + bool m_updateContinuously; }; struct QMouseDeviceData diff --git a/src/quick3d/imports/input/qt3dquick3dinputplugin.cpp b/src/quick3d/imports/input/qt3dquick3dinputplugin.cpp index ba2e0661c..2a9596a00 100644 --- a/src/quick3d/imports/input/qt3dquick3dinputplugin.cpp +++ b/src/quick3d/imports/input/qt3dquick3dinputplugin.cpp @@ -86,6 +86,7 @@ void Qt3DQuick3DInputPlugin::registerTypes(const char *uri) #endif qmlRegisterType(uri, 2, 0, "MouseHandler"); qmlRegisterType(uri, 2, 0, "MouseDevice"); + qmlRegisterType(uri, 2, 15, "MouseDevice"); qmlRegisterExtendedType(uri, 2, 0, "LogicalDevice"); qmlRegisterUncreatableType(uri, 2, 0, "AbstractActionInput", QStringLiteral("AbstractActionInput is abstract")); diff --git a/tests/auto/input/mousedevice/tst_mousedevice.cpp b/tests/auto/input/mousedevice/tst_mousedevice.cpp index f245e399d..95ae8de56 100644 --- a/tests/auto/input/mousedevice/tst_mousedevice.cpp +++ b/tests/auto/input/mousedevice/tst_mousedevice.cpp @@ -58,6 +58,7 @@ private Q_SLOTS: QCOMPARE(backendMouseDevice.previousPos(), QPointF()); QCOMPARE(backendMouseDevice.wasPressed(), false); QCOMPARE(backendMouseDevice.sensitivity(), 0.1f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), false); } void checkInitializeFromPeer() @@ -85,6 +86,7 @@ private Q_SLOTS: QCOMPARE(backendMouseDevice.previousPos(), QPointF()); QCOMPARE(backendMouseDevice.wasPressed(), false); QCOMPARE(backendMouseDevice.sensitivity(), 0.8f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), false); } { // WHEN @@ -125,6 +127,7 @@ private Q_SLOTS: QCOMPARE(backendMouseDevice.previousPos(), QPointF(400.0f, 400.0f)); QCOMPARE(backendMouseDevice.wasPressed(), true); QCOMPARE(backendMouseDevice.sensitivity(), 0.1f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), false); // WHEN eventList = QList() << QT_PREPEND_NAMESPACE(QMouseEvent)(QMouseEvent::MouseMove, @@ -147,12 +150,13 @@ private Q_SLOTS: QCOMPARE(backendMouseDevice.previousPos(), QPointF(600.0f, 600.0f)); QCOMPARE(backendMouseDevice.wasPressed(), true); QCOMPARE(backendMouseDevice.sensitivity(), 0.1f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), false); // WHEN eventList = QList() << QT_PREPEND_NAMESPACE(QMouseEvent)(QMouseEvent::MouseButtonRelease, - QPointF(600.0f, 600.0f), - QPointF(600.0f, 600.0f), - QPointF(600.0f, 600.0f), + QPointF(800.0f, 800.0f), + QPointF(800.0f, 800.0f), + QPointF(800.0f, 800.0f), Qt::LeftButton, Qt::NoButton, Qt::NoModifier); @@ -166,9 +170,61 @@ private Q_SLOTS: QCOMPARE(backendMouseDevice.mouseState().leftPressed, false); QCOMPARE(backendMouseDevice.mouseState().rightPressed, false); QCOMPARE(backendMouseDevice.mouseState().centerPressed, false); - QCOMPARE(backendMouseDevice.previousPos(), QPointF(600.0f, 600.0f)); + QCOMPARE(backendMouseDevice.previousPos(), QPointF(800.0f, 800.0f)); QCOMPARE(backendMouseDevice.wasPressed(), false); QCOMPARE(backendMouseDevice.sensitivity(), 0.1f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), false); + + // WHEN + eventList = QList() << QT_PREPEND_NAMESPACE(QMouseEvent)(QMouseEvent::MouseMove, + QPointF(900.0f, 900.0f), + QPointF(900.0f, 900.0f), + QPointF(900.0f, 900.0f), + Qt::NoButton, + Qt::NoButton, + Qt::NoModifier); + + // THEN -> no axes update + backendMouseDevice.updateMouseEvents(eventList); + QCOMPARE(backendMouseDevice.mouseState().xAxis, 0.0f); + QCOMPARE(backendMouseDevice.mouseState().yAxis, 0.0f); + QCOMPARE(backendMouseDevice.mouseState().wXAxis, 0.0f); + QCOMPARE(backendMouseDevice.mouseState().wYAxis, 0.0f); + QCOMPARE(backendMouseDevice.mouseState().leftPressed, false); + QCOMPARE(backendMouseDevice.mouseState().rightPressed, false); + QCOMPARE(backendMouseDevice.mouseState().centerPressed, false); + QCOMPARE(backendMouseDevice.previousPos(), QPointF(900.0f, 900.0f)); + QCOMPARE(backendMouseDevice.wasPressed(), false); + QCOMPARE(backendMouseDevice.sensitivity(), 0.1f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), false); + + + // WHEN + eventList = QList() << QT_PREPEND_NAMESPACE(QMouseEvent)(QMouseEvent::MouseMove, + QPointF(1000.0f, 1000.0f), + QPointF(1000.0f, 1000.0f), + QPointF(1000.0f, 1000.0f), + Qt::NoButton, + Qt::NoButton, + Qt::NoModifier); + + Qt3DInput::QMouseDevice mouseDevice; + mouseDevice.setUpdateAxesContinuously(true); + backendMouseDevice.syncFromFrontEnd(&mouseDevice, false); + backendMouseDevice.updateMouseEvents(eventList); + + // THEN + QCOMPARE(backendMouseDevice.mouseState().xAxis, (1000.0f - 900.0f) * 0.1f); + QCOMPARE(backendMouseDevice.mouseState().yAxis, (900.0f - 1000.0f) * 0.1f); + QCOMPARE(backendMouseDevice.mouseState().wXAxis, 0.0f); + QCOMPARE(backendMouseDevice.mouseState().wYAxis, 0.0f); + QCOMPARE(backendMouseDevice.mouseState().leftPressed,false); + QCOMPARE(backendMouseDevice.mouseState().rightPressed, false); + QCOMPARE(backendMouseDevice.mouseState().centerPressed, false); + QCOMPARE(backendMouseDevice.previousPos(), QPointF(1000.0f, 1000.0f)); + QCOMPARE(backendMouseDevice.wasPressed(), false); + QCOMPARE(backendMouseDevice.sensitivity(), 0.1f); + QCOMPARE(backendMouseDevice.updateAxesContinuously(), true); } void checkMouseWheelState() @@ -241,6 +297,15 @@ private Q_SLOTS: // THEN QCOMPARE(backendMouseDevice.sensitivity(), newValue); } + { + // WHEN + const bool newValue = true; + mouseDevice.setUpdateAxesContinuously(newValue); + backendMouseDevice.syncFromFrontEnd(&mouseDevice, false); + + // THEN + QCOMPARE(backendMouseDevice.updateAxesContinuously(), newValue); + } } }; diff --git a/tests/auto/input/qmousedevice/tst_qmousedevice.cpp b/tests/auto/input/qmousedevice/tst_qmousedevice.cpp index fd2c8e603..6a8f39c71 100644 --- a/tests/auto/input/qmousedevice/tst_qmousedevice.cpp +++ b/tests/auto/input/qmousedevice/tst_qmousedevice.cpp @@ -50,6 +50,7 @@ private Q_SLOTS: // THEN QCOMPARE(mouseDevice.sensitivity(), 0.1f); + QCOMPARE(mouseDevice.updateAxesContinuously(), false); QCOMPARE(mouseDevice.axisCount(), 4); QCOMPARE(mouseDevice.buttonCount(), 3); QCOMPARE(mouseDevice.axisNames(), QStringList() @@ -96,6 +97,25 @@ private Q_SLOTS: QCOMPARE(mouseDevice.sensitivity(), newValue); QCOMPARE(spy.count(), 0); } + { + // WHEN + QSignalSpy spy(&mouseDevice, SIGNAL(updateAxesContinuouslyChanged(bool))); + const bool newValue = true; + mouseDevice.setUpdateAxesContinuously(newValue); + + // THEN + QVERIFY(spy.isValid()); + QCOMPARE(mouseDevice.updateAxesContinuously(), newValue); + QCOMPARE(spy.count(), 1); + + // WHEN + spy.clear(); + mouseDevice.setUpdateAxesContinuously(newValue); + + // THEN + QCOMPARE(mouseDevice.updateAxesContinuously(), newValue); + QCOMPARE(spy.count(), 0); + } } void checkCreationData() @@ -175,6 +195,31 @@ private Q_SLOTS: } + void checkUpdateAxesContinuouslyUpdate() + { + // GIVEN + TestArbiter arbiter; + Qt3DInput::QMouseDevice mouseDevice; + arbiter.setArbiterOnNode(&mouseDevice); + + { + // WHEN + mouseDevice.setUpdateAxesContinuously(true); + // THEN + QCOMPARE(arbiter.dirtyNodes.size(), 1); + QCOMPARE(arbiter.dirtyNodes.front(), &mouseDevice); + } + + { + // WHEN + mouseDevice.setSensitivity(true); + + QCOMPARE(arbiter.dirtyNodes.size(), 1); + QCOMPARE(arbiter.dirtyNodes.front(), &mouseDevice); + } + + } + }; QTEST_MAIN(tst_QMouseDevice) -- cgit v1.2.3 From c5211b7026ebf26bc82889437329ae2cc11e9725 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 27 Jan 2020 14:13:11 +0100 Subject: Unit tests for qscheduler Change-Id: Iaa26160736bc6b92ecf0be767cb289d776cf46ad Reviewed-by: Mike Krus --- src/core/qscheduler_p.h | 2 +- tests/auto/core/core.pro | 3 +- tests/auto/core/qscheduler/qscheduler.pro | 7 + tests/auto/core/qscheduler/tst_qscheduler.cpp | 201 ++++++++++++++++++++++++++ 4 files changed, 211 insertions(+), 2 deletions(-) create mode 100644 tests/auto/core/qscheduler/qscheduler.pro create mode 100644 tests/auto/core/qscheduler/tst_qscheduler.cpp diff --git a/src/core/qscheduler_p.h b/src/core/qscheduler_p.h index dd4101ef2..92e8e04fb 100644 --- a/src/core/qscheduler_p.h +++ b/src/core/qscheduler_p.h @@ -60,7 +60,7 @@ namespace Qt3DCore { class QAspectManager; -class QScheduler : public QObject +class Q_AUTOTEST_EXPORT QScheduler : public QObject { Q_OBJECT public: diff --git a/tests/auto/core/core.pro b/tests/auto/core/core.pro index 13f4a0dc7..994c6206c 100644 --- a/tests/auto/core/core.pro +++ b/tests/auto/core/core.pro @@ -26,7 +26,8 @@ qtConfig(private_tests) { qpostman \ vector4d_base \ vector3d_base \ - aspectcommanddebugger + aspectcommanddebugger \ + qscheduler QT_FOR_CONFIG += 3dcore-private qtConfig(qt3d-simd-sse2) { diff --git a/tests/auto/core/qscheduler/qscheduler.pro b/tests/auto/core/qscheduler/qscheduler.pro new file mode 100644 index 000000000..078716116 --- /dev/null +++ b/tests/auto/core/qscheduler/qscheduler.pro @@ -0,0 +1,7 @@ +TARGET = tst_qscheduler +CONFIG += testcase +TEMPLATE = app + +SOURCES += tst_qscheduler.cpp + +QT += testlib 3dcore 3dcore-private diff --git a/tests/auto/core/qscheduler/tst_qscheduler.cpp b/tests/auto/core/qscheduler/tst_qscheduler.cpp new file mode 100644 index 000000000..d1afb5aac --- /dev/null +++ b/tests/auto/core/qscheduler/tst_qscheduler.cpp @@ -0,0 +1,201 @@ +/**************************************************************************** +** +** Copyright (C) 2020 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +using namespace Qt3DCore; + +class JobPrivate : public QAspectJobPrivate +{ + bool m_postFrameCalled = false; + + +public: + // QAspectJobPrivate interface + void postFrame(QAspectManager *aspectManager) + { + Q_ASSERT(aspectManager); + m_postFrameCalled = true; + } + + bool postFrameCalled() const + { + return m_postFrameCalled; + } +}; + +class Job : public QAspectJob +{ + bool m_wasExecuted = false; + +public: + Job() + : QAspectJob(*new JobPrivate) + {} + + bool wasExecuted() const + { + return m_wasExecuted; + } + + bool postFrameCalled() const + { + Q_D(const Job); + return d->postFrameCalled(); + } + + void run() override + { + m_wasExecuted = true; + } + +private: + Q_DECLARE_PRIVATE(Job) +}; +using JobPtr = QSharedPointer; + +class AspectPrivate : public QAbstractAspectPrivate +{ + bool m_jobsDoneCalled = false; + bool m_frameDoneCalled = false; + +public: + + bool jobsDoneCalled() const + { + return m_jobsDoneCalled; + } + + bool frameDoneCalled() const + { + return m_frameDoneCalled; + } + + // QAspectJobProviderInterface interface + void jobsDone() override + { + m_jobsDoneCalled = true; + } + + void frameDone() override + { + m_frameDoneCalled = true; + } +}; + +class Aspect : public QAbstractAspect +{ + Q_OBJECT + +public: + Aspect() + : QAbstractAspect(*new AspectPrivate) + {} + + JobPtr firstJob() const { return m_first; } + JobPtr secondJob() const { return m_second; } + +private: + // QAbstractAspect interface + QVector jobsToExecute(qint64) + { + return { m_first, m_second }; + } + + JobPtr m_first = JobPtr::create(); + JobPtr m_second = JobPtr::create(); + Q_DECLARE_PRIVATE(Aspect) +}; + +class tst_QScheduler : public QObject +{ + Q_OBJECT +private Q_SLOTS: + + void checkInitialState() + { + // GIVEN + QScheduler scheduler; + + // THEN + QVERIFY(scheduler.aspectManager() == nullptr); + + // WHEN + QAspectManager m; + scheduler.setAspectManager(&m); + + // THEN + QCOMPARE(scheduler.aspectManager(), &m); + } + + void checkScheduleAndWaitForFrameAspectJobs() + { + // GIVEN + QScheduler scheduler; + QAspectManager manager; + Aspect aspect; + AspectPrivate *aspectPriv = static_cast(QObjectPrivate::get(&aspect)); + + manager.registerAspect(&aspect); + scheduler.setAspectManager(&manager); + + // THEN + const JobPtr first = aspect.firstJob(); + const JobPtr second = aspect.secondJob(); + QVERIFY(!aspectPriv->jobsDoneCalled()); + QVERIFY(!aspectPriv->frameDoneCalled()); + QVERIFY(!first->wasExecuted()); + QVERIFY(!second->wasExecuted()); + QVERIFY(!first->postFrameCalled()); + QVERIFY(!second->postFrameCalled()); + + // WHEN + const int count = scheduler.scheduleAndWaitForFrameAspectJobs(0); + + // THEN + QCOMPARE(count, 2); + QVERIFY(first->wasExecuted()); + QVERIFY(second->wasExecuted()); + QVERIFY(first->postFrameCalled()); + QVERIFY(second->postFrameCalled()); + QVERIFY(aspectPriv->jobsDoneCalled()); + QVERIFY(!aspectPriv->frameDoneCalled()); + + manager.unregisterAspect(&aspect); + } +}; + +QTEST_MAIN(tst_QScheduler) + +#include "tst_qscheduler.moc" -- cgit v1.2.3 From 3e2b688817d615c1458e1144ad0f0f35555475e8 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Thu, 30 Jan 2020 08:31:42 +0000 Subject: Deprecate functor APIs Deprecate functor based APIs for buffer generators, geometry factories, texture data generators and mesh loaders While these are useful for some of Qt3D's internal mechanisms, they complicate some of the backend operations. Will delete some or make them private in Qt6. Change-Id: I64eaa338e0306647867d2084819ef8591e2c91c0 Reviewed-by: Paul Lemire --- src/render/frontend/qabstractfunctor.h | 4 ++-- src/render/geometry/qbuffer.h | 4 ++-- src/render/geometry/qgeometryrenderer.h | 4 ++-- src/render/geometry/qmesh_p.h | 3 +++ src/render/texture/qabstracttexture.cpp | 2 +- src/render/texture/qabstracttexture.h | 2 +- tests/auto/extras/common/geometrytesthelper.h | 3 +++ tests/auto/render/buffer/tst_buffer.cpp | 4 ++++ tests/auto/render/ddstextures/tst_ddstextures.cpp | 4 ++++ tests/auto/render/geometry/tst_geometry.cpp | 4 ++++ tests/auto/render/geometryrenderer/tst_geometryrenderer.cpp | 4 ++++ tests/auto/render/gltexture/tst_gltexture.cpp | 4 ++++ tests/auto/render/ktxtextures/tst_ktxtextures.cpp | 4 ++++ tests/auto/render/meshfunctors/tst_meshfunctors.cpp | 4 ++++ tests/auto/render/picking/tst_picking.cpp | 3 +++ tests/auto/render/qbuffer/tst_qbuffer.cpp | 4 ++++ tests/auto/render/qdefaultmeshes/tst_qdefaultmeshes.cpp | 4 ++++ tests/auto/render/qgeometryrenderer/tst_qgeometryrenderer.cpp | 4 ++++ tests/auto/render/qmesh/tst_qmesh.cpp | 3 +++ tests/auto/render/qsharedgltexture/tst_qsharedgltexture.cpp | 3 +++ tests/auto/render/qtextureimage/tst_qtextureimage.cpp | 3 +++ tests/auto/render/qtextureloader/tst_qtextureloader.cpp | 3 +++ tests/auto/render/textures/tst_textures.cpp | 4 ++++ 23 files changed, 73 insertions(+), 8 deletions(-) diff --git a/src/render/frontend/qabstractfunctor.h b/src/render/frontend/qabstractfunctor.h index 45492e141..697b22613 100644 --- a/src/render/frontend/qabstractfunctor.h +++ b/src/render/frontend/qabstractfunctor.h @@ -62,7 +62,7 @@ struct FunctorType }; template -qintptr functorTypeId() +Q3D_DECL_DEPRECATED qintptr functorTypeId() { return reinterpret_cast(&FunctorType::id); } @@ -76,7 +76,7 @@ qintptr functorTypeId() class Q_3DRENDERSHARED_EXPORT QAbstractFunctor { public: - QAbstractFunctor() = default; + Q3D_DECL_DEPRECATED QAbstractFunctor() = default; virtual ~QAbstractFunctor(); virtual qintptr id() const = 0; diff --git a/src/render/geometry/qbuffer.h b/src/render/geometry/qbuffer.h index aa6ebca66..f1ce110f0 100644 --- a/src/render/geometry/qbuffer.h +++ b/src/render/geometry/qbuffer.h @@ -107,8 +107,8 @@ public: void setData(const QByteArray &bytes); QByteArray data() const; - void setDataGenerator(const QBufferDataGeneratorPtr &functor); - QBufferDataGeneratorPtr dataGenerator() const; + Q3D_DECL_DEPRECATED void setDataGenerator(const QBufferDataGeneratorPtr &functor); + Q3D_DECL_DEPRECATED QBufferDataGeneratorPtr dataGenerator() const; Q_INVOKABLE void updateData(int offset, const QByteArray &bytes); diff --git a/src/render/geometry/qgeometryrenderer.h b/src/render/geometry/qgeometryrenderer.h index 14de40d0b..3f0f9fab2 100644 --- a/src/render/geometry/qgeometryrenderer.h +++ b/src/render/geometry/qgeometryrenderer.h @@ -103,8 +103,8 @@ public: QGeometry *geometry() const; PrimitiveType primitiveType() const; - QGeometryFactoryPtr geometryFactory() const; - void setGeometryFactory(const QGeometryFactoryPtr &factory); + Q3D_DECL_DEPRECATED QGeometryFactoryPtr geometryFactory() const; + Q3D_DECL_DEPRECATED void setGeometryFactory(const QGeometryFactoryPtr &factory); public Q_SLOTS: void setInstanceCount(int instanceCount); diff --git a/src/render/geometry/qmesh_p.h b/src/render/geometry/qmesh_p.h index 4a4ff4979..c80c930c5 100644 --- a/src/render/geometry/qmesh_p.h +++ b/src/render/geometry/qmesh_p.h @@ -120,7 +120,10 @@ public : QGeometry *operator()() override; bool operator ==(const QGeometryFactory &other) const override; + QT_WARNING_PUSH + QT_WARNING_DISABLE_DEPRECATED QT3D_FUNCTOR(MeshLoaderFunctor) + QT_WARNING_POP private: Qt3DCore::QNodeId m_mesh; diff --git a/src/render/texture/qabstracttexture.cpp b/src/render/texture/qabstracttexture.cpp index 258ab44dc..2e7fd0f63 100644 --- a/src/render/texture/qabstracttexture.cpp +++ b/src/render/texture/qabstracttexture.cpp @@ -1182,7 +1182,7 @@ void QAbstractTexture::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) } default: break; - }; + } } diff --git a/src/render/texture/qabstracttexture.h b/src/render/texture/qabstracttexture.h index b3d5efb34..2512d0786 100644 --- a/src/render/texture/qabstracttexture.h +++ b/src/render/texture/qabstracttexture.h @@ -306,7 +306,7 @@ public: int depth() const; int layers() const; int samples() const; - QTextureGeneratorPtr dataGenerator() const; + Q3D_DECL_DEPRECATED QTextureGeneratorPtr dataGenerator() const; HandleType handleType() const; QVariant handle() const; diff --git a/tests/auto/extras/common/geometrytesthelper.h b/tests/auto/extras/common/geometrytesthelper.h index 48e674cd9..5b04a078b 100644 --- a/tests/auto/extras/common/geometrytesthelper.h +++ b/tests/auto/extras/common/geometrytesthelper.h @@ -42,9 +42,12 @@ inline void generateGeometry(Qt3DRender::QGeometry &geometry) // Get all unique data generators from the buffers referenced by the attributes QHash dataGenerators; for (const auto attribute : attributes) { + QT_WARNING_PUSH + QT_WARNING_DISABLE_DEPRECATED const auto dataGenerator = attribute->buffer()->dataGenerator(); if (!dataGenerators.contains(dataGenerator)) dataGenerators.insert(dataGenerator, attribute->buffer()); + QT_WARNING_POP } // Generate data for each buffer diff --git a/tests/auto/render/buffer/tst_buffer.cpp b/tests/auto/render/buffer/tst_buffer.cpp index fa1491914..5c2ae296d 100644 --- a/tests/auto/render/buffer/tst_buffer.cpp +++ b/tests/auto/render/buffer/tst_buffer.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/ddstextures/tst_ddstextures.cpp b/tests/auto/render/ddstextures/tst_ddstextures.cpp index 1f33f20e2..ecdb5d234 100644 --- a/tests/auto/render/ddstextures/tst_ddstextures.cpp +++ b/tests/auto/render/ddstextures/tst_ddstextures.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/geometry/tst_geometry.cpp b/tests/auto/render/geometry/tst_geometry.cpp index 09dbb8eb3..a13f6fa40 100644 --- a/tests/auto/render/geometry/tst_geometry.cpp +++ b/tests/auto/render/geometry/tst_geometry.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/geometryrenderer/tst_geometryrenderer.cpp b/tests/auto/render/geometryrenderer/tst_geometryrenderer.cpp index 0f6af16db..19df24680 100644 --- a/tests/auto/render/geometryrenderer/tst_geometryrenderer.cpp +++ b/tests/auto/render/geometryrenderer/tst_geometryrenderer.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/gltexture/tst_gltexture.cpp b/tests/auto/render/gltexture/tst_gltexture.cpp index e971078d0..7d8c679f3 100644 --- a/tests/auto/render/gltexture/tst_gltexture.cpp +++ b/tests/auto/render/gltexture/tst_gltexture.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/ktxtextures/tst_ktxtextures.cpp b/tests/auto/render/ktxtextures/tst_ktxtextures.cpp index 57ccd3652..f57bc86b6 100644 --- a/tests/auto/render/ktxtextures/tst_ktxtextures.cpp +++ b/tests/auto/render/ktxtextures/tst_ktxtextures.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/meshfunctors/tst_meshfunctors.cpp b/tests/auto/render/meshfunctors/tst_meshfunctors.cpp index 1142d1447..f8110085b 100644 --- a/tests/auto/render/meshfunctors/tst_meshfunctors.cpp +++ b/tests/auto/render/meshfunctors/tst_meshfunctors.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/picking/tst_picking.cpp b/tests/auto/render/picking/tst_picking.cpp index d0e6512d5..b281eb6cb 100644 --- a/tests/auto/render/picking/tst_picking.cpp +++ b/tests/auto/render/picking/tst_picking.cpp @@ -82,8 +82,11 @@ public: Qt3DRender::QBuffer *vertexBuffer = static_cast(positionAttr->buffer()); // Load the geometry + QT_WARNING_PUSH + QT_WARNING_DISABLE_DEPRECATED const QByteArray data = (*vertexBuffer->dataGenerator())(); vertexBuffer->setData(data); + QT_WARNING_POP transform->setTranslation(position); diff --git a/tests/auto/render/qbuffer/tst_qbuffer.cpp b/tests/auto/render/qbuffer/tst_qbuffer.cpp index 94c0a49cb..fd96bf1c2 100644 --- a/tests/auto/render/qbuffer/tst_qbuffer.cpp +++ b/tests/auto/render/qbuffer/tst_qbuffer.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/qdefaultmeshes/tst_qdefaultmeshes.cpp b/tests/auto/render/qdefaultmeshes/tst_qdefaultmeshes.cpp index bbecdd187..8c64a005a 100644 --- a/tests/auto/render/qdefaultmeshes/tst_qdefaultmeshes.cpp +++ b/tests/auto/render/qdefaultmeshes/tst_qdefaultmeshes.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include diff --git a/tests/auto/render/qgeometryrenderer/tst_qgeometryrenderer.cpp b/tests/auto/render/qgeometryrenderer/tst_qgeometryrenderer.cpp index 28574d3c5..8cfbc0d23 100644 --- a/tests/auto/render/qgeometryrenderer/tst_qgeometryrenderer.cpp +++ b/tests/auto/render/qgeometryrenderer/tst_qgeometryrenderer.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include diff --git a/tests/auto/render/qmesh/tst_qmesh.cpp b/tests/auto/render/qmesh/tst_qmesh.cpp index 0df96dd24..d77005dfa 100644 --- a/tests/auto/render/qmesh/tst_qmesh.cpp +++ b/tests/auto/render/qmesh/tst_qmesh.cpp @@ -26,6 +26,9 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED #include #include diff --git a/tests/auto/render/qsharedgltexture/tst_qsharedgltexture.cpp b/tests/auto/render/qsharedgltexture/tst_qsharedgltexture.cpp index 4011eeea6..3187dbd52 100644 --- a/tests/auto/render/qsharedgltexture/tst_qsharedgltexture.cpp +++ b/tests/auto/render/qsharedgltexture/tst_qsharedgltexture.cpp @@ -26,6 +26,9 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED #include #include diff --git a/tests/auto/render/qtextureimage/tst_qtextureimage.cpp b/tests/auto/render/qtextureimage/tst_qtextureimage.cpp index 4996c877d..ba5c2c3d8 100644 --- a/tests/auto/render/qtextureimage/tst_qtextureimage.cpp +++ b/tests/auto/render/qtextureimage/tst_qtextureimage.cpp @@ -26,6 +26,9 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED #include #include diff --git a/tests/auto/render/qtextureloader/tst_qtextureloader.cpp b/tests/auto/render/qtextureloader/tst_qtextureloader.cpp index dd92894da..b6d949c83 100644 --- a/tests/auto/render/qtextureloader/tst_qtextureloader.cpp +++ b/tests/auto/render/qtextureloader/tst_qtextureloader.cpp @@ -26,6 +26,9 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED #include #include diff --git a/tests/auto/render/textures/tst_textures.cpp b/tests/auto/render/textures/tst_textures.cpp index 555bd09a3..934cc8151 100644 --- a/tests/auto/render/textures/tst_textures.cpp +++ b/tests/auto/render/textures/tst_textures.cpp @@ -26,6 +26,10 @@ ** ****************************************************************************/ +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + #include #include #include -- cgit v1.2.3 From 32755ab5cca668c82b43bbe8b2e907e4f7dd7720 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Fri, 31 Jan 2020 09:33:36 +0100 Subject: Fix stale Entity caches Make sure we mark the internal state as dirty when Entities get cleaned up. We could otherwise end up with stale caches referencing Entity's that have been cleaned up (referencing null bounding volumes ...) Change-Id: Ia2d2c67f8635e28690f33c0a7d4c9ff1de0eb471 Reviewed-by: Mike Krus --- src/render/backend/entity.cpp | 4 +++ tests/auto/render/entity/tst_entity.cpp | 47 +++++++++++++++++++++++-------- tests/auto/render/scene2d/tst_scene2d.cpp | 2 +- 3 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/render/backend/entity.cpp b/src/render/backend/entity.cpp index 682dc000e..d766baaaf 100644 --- a/src/render/backend/entity.cpp +++ b/src/render/backend/entity.cpp @@ -156,6 +156,10 @@ void Entity::cleanup() m_parentHandle = {}; m_boundingDirty = false; QBackendNode::setEnabled(false); + + // Ensure we rebuild caches when an Entity gets cleaned up + if (m_renderer) + markDirty(AbstractRenderer::AllDirty); } void Entity::setParentHandle(HEntity parentHandle) diff --git a/tests/auto/render/entity/tst_entity.cpp b/tests/auto/render/entity/tst_entity.cpp index e3b8e756e..2eeca2b39 100644 --- a/tests/auto/render/entity/tst_entity.cpp +++ b/tests/auto/render/entity/tst_entity.cpp @@ -123,10 +123,12 @@ private slots: TestRenderer renderer; NodeManagers nodeManagers; Qt3DRender::Render::Entity entity; - Qt3DCore::QEntity dummyFrontendEntity; entity.setRenderer(&renderer); entity.setNodeManagers(&nodeManagers); + // THEN + QCOMPARE(renderer.dirtyBits(), 0); + // THEN QVERIFY(entity.componentUuid().isNull()); QVERIFY(entity.componentUuid().isNull()); @@ -141,20 +143,16 @@ private slots: QVERIFY(!entity.isBoundingVolumeDirty()); QVERIFY(entity.childrenHandles().isEmpty()); QVERIFY(entity.layerIds().isEmpty()); + QCOMPARE(entity.renderer(), &renderer); + + QCOMPARE(renderer.dirtyBits(), 0); // WHEN for (QComponent *component : components) EntityPrivate::get(&entity)->componentAdded(component); - Qt3DCore::QEntity dummyFrontendEntityChild; - // Create nodes in the backend manager - nodeManagers.renderNodesManager()->getOrCreateResource(dummyFrontendEntity.id()); - nodeManagers.renderNodesManager()->getOrCreateResource(dummyFrontendEntityChild.id()); - -// TODOSYNC clean up -// // Send children added event to entity -// const auto addEntityChange = QPropertyNodeAddedChangePtr::create(dummyFrontendEntity.id(), &dummyFrontendEntityChild); -// entity.sceneChangeEvent(addEntityChange); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); // THEN QVERIFY(!entity.componentUuid().isNull()); @@ -170,7 +168,7 @@ private slots: QVERIFY(entity.isBoundingVolumeDirty()); QVERIFY(entity.childrenHandles().isEmpty()); QVERIFY(!entity.layerIds().isEmpty()); - QVERIFY(renderer.dirtyBits() != 0); + QCOMPARE(renderer.dirtyBits(), 0); bool containsAll = entity.containsComponentsOfType(); QVERIFY(containsAll); @@ -195,6 +193,9 @@ private slots: containsAll = entity.containsComponentsOfType(); QVERIFY(!containsAll); + + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); } void checkEntityReparenting() @@ -217,6 +218,9 @@ private slots: QVERIFY(backendB->childrenHandles().isEmpty()); QVERIFY(backendC->childrenHandles().isEmpty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); + // WHEN auto sendParentChange = [&nodeManagers](const Qt3DCore::QEntity &entity) { Entity *backendEntity = nodeManagers.renderNodesManager()->getOrCreateResource(entity.id()); @@ -238,6 +242,9 @@ private slots: QCOMPARE(backendB->childrenHandles().count(), 1); QVERIFY(backendC->childrenHandles().isEmpty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); + // WHEN - reparent C to A frontendEntityC.setParent(&frontendEntityA); sendParentChange(frontendEntityC); @@ -251,6 +258,9 @@ private slots: QVERIFY(backendB->childrenHandles().isEmpty()); QVERIFY(backendC->childrenHandles().isEmpty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); + // WHEN - reparent B to null. frontendEntityB.setParent(static_cast(nullptr)); sendParentChange(frontendEntityB); @@ -264,6 +274,9 @@ private slots: QVERIFY(!backendA->childrenHandles().contains(backendB->handle())); QVERIFY(backendB->childrenHandles().isEmpty()); QVERIFY(backendC->childrenHandles().isEmpty()); + + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); } void checkEntityCleanup() @@ -298,6 +311,9 @@ private slots: QVERIFY(backendB->childrenHandles().isEmpty()); QVERIFY(backendC->childrenHandles().isEmpty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); + // WHEN - cleaning up a child backendC->cleanup(); @@ -312,6 +328,9 @@ private slots: QVERIFY(backendB->childrenHandles().isEmpty()); QVERIFY(backendC->childrenHandles().isEmpty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); + // WHEN (cleaning up parent) backendA->cleanup(); @@ -324,6 +343,9 @@ private slots: QVERIFY(backendB->childrenHandles().isEmpty()); QVERIFY(backendC->childrenHandles().isEmpty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); + // WHEN backendB->cleanup(); @@ -335,6 +357,9 @@ private slots: QVERIFY(backendA->parent() == nullptr); QVERIFY(backendB->parent() == nullptr); QVERIFY(backendC->parent() == nullptr); + + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.resetDirty(); } void shouldHandleSingleComponentEvents_data() diff --git a/tests/auto/render/scene2d/tst_scene2d.cpp b/tests/auto/render/scene2d/tst_scene2d.cpp index fcb4c0908..ecade18fc 100644 --- a/tests/auto/render/scene2d/tst_scene2d.cpp +++ b/tests/auto/render/scene2d/tst_scene2d.cpp @@ -209,6 +209,7 @@ private Q_SLOTS: QScopedPointer testWindow(new TestWindow()); Scene2DSharedObjectPtr sharedObject(new Scene2DSharedObject(nullptr)); + TestRenderer renderer; QScopedPointer scene2d(new Scene2D()); QScopedPointer nodeManagers(new NodeManagers()); Qt3DRender::QGeometry *geometry = new Qt3DRender::QGeometry(); @@ -218,7 +219,6 @@ private Q_SLOTS: Qt3DRender::QBuffer *dataBuffer =new Qt3DRender::QBuffer(); QScopedPointer entity(new Qt3DCore::QEntity()); entity->addComponent(geometryRenderer); - TestRenderer renderer; renderer.setNodeManagers(nodeManagers.data()); scene2d->setRenderer(&renderer); scene2d->setEnabled(true); -- cgit v1.2.3 From d33c1630b09fcdad83f69bfd2530354584b2f42b Mon Sep 17 00:00:00 2001 From: Alexandru Croitor Date: Sun, 2 Feb 2020 13:42:10 +0100 Subject: Bump version Change-Id: Ib87ede7ae9e53334b07908eb33c13d171d3fd59c --- .qmake.conf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.qmake.conf b/.qmake.conf index ab88c5d54..a4879bb40 100644 --- a/.qmake.conf +++ b/.qmake.conf @@ -6,4 +6,4 @@ load(qt_build_config) DEFINES += QT_NO_FOREACH DEFINES += QT_NO_JAVA_STYLE_ITERATORS -MODULE_VERSION = 5.14.1 +MODULE_VERSION = 5.14.2 -- cgit v1.2.3 From fb2a38bb010bc30210e4a1ec211e24f263c889d1 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 3 Feb 2020 08:03:13 +0100 Subject: tst_filtercompatibletechniquejob: skip test if unable to create context Change-Id: I79bfa9f14518427bc1211cc48f6561906b1653ce Reviewed-by: Paul Lemire --- .../tst_filtercompatibletechniquejob.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp b/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp index 25262a772..1f88b49d1 100644 --- a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp +++ b/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp @@ -53,6 +53,7 @@ public: : Qt3DRender::QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) , m_jobManager(new Qt3DCore::QAspectJobManager()) , m_window(new QWindow()) + , m_contextCreationSuccessful(false) { m_window->setSurfaceType(QWindow::OpenGLSurface); m_window->setGeometry(0, 0, 10, 10); @@ -68,6 +69,8 @@ public: return; } + m_contextCreationSuccessful = true; + Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); QRenderAspect::onRegistered(); @@ -100,6 +103,11 @@ public: ? d_func()->m_renderer->nodeManagers() : nullptr; } + bool contextCreationSuccessful() const + { + return m_contextCreationSuccessful; + } + void initializeRenderer() { renderer()->setOpenGLContext(&m_glContext); @@ -119,6 +127,7 @@ private: QScopedPointer m_jobManager; QScopedPointer m_window; QOpenGLContext m_glContext; + bool m_contextCreationSuccessful; }; } // namespace Qt3DRender @@ -211,6 +220,11 @@ private Q_SLOTS: Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; Qt3DRender::TestAspect testAspect(buildTestScene()); + const bool unableToCreateContext = !testAspect.contextCreationSuccessful(); + + if (unableToCreateContext) + QSKIP("Initialization failed, unable to create GL context"); + // WHEN Qt3DRender::Render::NodeManagers *nodeManagers = testAspect.nodeManagers(); QVERIFY(nodeManagers); -- cgit v1.2.3 From 118124ac1340efb64e8821d466f9d9c2be001bc2 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 3 Feb 2020 10:04:39 +0100 Subject: tst_filtercompatibletechniquejob: fix unregister in case context creation failed Change-Id: I7988ab2c918ecca694df996cc95cd9730d69a6cd Reviewed-by: Paul Lemire --- .../filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp b/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp index 1f88b49d1..618709269 100644 --- a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp +++ b/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp @@ -94,7 +94,8 @@ public: ~TestAspect() { - QRenderAspect::onUnregistered(); + if (m_contextCreationSuccessful) + QRenderAspect::onUnregistered(); } Qt3DRender::Render::NodeManagers *nodeManagers() const -- cgit v1.2.3 From abf5d701ed90e3f1516821712a3018cbe7a2b7fe Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Fri, 2 Jun 2017 13:28:45 +0200 Subject: Add dedicated managers holder for GL Resources That way NodeManagers only refers to managers holding nodes (so can be used by aspect and all renderer) and GLResourceManagers refers to renderer specific resources. Note: the Scene2D resourceaccessor was making direct access to GL resource through the managers, this has been commented and will be restored later. Change-Id: Ic32784f60eac35aab8c066d1769f078639fa25b8 Reviewed-by: Mike Krus --- src/render/backend/handle_types_p.h | 6 - src/render/backend/managers_p.h | 24 ---- src/render/backend/nodemanagers.cpp | 22 ---- src/render/backend/nodemanagers_p.h | 22 +--- src/render/backend/resourceaccessor.cpp | 114 ++++++++++--------- src/render/backend/resourceaccessor_p.h | 8 +- src/render/frontend/qrenderaspect.cpp | 2 + .../renderers/opengl/debug/imguirenderer.cpp | 1 + .../opengl/graphicshelpers/graphicscontext.cpp | 2 +- .../opengl/graphicshelpers/graphicscontext_p.h | 1 + .../opengl/graphicshelpers/submissioncontext.cpp | 35 +++--- src/render/renderers/opengl/io/glbuffer_p.h | 5 + .../renderers/opengl/managers/gl_handle_types_p.h | 76 +++++++++++++ .../opengl/managers/glresourcemanagers.cpp | 70 ++++++++++++ .../opengl/managers/glresourcemanagers_p.h | 123 +++++++++++++++++++++ src/render/renderers/opengl/managers/managers.pri | 8 ++ src/render/renderers/opengl/opengl.pri | 1 + .../opengl/renderer/openglvertexarrayobject.cpp | 4 +- .../renderers/opengl/renderer/rendercommand_p.h | 1 + src/render/renderers/opengl/renderer/renderer.cpp | 48 ++++---- src/render/renderers/opengl/renderer/renderer_p.h | 4 + .../renderers/opengl/renderer/renderview.cpp | 1 + .../renderers/opengl/textures/gltexturemanager_p.h | 78 ------------- src/render/renderers/opengl/textures/textures.pri | 3 - src/render/texture/qtexture.cpp | 2 +- src/render/texture/texture.cpp | 2 +- tests/auto/render/scene2d/tst_scene2d.cpp | 1 + tests/auto/render/textures/tst_textures.cpp | 33 +++--- 28 files changed, 424 insertions(+), 273 deletions(-) create mode 100644 src/render/renderers/opengl/managers/gl_handle_types_p.h create mode 100644 src/render/renderers/opengl/managers/glresourcemanagers.cpp create mode 100644 src/render/renderers/opengl/managers/glresourcemanagers_p.h create mode 100644 src/render/renderers/opengl/managers/managers.pri delete mode 100644 src/render/renderers/opengl/textures/gltexturemanager_p.h diff --git a/src/render/backend/handle_types_p.h b/src/render/backend/handle_types_p.h index 195fc2cc6..73b4df341 100644 --- a/src/render/backend/handle_types_p.h +++ b/src/render/backend/handle_types_p.h @@ -89,12 +89,9 @@ class GeometryRenderer; class ObjectPicker; class RayCaster; class BoundingVolumeDebug; -class OpenGLVertexArrayObject; class Light; class EnvironmentLight; class ComputeCommand; -class GLBuffer; -class GLTexture; class RenderStateNode; class Armature; class Skeleton; @@ -111,7 +108,6 @@ typedef Qt3DCore::QHandle HLayer; typedef Qt3DCore::QHandle HLevelOfDetail; typedef Qt3DCore::QHandle HMaterial; typedef Qt3DCore::QHandle HMatrix; -typedef Qt3DCore::QHandle HVao; typedef Qt3DCore::QHandle HShader; typedef Qt3DCore::QHandle HShaderBuilder; typedef Qt3DCore::QHandle HTechnique; @@ -133,8 +129,6 @@ typedef Qt3DCore::QHandle HBoundingVolumeDebug; typedef Qt3DCore::QHandle HLight; typedef Qt3DCore::QHandle HEnvironmentLight; typedef Qt3DCore::QHandle HComputeCommand; -typedef Qt3DCore::QHandle HGLBuffer; -typedef Qt3DCore::QHandle HGLTexture; typedef Qt3DCore::QHandle HRenderState; typedef Qt3DCore::QHandle HArmature; typedef Qt3DCore::QHandle HSkeleton; diff --git a/src/render/backend/managers_p.h b/src/render/backend/managers_p.h index 759c16f64..024059a30 100644 --- a/src/render/backend/managers_p.h +++ b/src/render/backend/managers_p.h @@ -71,15 +71,12 @@ #include #include #include -#include -#include #include #include #include #include #include #include -#include #include #include #include @@ -266,15 +263,6 @@ public: TransformManager() {} }; -class VAOManager : public Qt3DCore::QResourceManager< - OpenGLVertexArrayObject, - VAOIdentifier, - Qt3DCore::NonLockingPolicy> -{ -public: - VAOManager() {} -}; - class RenderTargetManager : public Qt3DCore::QResourceManager< RenderTarget, Qt3DCore::QNodeId, @@ -321,17 +309,6 @@ public: ShaderDataManager() {} }; -class GLBufferManager : public Qt3DCore::QResourceManager< - GLBuffer, - Qt3DCore::QNodeId, - Qt3DCore::NonLockingPolicy> -{ -}; - -class GLFenceManager : public QHash -{ -}; - class TextureImageManager : public Qt3DCore::QResourceManager< TextureImage, Qt3DCore::QNodeId, @@ -471,7 +448,6 @@ Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::BoundingVolumeDebug, Q_REQUIRES_CLEA Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::ComputeCommand, Q_REQUIRES_CLEANUP) Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::Parameter, Q_REQUIRES_CLEANUP) Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::Transform, Q_REQUIRES_CLEANUP) -Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP) Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::Armature, Q_REQUIRES_CLEANUP) Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::Skeleton, Q_REQUIRES_CLEANUP) Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::Joint, Q_REQUIRES_CLEANUP) diff --git a/src/render/backend/nodemanagers.cpp b/src/render/backend/nodemanagers.cpp index 5e452f886..8603d4fb9 100644 --- a/src/render/backend/nodemanagers.cpp +++ b/src/render/backend/nodemanagers.cpp @@ -42,14 +42,12 @@ #include #include #include -#include #include #include #include #include #include -#include QT_BEGIN_NAMESPACE @@ -62,7 +60,6 @@ NodeManagers::NodeManagers() , m_renderNodesManager(new EntityManager()) , m_materialManager(new MaterialManager()) , m_worldMatrixManager(new MatrixManager()) - , m_vaoManager(new VAOManager()) , m_shaderManager(new ShaderManager()) , m_shaderBuilderManager(new ShaderBuilderManager()) , m_techniqueManager(new TechniqueManager()) @@ -70,7 +67,6 @@ NodeManagers::NodeManagers() , m_renderPassManager(new RenderPassManager()) , m_textureManager(new TextureManager()) , m_textureImageManager(new TextureImageManager()) - , m_glTextureManager(new GLTextureManager()) , m_layerManager(new LayerManager()) , m_levelOfDetailManager(new LevelOfDetailManager()) , m_filterKeyManager(new FilterKeyManager()) @@ -81,8 +77,6 @@ NodeManagers::NodeManagers() , m_attachmentManager(new AttachmentManager()) , m_parameterManager(new ParameterManager()) , m_shaderDataManager(new ShaderDataManager()) - , m_glBufferManager(new GLBufferManager()) - , m_glFenceManager(new GLFenceManager()) , m_bufferManager(new BufferManager()) , m_attributeManager(new AttributeManager()) , m_geometryManager(new GeometryManager()) @@ -107,13 +101,11 @@ NodeManagers::~NodeManagers() delete m_cameraManager; delete m_materialManager; delete m_worldMatrixManager; - delete m_vaoManager; delete m_shaderManager; delete m_shaderBuilderManager; delete m_techniqueManager; delete m_effectManager; delete m_renderPassManager; - delete m_glTextureManager; delete m_textureManager; delete m_layerManager; delete m_levelOfDetailManager; @@ -124,8 +116,6 @@ NodeManagers::~NodeManagers() delete m_attachmentManager; delete m_parameterManager; delete m_shaderDataManager; - delete m_glBufferManager; - delete m_glFenceManager; delete m_textureImageManager; delete m_bufferManager; delete m_attributeManager; @@ -178,12 +168,6 @@ MatrixManager *NodeManagers::manager() const noexcept return m_worldMatrixManager; } -template<> -VAOManager *NodeManagers::manager() const noexcept -{ - return m_vaoManager; -} - template<> ShaderManager *NodeManagers::manager() const noexcept { @@ -280,12 +264,6 @@ ShaderDataManager *NodeManagers::manager() const noexcept return m_shaderDataManager; } -template<> -GLBufferManager *NodeManagers::manager() const noexcept -{ - return m_glBufferManager; -} - template<> TextureImageManager *NodeManagers::manager() const noexcept { diff --git a/src/render/backend/nodemanagers_p.h b/src/render/backend/nodemanagers_p.h index 8dda4e8ad..62a73b510 100644 --- a/src/render/backend/nodemanagers_p.h +++ b/src/render/backend/nodemanagers_p.h @@ -75,7 +75,6 @@ class RayCasterManager; class BoundingVolumeDebugManager; class MaterialManager; class MatrixManager; -class VAOManager; class ShaderManager; class ShaderBuilderManager; class TechniqueManager; @@ -86,13 +85,10 @@ class SceneManager; class AttachmentManager; class ParameterManager; class ShaderDataManager; -class GLBufferManager; -class GLFenceManager; class TextureImageManager; class FilterKeyManager; class FrameGraphManager; class TransformManager; -class GLTextureManager; class TextureManager; class TextureDataManager; class TextureImageDataManager; @@ -127,7 +123,6 @@ class RenderTargetOutput; class RenderTarget; class ShaderData; class Parameter; -class GLBuffer; class TextureImage; class Buffer; class Attribute; @@ -143,7 +138,6 @@ class RenderStateNode; class Armature; class Skeleton; class Joint; -class OpenGLVertexArrayObject; class ShaderImage; class ResourceAccessor; @@ -192,13 +186,11 @@ public: inline EntityManager *renderNodesManager() const noexcept { return m_renderNodesManager; } inline MaterialManager *materialManager() const noexcept { return m_materialManager; } inline MatrixManager *worldMatrixManager() const noexcept { return m_worldMatrixManager; } - inline VAOManager *vaoManager() const noexcept { return m_vaoManager; } inline ShaderManager *shaderManager() const noexcept { return m_shaderManager; } inline ShaderBuilderManager *shaderBuilderManager() const noexcept { return m_shaderBuilderManager; } inline TechniqueManager *techniqueManager() const noexcept { return m_techniqueManager; } inline EffectManager *effectManager() const noexcept { return m_effectManager; } inline RenderPassManager *renderPassManager() const noexcept { return m_renderPassManager; } - inline GLTextureManager *glTextureManager() const noexcept { return m_glTextureManager; } inline TextureManager *textureManager() const noexcept { return m_textureManager; } inline LayerManager *layerManager() const noexcept { return m_layerManager; } inline LevelOfDetailManager *levelOfDetailManager() const noexcept { return m_levelOfDetailManager; } @@ -210,8 +202,6 @@ public: inline AttachmentManager *attachmentManager() const noexcept { return m_attachmentManager; } inline ParameterManager *parameterManager() const noexcept { return m_parameterManager; } inline ShaderDataManager *shaderDataManager() const noexcept { return m_shaderDataManager; } - inline GLBufferManager *glBufferManager() const noexcept { return m_glBufferManager; } - inline GLFenceManager *glFenceManager() const noexcept { return m_glFenceManager; } inline TextureImageManager *textureImageManager() const noexcept { return m_textureImageManager; } inline BufferManager *bufferManager() const noexcept { return m_bufferManager; } inline AttributeManager *attributeManager() const noexcept { return m_attributeManager; } @@ -236,7 +226,6 @@ private: EntityManager *m_renderNodesManager; MaterialManager *m_materialManager; MatrixManager *m_worldMatrixManager; - VAOManager *m_vaoManager; ShaderManager *m_shaderManager; ShaderBuilderManager *m_shaderBuilderManager; TechniqueManager *m_techniqueManager; @@ -244,7 +233,6 @@ private: RenderPassManager *m_renderPassManager; TextureManager *m_textureManager; TextureImageManager *m_textureImageManager; - GLTextureManager *m_glTextureManager; LayerManager *m_layerManager; LevelOfDetailManager *m_levelOfDetailManager; FilterKeyManager *m_filterKeyManager; @@ -255,8 +243,6 @@ private: AttachmentManager *m_attachmentManager; ParameterManager *m_parameterManager; ShaderDataManager *m_shaderDataManager; - GLBufferManager *m_glBufferManager; - GLFenceManager *m_glFenceManager; BufferManager *m_bufferManager; AttributeManager *m_attributeManager; GeometryManager *m_geometryManager; @@ -290,9 +276,6 @@ Q_3DRENDERSHARED_PRIVATE_EXPORT MaterialManager *NodeManagers::manager template<> Q_3DRENDERSHARED_PRIVATE_EXPORT MatrixManager *NodeManagers::manager() const noexcept; -template<> -Q_3DRENDERSHARED_PRIVATE_EXPORT VAOManager *NodeManagers::manager() const noexcept; - template<> Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderManager *NodeManagers::manager() const noexcept; @@ -342,14 +325,11 @@ template<> Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderDataManager *NodeManagers::manager() const noexcept; template<> -Q_3DRENDERSHARED_PRIVATE_EXPORT GLBufferManager *NodeManagers::manager() const noexcept; +Q_3DRENDERSHARED_PRIVATE_EXPORT BufferManager *NodeManagers::manager() const noexcept; template<> Q_3DRENDERSHARED_PRIVATE_EXPORT TextureImageManager *NodeManagers::manager() const noexcept; -template<> -Q_3DRENDERSHARED_PRIVATE_EXPORT BufferManager *NodeManagers::manager() const noexcept; - template<> Q_3DRENDERSHARED_PRIVATE_EXPORT AttributeManager *NodeManagers::manager() const noexcept; diff --git a/src/render/backend/resourceaccessor.cpp b/src/render/backend/resourceaccessor.cpp index 4f70df436..af19546b7 100644 --- a/src/render/backend/resourceaccessor.cpp +++ b/src/render/backend/resourceaccessor.cpp @@ -42,9 +42,7 @@ #include #include #include -#include #include -#include #include @@ -59,10 +57,10 @@ RenderBackendResourceAccessor::~RenderBackendResourceAccessor() } ResourceAccessor::ResourceAccessor(NodeManagers *mgr) - : m_glTextureManager(mgr->glTextureManager()) - , m_textureManager(mgr->textureManager()) - , m_attachmentManager(mgr->attachmentManager()) - , m_entityManager(mgr->renderNodesManager()) +// : m_glTextureManager(mgr->glTextureManager()) +// , m_textureManager(mgr->textureManager()) +// , m_attachmentManager(mgr->attachmentManager()) +// , m_entityManager(mgr->renderNodesManager()) { } @@ -70,58 +68,58 @@ ResourceAccessor::ResourceAccessor(NodeManagers *mgr) // called by render plugins from arbitrary thread bool ResourceAccessor::accessResource(ResourceType type, Qt3DCore::QNodeId nodeId, void **handle, QMutex **lock) { - switch (type) { - - case RenderBackendResourceAccessor::OGLTextureWrite: - Q_FALLTHROUGH(); - case RenderBackendResourceAccessor::OGLTextureRead: - { - Texture *tex = m_textureManager->lookupResource(nodeId); - if (!tex) - return false; - - GLTexture *glTex = m_glTextureManager->lookupResource(tex->peerId()); - if (!glTex) - return false; - - if (glTex->isDirty()) - return false; - - if (type == RenderBackendResourceAccessor::OGLTextureWrite) - glTex->setExternalRenderingEnabled(true); - - QOpenGLTexture **glTextureHandle = reinterpret_cast(handle); - *glTextureHandle = glTex->getGLTexture(); - - if (type == RenderBackendResourceAccessor::OGLTextureWrite) - *lock = glTex->externalRenderingLock(); - - return true; - } - - case RenderBackendResourceAccessor::OutputAttachment: { - RenderTargetOutput *output = m_attachmentManager->lookupResource(nodeId); - if (output) { - Attachment **attachmentData = reinterpret_cast(handle); - *attachmentData = output->attachment(); - return true; - } - break; - } - - case RenderBackendResourceAccessor::EntityHandle: { - Entity *entity = m_entityManager->lookupResource(nodeId); - if (entity) { - Entity **pEntity = reinterpret_cast(handle); - *pEntity = entity; - return true; - } - break; - } - - default: - break; - } +// switch (type) { + +// case RenderBackendResourceAccessor::OGLTextureWrite: +// Q_FALLTHROUGH(); +// case RenderBackendResourceAccessor::OGLTextureRead: +// { +// Texture *tex = m_textureManager->lookupResource(nodeId); +// if (!tex) +// return false; + +// GLTexture *glTex = m_glTextureManager->lookupResource(tex->peerId()); +// if (!glTex) +// return false; + +// if (glTex->isDirty()) +// return false; + +// if (type == RenderBackendResourceAccessor::OGLTextureWrite) +// glTex->setExternalRenderingEnabled(true); + +// QOpenGLTexture **glTextureHandle = reinterpret_cast(handle); +// *glTextureHandle = glTex->getGLTexture(); + +// if (type == RenderBackendResourceAccessor::OGLTextureWrite) +// *lock = glTex->externalRenderingLock(); + +// return true; +// } + +// case RenderBackendResourceAccessor::OutputAttachment: { +// RenderTargetOutput *output = m_attachmentManager->lookupResource(nodeId); +// if (output) { +// Attachment **attachmentData = reinterpret_cast(handle); +// *attachmentData = output->attachment(); +// return true; +// } +// break; +// } + +// case RenderBackendResourceAccessor::EntityHandle: { +// Entity *entity = m_entityManager->lookupResource(nodeId); +// if (entity) { +// Entity **pEntity = reinterpret_cast(handle); +// *pEntity = entity; +// return true; +// } +// break; +// } + +// default: +// break; +// } return false; } diff --git a/src/render/backend/resourceaccessor_p.h b/src/render/backend/resourceaccessor_p.h index ec53a04a2..6ceb8677b 100644 --- a/src/render/backend/resourceaccessor_p.h +++ b/src/render/backend/resourceaccessor_p.h @@ -89,10 +89,10 @@ public: ResourceAccessor(NodeManagers *mgr); bool accessResource(ResourceType type, Qt3DCore::QNodeId nodeId, void **handle, QMutex **lock) final; private: - GLTextureManager *m_glTextureManager; - TextureManager *m_textureManager; - AttachmentManager *m_attachmentManager; - EntityManager *m_entityManager; +// GLTextureManager *m_glTextureManager; +// TextureManager *m_textureManager; +// AttachmentManager *m_attachmentManager; +// EntityManager *m_entityManager; }; } // namespace Render diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index 1ce9f172f..35a037527 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -645,6 +645,8 @@ void QRenderAspect::onUnregistered() d->unregisterBackendTypes(); + d->m_renderer->releaseGraphicsResources(); + delete d->m_nodeManagers; d->m_nodeManagers = nullptr; diff --git a/src/render/renderers/opengl/debug/imguirenderer.cpp b/src/render/renderers/opengl/debug/imguirenderer.cpp index f432970e4..8abe1b8c0 100644 --- a/src/render/renderers/opengl/debug/imguirenderer.cpp +++ b/src/render/renderers/opengl/debug/imguirenderer.cpp @@ -48,6 +48,7 @@ #include #include #include +#include #include #include diff --git a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp b/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp index 71edc1c74..9e5b3e158 100644 --- a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp +++ b/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp @@ -56,7 +56,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h b/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h index 2f4df2e22..b4f589e71 100644 --- a/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h +++ b/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h @@ -72,6 +72,7 @@ #include #include #include +#include #include QT_BEGIN_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp index 47779dded..3a619f361 100644 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp +++ b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp @@ -54,14 +54,15 @@ #include #include #include +#include #include #include #include -#include #include #include #include #include +#include #include #if !defined(QT_OPENGL_ES_2) @@ -530,7 +531,7 @@ GLuint SubmissionContext::updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeI bool needsResize = !m_renderTargetsSize.contains(fboId); // not even initialized yet? if (!needsResize) { // render target exists, has attachment been resized? - GLTextureManager *glTextureManager = m_renderer->nodeManagers()->glTextureManager(); + GLTextureManager *glTextureManager = m_renderer->glResourceManagers()->glTextureManager(); const QSize s = m_renderTargetsSize[fboId]; const auto attachments_ = attachments.attachments(); for (const Attachment &attachment : attachments_) { @@ -814,7 +815,7 @@ void SubmissionContext::bindFrameBufferAttachmentHelper(GLuint fboId, const Atta // stencil before 3.1 with the appropriate extension). QSize fboSize; - GLTextureManager *glTextureManager = m_renderer->nodeManagers()->glTextureManager(); + GLTextureManager *glTextureManager = m_renderer->glResourceManagers()->glTextureManager(); const auto attachments_ = attachments.attachments(); for (const Attachment &attachment : attachments_) { GLTexture *rTex = glTextureManager->lookupResource(attachment.m_textureUuid); @@ -1157,8 +1158,6 @@ bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) // Set the pinned texture of the previous material texture // to pinable so that we should easily find an available texture unit - NodeManagers *manager = m_renderer->nodeManagers(); - m_textureContext.deactivateTexturesWithScope(TextureSubmissionContext::TextureScopeMaterial); // Update the uniforms with the correct texture unit id's PackUniformHash &uniformValues = parameterPack.uniforms(); @@ -1169,7 +1168,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) const ShaderParameterPack::NamedResource &namedTex = parameterPack.textures().at(i); // Given a Texture QNodeId, we retrieve the associated shared GLTexture if (uniformValues.contains(namedTex.glslNameId)) { - GLTexture *t = manager->glTextureManager()->lookupResource(namedTex.nodeId); + GLTexture *t = m_renderer->glResourceManagers()->glTextureManager()->lookupResource(namedTex.nodeId); if (t != nullptr) { UniformValue &texUniform = uniformValues.value(namedTex.glslNameId); if (texUniform.valueType() == UniformValue::TextureValue) { @@ -1194,9 +1193,9 @@ bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) const ShaderParameterPack::NamedResource &namedTex = parameterPack.images().at(i); // Given a Texture QNodeId, we retrieve the associated shared GLTexture if (uniformValues.contains(namedTex.glslNameId)) { - ShaderImage *img = manager->shaderImageManager()->lookupResource(namedTex.nodeId); + ShaderImage *img = m_renderer->nodeManagers()->shaderImageManager()->lookupResource(namedTex.nodeId); if (img != nullptr) { - GLTexture *t = manager->glTextureManager()->lookupResource(img->textureId()); + GLTexture *t = m_renderer->glResourceManagers()->glTextureManager()->lookupResource(img->textureId()); if (t == nullptr) { qCWarning(Backend) << "Shader Image referencing invalid texture"; continue; @@ -1277,7 +1276,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) void SubmissionContext::enableAttribute(const VAOVertexAttribute &attr) { // Bind buffer within the current VAO - GLBuffer *buf = m_renderer->nodeManagers()->glBufferManager()->data(attr.bufferHandle); + GLBuffer *buf = m_renderer->glResourceManagers()->glBufferManager()->data(attr.bufferHandle); Q_ASSERT(buf); bindGLBuffer(buf, attr.attributeType); @@ -1316,7 +1315,7 @@ void SubmissionContext::specifyAttribute(const Attribute *attribute, } const GLint attributeDataType = glDataTypeFromAttributeDataType(attribute->vertexBaseType()); - const HGLBuffer glBufferHandle = m_renderer->nodeManagers()->glBufferManager()->lookupHandle(buffer->peerId()); + const HGLBuffer glBufferHandle = m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); Q_ASSERT(!glBufferHandle.isNull()); const GLBuffer::Type attributeType = attributeTypeToGLBufferType(attribute->attributeType()); @@ -1365,21 +1364,21 @@ void SubmissionContext::specifyIndices(Buffer *buffer) // bound within the current VAO // Save this in the current emulated VAO if (m_currentVAO) - m_currentVAO->saveIndexAttribute(m_renderer->nodeManagers()->glBufferManager()->lookupHandle(buffer->peerId())); + m_currentVAO->saveIndexAttribute(m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId())); } void SubmissionContext::updateBuffer(Buffer *buffer) { const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); if (it != m_renderBufferHash.end()) - uploadDataToGLBuffer(buffer, m_renderer->nodeManagers()->glBufferManager()->data(it.value())); + uploadDataToGLBuffer(buffer, m_renderer->glResourceManagers()->glBufferManager()->data(it.value())); } QByteArray SubmissionContext::downloadBufferContent(Buffer *buffer) { const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); if (it != m_renderBufferHash.end()) - return downloadDataFromGLBuffer(buffer, m_renderer->nodeManagers()->glBufferManager()->data(it.value())); + return downloadDataFromGLBuffer(buffer, m_renderer->glResourceManagers()->glBufferManager()->data(it.value())); return QByteArray(); } @@ -1388,13 +1387,13 @@ void SubmissionContext::releaseBuffer(Qt3DCore::QNodeId bufferId) auto it = m_renderBufferHash.find(bufferId); if (it != m_renderBufferHash.end()) { HGLBuffer glBuffHandle = it.value(); - GLBuffer *glBuff = m_renderer->nodeManagers()->glBufferManager()->data(glBuffHandle); + GLBuffer *glBuff = m_renderer->glResourceManagers()->glBufferManager()->data(glBuffHandle); Q_ASSERT(glBuff); // Destroy the GPU resource glBuff->destroy(this); // Destroy the GLBuffer instance - m_renderer->nodeManagers()->glBufferManager()->releaseResource(bufferId); + m_renderer->glResourceManagers()->glBufferManager()->releaseResource(bufferId); // Remove Id - HGLBuffer entry m_renderBufferHash.erase(it); } @@ -1410,12 +1409,12 @@ GLBuffer *SubmissionContext::glBufferForRenderBuffer(Buffer *buf, GLBuffer::Type { if (!m_renderBufferHash.contains(buf->peerId())) m_renderBufferHash.insert(buf->peerId(), createGLBufferFor(buf, type)); - return m_renderer->nodeManagers()->glBufferManager()->data(m_renderBufferHash.value(buf->peerId())); + return m_renderer->glResourceManagers()->glBufferManager()->data(m_renderBufferHash.value(buf->peerId())); } HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer, GLBuffer::Type type) { - GLBuffer *b = m_renderer->nodeManagers()->glBufferManager()->getOrCreateResource(buffer->peerId()); + GLBuffer *b = m_renderer->glResourceManagers()->glBufferManager()->getOrCreateResource(buffer->peerId()); // b.setUsagePattern(static_cast(buffer->usage())); Q_ASSERT(b); if (!b->create(this)) @@ -1424,7 +1423,7 @@ HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer, GLBuffer::Type ty if (!bindGLBuffer(b, type)) qCWarning(Render::Io) << Q_FUNC_INFO << "buffer binding failed"; - return m_renderer->nodeManagers()->glBufferManager()->lookupHandle(buffer->peerId()); + return m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); } bool SubmissionContext::bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type) diff --git a/src/render/renderers/opengl/io/glbuffer_p.h b/src/render/renderers/opengl/io/glbuffer_p.h index 731634b6b..676fb00d9 100644 --- a/src/render/renderers/opengl/io/glbuffer_p.h +++ b/src/render/renderers/opengl/io/glbuffer_p.h @@ -94,6 +94,11 @@ public: inline bool isCreated() const { return m_isCreated; } inline bool isBound() const { return m_bound; } +#ifdef Q_OS_WIN + // To get MSVC to compile even though we don't need any cleanup + void cleanup() {} +#endif + private: GLuint m_bufferId; bool m_isCreated; diff --git a/src/render/renderers/opengl/managers/gl_handle_types_p.h b/src/render/renderers/opengl/managers/gl_handle_types_p.h new file mode 100644 index 000000000..eb25bab7f --- /dev/null +++ b/src/render/renderers/opengl/managers/gl_handle_types_p.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H +#define QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class GLBuffer; +class GLTexture; +class OpenGLVertexArrayObject; + +typedef Qt3DCore::QHandle HGLBuffer; +typedef Qt3DCore::QHandle HVao; +typedef Qt3DCore::QHandle HGLTexture; + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H diff --git a/src/render/renderers/opengl/managers/glresourcemanagers.cpp b/src/render/renderers/opengl/managers/glresourcemanagers.cpp new file mode 100644 index 000000000..e3be4c7af --- /dev/null +++ b/src/render/renderers/opengl/managers/glresourcemanagers.cpp @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glresourcemanagers_p.h" +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + + +GLResourceManagers::GLResourceManagers() + : m_glBufferManager(new GLBufferManager()) + , m_glTextureManager(new GLTextureManager()) + , m_glFenceManager(new GLFenceManager()) + , m_vaoManager(new VAOManager()) +{ +} + +GLResourceManagers::~GLResourceManagers() +{ + delete m_vaoManager; + delete m_glFenceManager; + delete m_glTextureManager; + delete m_glBufferManager; +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/managers/glresourcemanagers_p.h b/src/render/renderers/opengl/managers/glresourcemanagers_p.h new file mode 100644 index 000000000..a2db09316 --- /dev/null +++ b/src/render/renderers/opengl/managers/glresourcemanagers_p.h @@ -0,0 +1,123 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H +#define QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT GLFenceManager : public QHash +{ +}; + +class Q_AUTOTEST_EXPORT VAOManager : public Qt3DCore::QResourceManager< + OpenGLVertexArrayObject, + VAOIdentifier, + Qt3DCore::NonLockingPolicy> +{ +public: + VAOManager() {} +}; + +class Q_AUTOTEST_EXPORT GLBufferManager : public Qt3DCore::QResourceManager< + GLBuffer, + Qt3DCore::QNodeId, + Qt3DCore::NonLockingPolicy> +{ +}; + +class Q_AUTOTEST_EXPORT GLTextureManager : public Qt3DCore::QResourceManager< + GLTexture, + Qt3DCore::QNodeId, + Qt3DCore::NonLockingPolicy> +{ +public: + QHash texNodeIdForGLTexture; +}; + + +class Q_AUTOTEST_EXPORT GLResourceManagers +{ +public: + GLResourceManagers(); + ~GLResourceManagers(); + + inline VAOManager *vaoManager() const noexcept { return m_vaoManager; } + inline GLTextureManager *glTextureManager() const noexcept { return m_glTextureManager; } + inline GLBufferManager *glBufferManager() const noexcept { return m_glBufferManager; } + inline GLFenceManager *glFenceManager() const noexcept { return m_glFenceManager; } + +private: + GLBufferManager *m_glBufferManager; + GLTextureManager *m_glTextureManager; + GLFenceManager *m_glFenceManager; + VAOManager *m_vaoManager; +}; + +} // Render + +} // Qt3DRender + +Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP) + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H diff --git a/src/render/renderers/opengl/managers/managers.pri b/src/render/renderers/opengl/managers/managers.pri new file mode 100644 index 000000000..97a4c2c45 --- /dev/null +++ b/src/render/renderers/opengl/managers/managers.pri @@ -0,0 +1,8 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/gl_handle_types_p.h \ + $$PWD/glresourcemanagers_p.h + +SOURCES += \ + $$PWD/glresourcemanagers.cpp diff --git a/src/render/renderers/opengl/opengl.pri b/src/render/renderers/opengl/opengl.pri index f72f2d1a5..ad9d5c79a 100644 --- a/src/render/renderers/opengl/opengl.pri +++ b/src/render/renderers/opengl/opengl.pri @@ -5,6 +5,7 @@ include (io/io.pri) include (textures/textures.pri) include (graphicshelpers/graphicshelpers.pri) include (renderstates/renderstates.pri) +include (managers/managers.pri) !integrity: include (debug/debug.pri) diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp b/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp index f5d0a64f5..58ce70c28 100644 --- a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp +++ b/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp @@ -40,7 +40,7 @@ #include "openglvertexarrayobject_p.h" #include #include -#include +#include #include QT_BEGIN_NAMESPACE @@ -71,7 +71,7 @@ void OpenGLVertexArrayObject::bind() for (const SubmissionContext::VAOVertexAttribute &attr : qAsConst(m_vertexAttributes)) m_ctx->enableAttribute(attr); if (!m_indexAttribute.isNull()) - m_ctx->bindGLBuffer(m_ctx->m_renderer->nodeManagers()->glBufferManager()->data(m_indexAttribute), + m_ctx->bindGLBuffer(m_ctx->m_renderer->glResourceManagers()->glBufferManager()->data(m_indexAttribute), GLBuffer::IndexBuffer); } } diff --git a/src/render/renderers/opengl/renderer/rendercommand_p.h b/src/render/renderers/opengl/renderer/rendercommand_p.h index be00fb753..e1cf7a4e0 100644 --- a/src/render/renderers/opengl/renderer/rendercommand_p.h +++ b/src/render/renderers/opengl/renderer/rendercommand_p.h @@ -56,6 +56,7 @@ #include #include #include +#include #include #include #include diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index c0549a8fd..21eeae9d8 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -77,7 +77,6 @@ #include #include #include -#include #include #include #include @@ -99,6 +98,8 @@ #include #endif +#include + #include #include #include @@ -280,6 +281,7 @@ Renderer::Renderer(QRenderAspect::RenderType type) JobTypes::EntityComponentTypeFiltering)) , m_ownedContext(false) , m_offscreenHelper(nullptr) + , m_glResourceManagers(nullptr) , m_commandExecuter(new Qt3DRender::Debug::CommandExecuter(this)) , m_shouldSwapBuffers(true) , m_imGuiRenderer(nullptr) @@ -332,6 +334,7 @@ Renderer::~Renderer() delete m_renderQueue; delete m_defaultRenderStateSet; delete m_shaderCache; + delete m_glResourceManagers; if (!m_ownedContext) QObject::disconnect(m_contextConnection); @@ -376,6 +379,7 @@ void Renderer::setJobsInLastFrame(int jobsInLastFrame) void Renderer::setNodeManagers(NodeManagers *managers) { m_nodesManager = managers; + m_glResourceManagers = new GLResourceManagers(); m_updateShaderDataTransformJob->setManagers(m_nodesManager); m_cleanupJob->setManagers(m_nodesManager); @@ -561,6 +565,12 @@ void Renderer::shutdown() m_submitRenderViewsSemaphore.release(1); m_renderThread->wait(); } + + // Destroy internal managers + // This needs to be done before the nodeManager is destroy + // as the internal resources might somehow rely on nodeManager resources + delete m_glResourceManagers; + m_glResourceManagers = nullptr; } /*! @@ -599,23 +609,23 @@ void Renderer::releaseGraphicsResources() if (context->thread() == QThread::currentThread() && context->makeCurrent(offscreenSurface)) { // Clean up the graphics context and any resources - const QVector activeTexturesHandles = m_nodesManager->glTextureManager()->activeHandles(); + const QVector activeTexturesHandles = m_glResourceManagers->glTextureManager()->activeHandles(); for (const HGLTexture &textureHandle : activeTexturesHandles) { - GLTexture *tex = m_nodesManager->glTextureManager()->data(textureHandle); + GLTexture *tex = m_glResourceManagers->glTextureManager()->data(textureHandle); tex->destroy(); } // Do the same thing with buffers - const QVector activeBuffers = m_nodesManager->glBufferManager()->activeHandles(); + const QVector activeBuffers = m_glResourceManagers->glBufferManager()->activeHandles(); for (const HGLBuffer &bufferHandle : activeBuffers) { - GLBuffer *buffer = m_nodesManager->glBufferManager()->data(bufferHandle); + GLBuffer *buffer = m_glResourceManagers->glBufferManager()->data(bufferHandle); buffer->destroy(m_submissionContext.data()); } // Do the same thing with VAOs - const QVector activeVaos = m_nodesManager->vaoManager()->activeHandles(); + const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); for (const HVao &vaoHandle : activeVaos) { - OpenGLVertexArrayObject *vao = m_nodesManager->vaoManager()->data(vaoHandle); + OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(vaoHandle); vao->destroy(); } @@ -1029,9 +1039,9 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView // Executed in a job void Renderer::lookForAbandonedVaos() { - const QVector activeVaos = m_nodesManager->vaoManager()->activeHandles(); - for (const HVao &handle : activeVaos) { - OpenGLVertexArrayObject *vao = m_nodesManager->vaoManager()->data(handle); + const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); + for (HVao handle : activeVaos) { + OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(handle); // Make sure to only mark VAOs for deletion that were already created // (ignore those that might be currently under construction in the render thread) @@ -1275,7 +1285,7 @@ void Renderer::updateGLResources() { // Update active fence objects: // - Destroy fences that have reached their signaled state - GLFenceManager *fenceManager = m_nodesManager->glFenceManager(); + GLFenceManager *fenceManager = m_glResourceManagers->glFenceManager(); const auto end = fenceManager->end(); auto it = fenceManager->begin(); while (it != end) { @@ -1347,7 +1357,7 @@ void Renderer::updateGLResources() // AspectThread are locked ensuring no races between Texture/TextureImage and // GLTexture if (m_submissionContext != nullptr) { - GLTextureManager *glTextureManager = m_nodesManager->glTextureManager(); + GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); const QVector glTextureHandles = glTextureManager->activeHandles(); // Upload texture data for (const HGLTexture &glTextureHandle : glTextureHandles) { @@ -1393,7 +1403,7 @@ void Renderer::updateTexture(Texture *texture) // this will create 2 identical GLTextures, no sharing will take place // Try to find the associated GLTexture for the backend Texture - GLTextureManager *glTextureManager = m_nodesManager->glTextureManager(); + GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); GLTexture *glTexture = glTextureManager->lookupResource(texture->peerId()); // No GLTexture associated yet -> create it @@ -1446,7 +1456,7 @@ void Renderer::updateTexture(Texture *texture) // Render Thread void Renderer::cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId) { - GLTextureManager *glTextureManager = m_nodesManager->glTextureManager(); + GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); GLTexture *glTexture = glTextureManager->lookupResource(cleanedUpTextureId); // Destroying the GLTexture implicitely also destroy the GL resources @@ -1553,7 +1563,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVectorinsertFenceIds(); - GLFenceManager *fenceManager = m_nodesManager->glFenceManager(); + GLFenceManager *fenceManager = m_glResourceManagers->glFenceManager(); for (const Qt3DCore::QNodeId insertFenceId : insertFenceIds) { // If the fence is not in the manager, then it hasn't been inserted // into the command stream yet. @@ -2124,7 +2134,7 @@ void Renderer::createOrUpdateVAO(RenderCommand *command, { const VAOIdentifier vaoKey(command->m_geometry, command->m_shader); - VAOManager *vaoManager = m_nodesManager->vaoManager(); + VAOManager *vaoManager = m_glResourceManagers->vaoManager(); command->m_vao = vaoManager->lookupHandle(vaoKey); if (command->m_vao.isNull()) { @@ -2167,7 +2177,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) continue; } - vao = m_nodesManager->vaoManager()->data(command.m_vao); + vao = m_glResourceManagers->vaoManager()->data(command.m_vao); // something may have went wrong when initializing the VAO if (!vao->isSpecified()) { @@ -2338,11 +2348,11 @@ void Renderer::cleanGraphicsResources() for (const HVao &vaoHandle : abandonedVaos) { // might have already been destroyed last frame, but added by the cleanup job before, so // check if the VAO is really still existent - OpenGLVertexArrayObject *vao = m_nodesManager->vaoManager()->data(vaoHandle); + OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(vaoHandle); if (vao) { vao->destroy(); // We remove VAO from manager using its VAOIdentifier - m_nodesManager->vaoManager()->releaseResource(vao->key()); + m_glResourceManagers->vaoManager()->release(vaoHandle); } } } diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index 4b8574252..d8f95dc2b 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -56,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -153,6 +154,7 @@ class VSyncFrameAdvanceService; class PickEventFilter; class NodeManagers; class ShaderCache; +class GLResourceManagers; class UpdateLevelOfDetailJob; typedef QSharedPointer UpdateLevelOfDetailJobPtr; @@ -256,6 +258,7 @@ public: RenderSettings *settings() const override; QOpenGLContext *shareContext() const override; + inline GLResourceManagers *glResourceManagers() const { return m_glResourceManagers; } // Executed in secondary GL thread void loadShader(Shader *shader, Qt3DRender::Render::HShader shaderHandle) override; @@ -431,6 +434,7 @@ private: bool m_ownedContext; OffscreenSurfaceHelper *m_offscreenHelper; + GLResourceManagers *m_glResourceManagers; QMutex m_offscreenSurfaceMutex; QScopedPointer m_commandExecuter; diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp index f34015455..2a16c9bfd 100644 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ b/src/render/renderers/opengl/renderer/renderview.cpp @@ -68,6 +68,7 @@ #include #include #include +#include #include #include #include diff --git a/src/render/renderers/opengl/textures/gltexturemanager_p.h b/src/render/renderers/opengl/textures/gltexturemanager_p.h deleted file mode 100644 index 335af136c..000000000 --- a/src/render/renderers/opengl/textures/gltexturemanager_p.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GLTEXTUREMANAGER_H -#define QT3DRENDER_RENDER_GLTEXTUREMANAGER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class Q_AUTOTEST_EXPORT GLTextureManager : public Qt3DCore::QResourceManager< - GLTexture, - Qt3DCore::QNodeId, - Qt3DCore::NonLockingPolicy> -{ -public: - QHash texNodeIdForGLTexture; -}; - -} // namespace Render -} // namespace Qt3DRender - -Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::GLTexture, Q_REQUIRES_CLEANUP) - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GLTEXTUREMANAGER_H diff --git a/src/render/renderers/opengl/textures/textures.pri b/src/render/renderers/opengl/textures/textures.pri index 42ffff7eb..e17abfbb3 100644 --- a/src/render/renderers/opengl/textures/textures.pri +++ b/src/render/renderers/opengl/textures/textures.pri @@ -5,8 +5,5 @@ SOURCES += \ $$PWD/renderbuffer.cpp HEADERS += \ - $$PWD/gltexturemanager_p.h \ $$PWD/gltexture_p.h \ $$PWD/renderbuffer_p.h - - diff --git a/src/render/texture/qtexture.cpp b/src/render/texture/qtexture.cpp index 84a228428..7f662dfc5 100644 --- a/src/render/texture/qtexture.cpp +++ b/src/render/texture/qtexture.cpp @@ -57,7 +57,7 @@ #include #include #include -#include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/texture/texture.cpp b/src/render/texture/texture.cpp index 1414cd337..795c5844e 100644 --- a/src/render/texture/texture.cpp +++ b/src/render/texture/texture.cpp @@ -47,7 +47,7 @@ #include #include -#include +#include #include QT_BEGIN_NAMESPACE diff --git a/tests/auto/render/scene2d/tst_scene2d.cpp b/tests/auto/render/scene2d/tst_scene2d.cpp index fcb4c0908..3d943eae7 100644 --- a/tests/auto/render/scene2d/tst_scene2d.cpp +++ b/tests/auto/render/scene2d/tst_scene2d.cpp @@ -326,6 +326,7 @@ private Q_SLOTS: tri, v0, v1, v2, Qt3DRender::QPickEvent::LeftButton, Qt::LeftButton, 0, uvw) { + QSKIP("Disabled until Renderer plugin refactoring is complete"); // WHEN QVector3D uvw(1.0, 0.0f, 0.0f); Qt3DRender::QPickEventPtr ev = Qt3DRender::QPickEventPtr(PICK_TRIANGLE(0, 0, 1, 2, uvw)); diff --git a/tests/auto/render/textures/tst_textures.cpp b/tests/auto/render/textures/tst_textures.cpp index 934cc8151..12d538772 100644 --- a/tests/auto/render/textures/tst_textures.cpp +++ b/tests/auto/render/textures/tst_textures.cpp @@ -38,11 +38,11 @@ QT_WARNING_DISABLE_DEPRECATED #include #include +#include #include #include #include #include -#include #include #include @@ -242,8 +242,8 @@ private Q_SLOTS: renderer.updateTexture(bt1b); // THEN - QCOMPARE(mgrs->glTextureManager()->lookupResource(bt1a->peerId()), mgrs->glTextureManager()->lookupResource(bt1b->peerId())); - + QCOMPARE(renderer.glResourceManagers()->glTextureManager()->lookupResource(bt1a->peerId()), + renderer.glResourceManagers()->glTextureManager()->lookupResource(bt1b->peerId())); renderer.shutdown(); } @@ -278,11 +278,12 @@ private Q_SLOTS: // no 2 textures must be the same for (int i = 0; i < backend.size(); i++) for (int k = i+1; k < backend.size(); k++) - QVERIFY(mgrs->glTextureManager()->lookupResource(backend[i]->peerId()) != mgrs->glTextureManager()->lookupResource(backend[k]->peerId())); + QVERIFY(renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[i]->peerId()) != + renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[k]->peerId())); QVector glTextures; for (Qt3DRender::Render::Texture *t : backend) - glTextures.push_back(mgrs->glTextureManager()->lookupResource(t->peerId())); + glTextures.push_back(renderer.glResourceManagers()->glTextureManager()->lookupResource(t->peerId())); // some texture generators must be the same QVERIFY(glTextures[0]->textureGenerator().data() == nullptr); @@ -308,6 +309,8 @@ private Q_SLOTS: Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); renderer.setNodeManagers(mgrs.data()); + Qt3DRender::Render::GLResourceManagers *glMgrs = renderer.glResourceManagers(); + // both texture having the same sharedTextureId { // GIVEN @@ -332,8 +335,8 @@ private Q_SLOTS: renderer.updateTexture(bt2); // THEN - Qt3DRender::Render::GLTexture *glt1 = mgrs->glTextureManager()->lookupResource(bt1->peerId()); - Qt3DRender::Render::GLTexture *glt2 = mgrs->glTextureManager()->lookupResource(bt2->peerId()); + Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); + Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); QVERIFY(glt1 != glt2); QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); @@ -363,8 +366,8 @@ private Q_SLOTS: renderer.updateTexture(bt2); // THEN - Qt3DRender::Render::GLTexture *glt1 = mgrs->glTextureManager()->lookupResource(bt1->peerId()); - Qt3DRender::Render::GLTexture *glt2 = mgrs->glTextureManager()->lookupResource(bt2->peerId()); + Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); + Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); QVERIFY(glt1 != glt2); QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); @@ -396,12 +399,12 @@ private Q_SLOTS: renderer.updateTexture(backendTexture); } - Qt3DRender::QTextureImageDataGeneratorPtr idg1a = mgrs->glTextureManager()->lookupResource(backend[0]->peerId())->images()[0].generator; - Qt3DRender::QTextureImageDataGeneratorPtr idg1b = mgrs->glTextureManager()->lookupResource(backend[1]->peerId())->images()[0].generator; - Qt3DRender::QTextureImageDataGeneratorPtr idg2 = mgrs->glTextureManager()->lookupResource(backend[1]->peerId())->images()[1].generator; - Qt3DRender::QTextureGeneratorPtr tg1a = mgrs->glTextureManager()->lookupResource(backend[0]->peerId())->textureGenerator(); - Qt3DRender::QTextureGeneratorPtr tg1b = mgrs->glTextureManager()->lookupResource(backend[2]->peerId())->textureGenerator(); - Qt3DRender::QTextureGeneratorPtr tg2 = mgrs->glTextureManager()->lookupResource(backend[1]->peerId())->textureGenerator(); + Qt3DRender::QTextureImageDataGeneratorPtr idg1a = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[0]->peerId())->images()[0].generator; + Qt3DRender::QTextureImageDataGeneratorPtr idg1b = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->images()[0].generator; + Qt3DRender::QTextureImageDataGeneratorPtr idg2 = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->images()[1].generator; + Qt3DRender::QTextureGeneratorPtr tg1a = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[0]->peerId())->textureGenerator(); + Qt3DRender::QTextureGeneratorPtr tg1b = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[2]->peerId())->textureGenerator(); + Qt3DRender::QTextureGeneratorPtr tg2 = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->textureGenerator(); // THEN QVERIFY(idg1a); -- cgit v1.2.3 From 9124a61eb1c10ed3bb7251baf2f42ac4a865e514 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Wed, 7 Jun 2017 10:49:04 +0200 Subject: Introduce a GLShader class GLShader is renderer specific shader implementation for OpenGL. Shader now contains only backend information for a QShaderProgram frontend node. - Similar to the GLTexture handling, a generic adopt/abandon manager for shaders was introduced (regardless of the actually GraphicsAPIShader class). - The renderer and renderviews were adapted to the new changes. This was the last major thing preventing the modularisation of the QRenderAspect and renderers Change-Id: If671d60928b433977e9d6e5c58199827f9408a3f Task-number: QTBUG-61151 Reviewed-by: Mike Krus --- src/render/backend/apishadermanager_p.h | 224 +++++++++++++ src/render/backend/commandexecuter.cpp | 2 +- src/render/backend/managers_p.h | 15 + src/render/backend/render-backend.pri | 3 +- src/render/framegraph/setfence.cpp | 1 + src/render/frontend/qrenderaspect.cpp | 2 +- src/render/materialsystem/materialsystem.pri | 2 - src/render/materialsystem/shader.cpp | 365 +++------------------ src/render/materialsystem/shader_p.h | 96 ++---- src/render/materialsystem/shadercache.cpp | 174 ---------- src/render/materialsystem/shaderimage.cpp | 1 - .../opengl/graphicshelpers/graphicscontext.cpp | 100 +++--- .../opengl/graphicshelpers/graphicscontext_p.h | 20 +- .../opengl/graphicshelpers/submissioncontext.cpp | 24 +- .../opengl/graphicshelpers/submissioncontext_p.h | 4 +- .../opengl/managers/glresourcemanagers.cpp | 3 + .../opengl/managers/glresourcemanagers_p.h | 12 + src/render/renderers/opengl/managers/managers.pri | 1 + src/render/renderers/opengl/renderer/glshader.cpp | 316 ++++++++++++++++++ src/render/renderers/opengl/renderer/glshader_p.h | 160 +++++++++ .../opengl/renderer/openglvertexarrayobject.cpp | 4 +- .../opengl/renderer/openglvertexarrayobject_p.h | 6 +- .../renderers/opengl/renderer/rendercommand.cpp | 8 +- .../renderers/opengl/renderer/rendercommand_p.h | 5 +- src/render/renderers/opengl/renderer/renderer.cpp | 64 +++- src/render/renderers/opengl/renderer/renderer.pri | 7 +- src/render/renderers/opengl/renderer/renderer_p.h | 6 +- .../renderers/opengl/renderer/renderview.cpp | 44 ++- .../renderers/opengl/renderer/renderview_p.h | 6 +- .../render/glshadermanager/glshadermanager.pro | 12 + .../render/glshadermanager/tst_glshadermanager.cpp | 199 +++++++++++ tests/auto/render/render.pro | 2 +- tests/auto/render/renderviews/tst_renderviews.cpp | 111 +++++-- tests/auto/render/shader/tst_shader.cpp | 46 +-- tests/auto/render/shadercache/shadercache.pro | 11 - tests/auto/render/shadercache/tst_shadercache.cpp | 293 ----------------- 36 files changed, 1268 insertions(+), 1081 deletions(-) create mode 100644 src/render/backend/apishadermanager_p.h delete mode 100644 src/render/materialsystem/shadercache.cpp create mode 100644 src/render/renderers/opengl/renderer/glshader.cpp create mode 100644 src/render/renderers/opengl/renderer/glshader_p.h create mode 100644 tests/auto/render/glshadermanager/glshadermanager.pro create mode 100644 tests/auto/render/glshadermanager/tst_glshadermanager.cpp delete mode 100644 tests/auto/render/shadercache/shadercache.pro delete mode 100644 tests/auto/render/shadercache/tst_shadercache.cpp diff --git a/src/render/backend/apishadermanager_p.h b/src/render/backend/apishadermanager_p.h new file mode 100644 index 000000000..ec17b2196 --- /dev/null +++ b/src/render/backend/apishadermanager_p.h @@ -0,0 +1,224 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_APISHADERMANAGER_H +#define QT3DRENDER_RENDER_APISHADERMANAGER_H + + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Shader; + +template +class APIShaderManager +{ +public: + explicit APIShaderManager() + { + } + + ~APIShaderManager() + { + } + + QVector takeActiveResources() const + { + QReadLocker lock(&m_readWriteLock); + return m_apiShaders.keys().toVector() + m_abandonedShaders; + } + + APIShader *lookupResource(Qt3DCore::QNodeId shaderId) + { + QReadLocker lock(&m_readWriteLock); + return m_nodeIdToAPIShader.value(shaderId); + } + + // Note: automatically adopts the Shader if it needs to be created + APIShader *createOrAdoptExisting(const Shader *shader) + { + // Try to find if an APIShader that matches shader + // already exists + + { + QReadLocker readLock(&m_readWriteLock); + { + const auto end = m_apiShaders.cend(); + for (auto it = m_apiShaders.cbegin(); it != end; ++it) + if (isSameShader(it.key(), shader)) { + APIShader *apiShader = it.key(); + // Adopt if needed + readLock.unlock(); + adopt(apiShader, shader); + return apiShader; + } + } + + // Try to find if one of the scheduled for deletion APIShader + // could be reused + { + const auto end = m_abandonedShaders.end(); + for (auto it = m_abandonedShaders.begin(); it != end; ++it) + if (isSameShader(*it, shader)) { + APIShader *apiShader = *it; + // Adopt if needed + readLock.unlock(); + // Remove from list of shaders scheduled for relase + m_abandonedShaders.erase(it); + adopt(apiShader, shader); + return apiShader; + } + } + } + + // If not create one + APIShader *apiShader = create(); + adopt(apiShader, shader); + return apiShader; + } + + // Should never be called from outside code + // but left public to maintain adopt/abandon symmetry + void adopt(APIShader *apiShader, const Shader *shader) + { + QWriteLocker lock(&m_readWriteLock); + if (!m_apiShaders[apiShader].contains(shader->peerId())) { + m_apiShaders[apiShader].push_back(shader->peerId()); + m_nodeIdToAPIShader.insert(shader->peerId(), apiShader); + } + } + + void abandon(APIShader *apiShader, const Shader *shader) + { + QWriteLocker lock(&m_readWriteLock); + APIShader *storedApiShader = m_nodeIdToAPIShader.take(shader->peerId()); + Q_ASSERT(apiShader != nullptr && apiShader == storedApiShader); + + QVector &referencedShaderNodes = m_apiShaders[apiShader]; + referencedShaderNodes.removeAll(shader->peerId()); + + if (referencedShaderNodes.empty()) { + m_abandonedShaders.push_back(apiShader); + m_apiShaders.remove(apiShader); + } + } + + QVector takeAbandonned() + { + QWriteLocker lock(&m_readWriteLock); + return std::move(m_abandonedShaders); + } + + QVector takeUpdated() + { + QWriteLocker lock(&m_readWriteLock); + return std::move(m_updatedShaders); + } + + QVector shaderIdsForProgram(GLShader *glShader) const + { + QReadLocker lock(&m_readWriteLock); + return m_apiShaders.value(glShader); + } + + void purge() + { + qDeleteAll(takeAbandonned()); + } + +private: + + bool isSameShader(const APIShader *apiShader, const Shader *shaderNode) + { + const QVector nodeShaderCode = shaderNode->shaderCode(); + const QVector apiShaderCode = apiShader->shaderCode(); + + const int s = nodeShaderCode.size(); + + Q_ASSERT(s == apiShaderCode.size()); + + for (int i = 0; i < s; ++i) + if (nodeShaderCode.at(i) != apiShaderCode.at(i)) + return false; + + return true; + } + + APIShader *create() + { + APIShader *apiShader = new APIShader(); + m_updatedShaders.push_back(apiShader); + return apiShader; + } + + + QHash m_nodeIdToAPIShader; + QHash> m_apiShaders; + + QVector m_abandonedShaders; + QVector m_updatedShaders; + + mutable QReadWriteLock m_readWriteLock; +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_APISHADERMANAGER_H diff --git a/src/render/backend/commandexecuter.cpp b/src/render/backend/commandexecuter.cpp index 5ed0c970d..8e45fb924 100644 --- a/src/render/backend/commandexecuter.cpp +++ b/src/render/backend/commandexecuter.cpp @@ -349,7 +349,7 @@ void CommandExecuter::performAsynchronousCommandExecution(const QVectorcommands()) { QJsonObject commandObj; Render::NodeManagers *nodeManagers = m_renderer->nodeManagers(); - commandObj.insert(QLatin1String("shader"), backendNodeToJSon(c.m_shader, nodeManagers->shaderManager())); + commandObj.insert(QLatin1String("shader"), int(c.m_shaderId.id())); commandObj.insert(QLatin1String("vao"), double(c.m_vao.handle())); commandObj.insert(QLatin1String("instanceCount"), c.m_instanceCount); commandObj.insert(QLatin1String("geometry"), backendNodeToJSon(c.m_geometry, nodeManagers->geometryManager())); diff --git a/src/render/backend/managers_p.h b/src/render/backend/managers_p.h index 024059a30..24b161b6e 100644 --- a/src/render/backend/managers_p.h +++ b/src/render/backend/managers_p.h @@ -204,6 +204,21 @@ class ShaderManager : public Qt3DCore::QResourceManager< { public: ShaderManager() {} + + // Called in AspectThread by Shader node functor destroy + void addShaderIdToCleanup(Qt3DCore::QNodeId id) + { + m_shaderIdsToCleanup.push_back(id); + } + + // Called by RenderThread in updateGLResources (locked) + QVector takeShaderIdsToCleanup() + { + return std::move(m_shaderIdsToCleanup); + } + +private: + QVector m_shaderIdsToCleanup; }; class ShaderBuilderManager : public Qt3DCore::QResourceManager< diff --git a/src/render/backend/render-backend.pri b/src/render/backend/render-backend.pri index c910adfe4..87083312f 100644 --- a/src/render/backend/render-backend.pri +++ b/src/render/backend/render-backend.pri @@ -38,7 +38,8 @@ HEADERS += \ $$PWD/visitorutils_p.h \ $$PWD/segmentsvisitor_p.h \ $$PWD/pointsvisitor_p.h \ - $$PWD/commandexecuter_p.h + $$PWD/commandexecuter_p.h \ + $$PWD/apishadermanager_p.h SOURCES += \ $$PWD/renderthread.cpp \ diff --git a/src/render/framegraph/setfence.cpp b/src/render/framegraph/setfence.cpp index b2e995b25..e0a0d8578 100644 --- a/src/render/framegraph/setfence.cpp +++ b/src/render/framegraph/setfence.cpp @@ -38,6 +38,7 @@ ****************************************************************************/ #include "setfence_p.h" +#include QT_BEGIN_NAMESPACE diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index 35a037527..d8551fd1b 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -309,7 +309,7 @@ void QRenderAspectPrivate::registerBackendTypes() q->registerBackendType(QSharedPointer >::create(m_renderer)); q->registerBackendType(QSharedPointer >::create(m_renderer)); q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); - q->registerBackendType(QSharedPointer >::create(m_renderer)); + q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers->shaderManager())); q->registerBackendType(QSharedPointer >::create(m_renderer)); q->registerBackendType(QSharedPointer::create(m_renderer, m_nodeManagers)); q->registerBackendType(QSharedPointer>::create(m_renderer)); diff --git a/src/render/materialsystem/materialsystem.pri b/src/render/materialsystem/materialsystem.pri index ae3d2f78c..50e414a8e 100644 --- a/src/render/materialsystem/materialsystem.pri +++ b/src/render/materialsystem/materialsystem.pri @@ -33,7 +33,6 @@ HEADERS += \ $$PWD/technique_p.h \ $$PWD/qgraphicsapifilter.h \ $$PWD/qgraphicsapifilter_p.h \ - $$PWD/shadercache_p.h \ $$PWD/techniquemanager_p.h SOURCES += \ @@ -58,7 +57,6 @@ SOURCES += \ $$PWD/shaderimage.cpp \ $$PWD/technique.cpp \ $$PWD/qgraphicsapifilter.cpp \ - $$PWD/shadercache.cpp \ $$PWD/techniquemanager.cpp RESOURCES += \ diff --git a/src/render/materialsystem/shader.cpp b/src/render/materialsystem/shader.cpp index 0d4b5edba..00d9d334f 100644 --- a/src/render/materialsystem/shader.cpp +++ b/src/render/materialsystem/shader.cpp @@ -50,6 +50,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -83,47 +84,23 @@ const int Shader::skinningPaletteNameId = StringToInt::lookupId(QLatin1String("s Shader::Shader() : BackendNode(ReadWrite) - , m_isLoaded(false) - , m_dna(0) - , m_oldDna(0) - , m_graphicsContext(nullptr) - , m_status(QShaderProgram::NotReady) , m_requiresFrontendSync(false) + , m_status(QShaderProgram::NotReady) + , m_dirty(false) { m_shaderCode.resize(static_cast(QShaderProgram::Compute) + 1); } Shader::~Shader() { - // TO DO: ShaderProgram is leaked as of now - // Fix that taking care that they may be shared given a same dna - if (m_graphicsContext) - QObject::disconnect(m_contextConnection); } void Shader::cleanup() { - // Remove this shader from the hash in the graphics context so - // nothing tries to use it after it has been recycled - { - QMutexLocker lock(&m_mutex); - if (m_graphicsContext) - m_graphicsContext->removeShaderProgramReference(this); - m_graphicsContext = nullptr; - QObject::disconnect(m_contextConnection); - } - QBackendNode::setEnabled(false); - m_isLoaded = false; - m_dna = 0; - m_oldDna = 0; - m_uniformsNames.clear(); - m_attributesNames.clear(); - m_uniformBlockNames.clear(); - m_uniforms.clear(); - m_attributes.clear(); - m_uniformBlocks.clear(); m_status = QShaderProgram::NotReady; + m_log.clear(); + m_dirty = false; } void Shader::syncFromFrontEnd(const QNode *frontEnd, bool firstTime) @@ -146,300 +123,21 @@ void Shader::syncFromFrontEnd(const QNode *frontEnd, bool firstTime) } } -void Shader::setGraphicsContext(GraphicsContext *context) -{ - QMutexLocker lock(&m_mutex); - m_graphicsContext = context; - if (m_graphicsContext) { - m_contextConnection = QObject::connect(m_graphicsContext->openGLContext(), - &QOpenGLContext::aboutToBeDestroyed, - [this] { setGraphicsContext(nullptr); }); - } -} - -GraphicsContext *Shader::graphicsContext() -{ - QMutexLocker lock(&m_mutex); - return m_graphicsContext; -} - -QVector Shader::uniformsNames() const -{ - return m_uniformsNames; -} - -QVector Shader::attributesNames() const -{ - return m_attributesNames; -} - -QVector Shader::uniformBlockNames() const -{ - return m_uniformBlockNames; -} - -QVector Shader::storageBlockNames() const -{ - return m_shaderStorageBlockNames; -} - -QVector Shader::shaderCode() const -{ - return m_shaderCode; -} - void Shader::setShaderCode(QShaderProgram::ShaderType type, const QByteArray &code) { if (code == m_shaderCode[type]) return; m_shaderCode[type] = code; - m_isLoaded = false; - m_status = QShaderProgram::NotReady; - updateDNA(); m_requiresFrontendSync = true; + m_dirty = true; + setStatus(QShaderProgram::NotReady); markDirty(AbstractRenderer::ShadersDirty); } -QHash Shader::activeUniformsForUniformBlock(int blockIndex) const -{ - return m_uniformBlockIndexToShaderUniforms.value(blockIndex); -} - -ShaderUniformBlock Shader::uniformBlockForBlockIndex(int blockIndex) -{ - for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { - if (m_uniformBlocks[i].m_index == blockIndex) { - return m_uniformBlocks[i]; - } - } - return ShaderUniformBlock(); -} - -ShaderUniformBlock Shader::uniformBlockForBlockNameId(int blockNameId) -{ - for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { - if (m_uniformBlocks[i].m_nameId == blockNameId) { - return m_uniformBlocks[i]; - } - } - return ShaderUniformBlock(); -} - -ShaderUniformBlock Shader::uniformBlockForBlockName(const QString &blockName) -{ - for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { - if (m_uniformBlocks[i].m_name == blockName) { - return m_uniformBlocks[i]; - } - } - return ShaderUniformBlock(); -} - -ShaderStorageBlock Shader::storageBlockForBlockIndex(int blockIndex) -{ - for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { - if (m_shaderStorageBlocks[i].m_index == blockIndex) - return m_shaderStorageBlocks[i]; - } - return ShaderStorageBlock(); -} - -ShaderStorageBlock Shader::storageBlockForBlockNameId(int blockNameId) -{ - for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { - if (m_shaderStorageBlocks[i].m_nameId == blockNameId) - return m_shaderStorageBlocks[i]; - } - return ShaderStorageBlock(); -} - -ShaderStorageBlock Shader::storageBlockForBlockName(const QString &blockName) -{ - for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { - if (m_shaderStorageBlocks[i].m_name == blockName) - return m_shaderStorageBlocks[i]; - } - return ShaderStorageBlock(); -} - -void Shader::prepareUniforms(ShaderParameterPack &pack) -{ - const PackUniformHash &values = pack.uniforms(); - - auto it = values.keys.cbegin(); - const auto end = values.keys.cend(); - - while (it != end) { - // Find if there's a uniform with the same name id - for (const ShaderUniform &uniform : qAsConst(m_uniforms)) { - if (uniform.m_nameId == *it) { - pack.setSubmissionUniform(uniform); - break; - } - } - ++it; - } -} - -void Shader::setFragOutputs(const QHash &fragOutputs) -{ - { - QMutexLocker lock(&m_mutex); - m_fragOutputs = fragOutputs; - } - updateDNA(); -} - -const QHash Shader::fragOutputs() const -{ - QMutexLocker lock(&m_mutex); - return m_fragOutputs; -} - -void Shader::updateDNA() -{ - m_oldDna = m_dna; - uint codeHash = qHash(m_shaderCode[QShaderProgram::Vertex] - + m_shaderCode[QShaderProgram::TessellationControl] - + m_shaderCode[QShaderProgram::TessellationEvaluation] - + m_shaderCode[QShaderProgram::Geometry] - + m_shaderCode[QShaderProgram::Fragment] - + m_shaderCode[QShaderProgram::Compute]); - - QMutexLocker locker(&m_mutex); - uint attachmentHash = 0; - QHash::const_iterator it = m_fragOutputs.cbegin(); - QHash::const_iterator end = m_fragOutputs.cend(); - while (it != end) { - attachmentHash += ::qHash(it.value()) + ::qHash(it.key()); - ++it; - } - const ProgramDNA newDNA = codeHash + attachmentHash; - - // Remove reference to shader based on DNA in the ShaderCache - // In turn this will allow to purge the shader program if no other - // Shader backend node references it - // Note: the purge is actually happening occasionally in GraphicsContext::beginDrawing - if (m_graphicsContext && newDNA != m_oldDna) - m_graphicsContext->removeShaderProgramReference(this); - - m_dna = newDNA; -} - -void Shader::initializeUniforms(const QVector &uniformsDescription) -{ - m_uniforms = uniformsDescription; - m_uniformsNames.resize(uniformsDescription.size()); - m_uniformsNamesIds.reserve(uniformsDescription.size()); - m_standardUniformNamesIds.reserve(5); - QHash activeUniformsInDefaultBlock; - - static const QVector standardUniformNameIds = { - modelMatrixNameId, - viewMatrixNameId, - projectionMatrixNameId, - modelViewMatrixNameId, - viewProjectionMatrixNameId, - modelViewProjectionNameId, - mvpNameId, - inverseModelMatrixNameId, - inverseViewMatrixNameId, - inverseProjectionMatrixNameId, - inverseModelViewNameId, - inverseViewProjectionMatrixNameId, - inverseModelViewProjectionNameId, - modelNormalMatrixNameId, - modelViewNormalNameId, - viewportMatrixNameId, - inverseViewportMatrixNameId, - aspectRatioNameId, - exposureNameId, - gammaNameId, - timeNameId, - eyePositionNameId, - skinningPaletteNameId, - }; - - for (int i = 0, m = uniformsDescription.size(); i < m; i++) { - m_uniformsNames[i] = m_uniforms[i].m_name; - const int nameId = StringToInt::lookupId(m_uniformsNames[i]); - m_uniforms[i].m_nameId = nameId; - - // Is the uniform a Qt3D "Standard" uniform or a user defined one? - if (standardUniformNameIds.contains(nameId)) - m_standardUniformNamesIds.push_back(nameId); - else - m_uniformsNamesIds.push_back(nameId); - - if (uniformsDescription[i].m_blockIndex == -1) { // Uniform is in default block - qCDebug(Shaders) << "Active Uniform in Default Block " << uniformsDescription[i].m_name << uniformsDescription[i].m_blockIndex; - activeUniformsInDefaultBlock.insert(uniformsDescription[i].m_name, uniformsDescription[i]); - } - } - m_uniformBlockIndexToShaderUniforms.insert(-1, activeUniformsInDefaultBlock); -} - -void Shader::initializeAttributes(const QVector &attributesDescription) -{ - m_attributes = attributesDescription; - m_attributesNames.resize(attributesDescription.size()); - m_attributeNamesIds.resize(attributesDescription.size()); - for (int i = 0, m = attributesDescription.size(); i < m; i++) { - m_attributesNames[i] = attributesDescription[i].m_name; - m_attributes[i].m_nameId = StringToInt::lookupId(m_attributesNames[i]); - m_attributeNamesIds[i] = m_attributes[i].m_nameId; - qCDebug(Shaders) << "Active Attribute " << attributesDescription[i].m_name; - } -} - -void Shader::initializeUniformBlocks(const QVector &uniformBlockDescription) -{ - m_uniformBlocks = uniformBlockDescription; - m_uniformBlockNames.resize(uniformBlockDescription.size()); - m_uniformBlockNamesIds.resize(uniformBlockDescription.size()); - for (int i = 0, m = uniformBlockDescription.size(); i < m; ++i) { - m_uniformBlockNames[i] = m_uniformBlocks[i].m_name; - m_uniformBlockNamesIds[i] = StringToInt::lookupId(m_uniformBlockNames[i]); - m_uniformBlocks[i].m_nameId = m_uniformBlockNamesIds[i]; - qCDebug(Shaders) << "Initializing Uniform Block {" << m_uniformBlockNames[i] << "}"; - - // Find all active uniforms for the shader block - QVector::const_iterator uniformsIt = m_uniforms.cbegin(); - const QVector::const_iterator uniformsEnd = m_uniforms.cend(); - - QVector::const_iterator uniformNamesIt = m_uniformsNames.cbegin(); - const QVector::const_iterator uniformNamesEnd = m_attributesNames.cend(); - - QHash activeUniformsInBlock; - - while (uniformsIt != uniformsEnd && uniformNamesIt != uniformNamesEnd) { - if (uniformsIt->m_blockIndex == uniformBlockDescription[i].m_index) { - QString uniformName = *uniformNamesIt; - if (!m_uniformBlockNames[i].isEmpty() && !uniformName.startsWith(m_uniformBlockNames[i])) - uniformName = m_uniformBlockNames[i] + QLatin1Char('.') + *uniformNamesIt; - activeUniformsInBlock.insert(uniformName, *uniformsIt); - qCDebug(Shaders) << "Active Uniform Block " << uniformName << " in block " << m_uniformBlockNames[i] << " at index " << uniformsIt->m_blockIndex; - } - ++uniformsIt; - ++uniformNamesIt; - } - m_uniformBlockIndexToShaderUniforms.insert(uniformBlockDescription[i].m_index, activeUniformsInBlock); - } -} - -void Shader::initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription) +QVector Shader::shaderCode() const { - m_shaderStorageBlocks = shaderStorageBlockDescription; - m_shaderStorageBlockNames.resize(shaderStorageBlockDescription.size()); - m_shaderStorageBlockNamesIds.resize(shaderStorageBlockDescription.size()); - - for (int i = 0, m = shaderStorageBlockDescription.size(); i < m; ++i) { - m_shaderStorageBlockNames[i] = m_shaderStorageBlocks[i].m_name; - m_shaderStorageBlockNamesIds[i] = StringToInt::lookupId(m_shaderStorageBlockNames[i]); - m_shaderStorageBlocks[i].m_nameId =m_shaderStorageBlockNamesIds[i]; - qCDebug(Shaders) << "Initializing Shader Storage Block {" << m_shaderStorageBlockNames[i] << "}"; - } + return m_shaderCode; } /*! @@ -449,26 +147,11 @@ void Shader::initializeShaderStorageBlocks(const QVector &sh */ void Shader::initializeFromReference(const Shader &other) { - Q_ASSERT(m_dna == other.m_dna); - m_uniformsNamesIds = other.m_uniformsNamesIds; - m_standardUniformNamesIds = other.m_standardUniformNamesIds; - m_uniformsNames = other.m_uniformsNames; - m_uniforms = other.m_uniforms; - m_attributesNames = other.m_attributesNames; - m_attributeNamesIds = other.m_attributeNamesIds; - m_attributes = other.m_attributes; - m_uniformBlockNamesIds = other.m_uniformBlockNamesIds; - m_uniformBlockNames = other.m_uniformBlockNames; - m_uniformBlocks = other.m_uniformBlocks; - m_uniformBlockIndexToShaderUniforms = other.m_uniformBlockIndexToShaderUniforms; - m_fragOutputs = other.m_fragOutputs; - m_shaderStorageBlockNamesIds = other.m_shaderStorageBlockNamesIds; - m_shaderStorageBlockNames = other.m_shaderStorageBlockNames; - m_shaderStorageBlocks = other.m_shaderStorageBlocks; - m_isLoaded = other.m_isLoaded; m_status = other.m_status; m_log = other.m_log; m_requiresFrontendSync = true; + setStatus(other.status()); + setLog(other.log()); } void Shader::setLog(const QString &log) @@ -483,6 +166,32 @@ void Shader::setStatus(QShaderProgram::Status status) m_requiresFrontendSync = true; } +ShaderFunctor::ShaderFunctor(AbstractRenderer *renderer, ShaderManager *manager) + : m_renderer(renderer) + , m_shaderManager(manager) +{ +} + +QBackendNode *ShaderFunctor::create(const QNodeCreatedChangeBasePtr &change) const +{ + Shader *backend = m_shaderManager->getOrCreateResource(change->subjectId()); + backend->setRenderer(m_renderer); + return backend; +} + +QBackendNode *ShaderFunctor::get(QNodeId id) const +{ + return m_shaderManager->lookupResource(id); +} + +void ShaderFunctor::destroy(QNodeId id) const +{ + m_shaderManager->addShaderIdToCleanup(id); + // We only add ourselves to the dirty list + // The actual removal needs to be performed after we have + // destroyed the associated APIShader in the RenderThread +} + } // namespace Render } // namespace Qt3DRender diff --git a/src/render/materialsystem/shader_p.h b/src/render/materialsystem/shader_p.h index 4c5bc5ea1..8b1941d2c 100644 --- a/src/render/materialsystem/shader_p.h +++ b/src/render/materialsystem/shader_p.h @@ -52,11 +52,7 @@ // #include -#include -#include #include -#include -#include #include QT_BEGIN_NAMESPACE @@ -70,8 +66,6 @@ namespace Render { class ShaderManager; class AttachmentPack; -typedef uint ProgramDNA; - class Q_AUTOTEST_EXPORT Shader : public BackendNode { public: @@ -104,92 +98,26 @@ public: void cleanup(); - void setGraphicsContext(GraphicsContext *context); - GraphicsContext *graphicsContext(); - - void prepareUniforms(ShaderParameterPack &pack); - void setFragOutputs(const QHash &fragOutputs); - const QHash fragOutputs() const; - - inline QVector uniformsNamesIds() const { return m_uniformsNamesIds; } - inline QVector standardUniformNameIds() const { return m_standardUniformNamesIds; } - inline QVector uniformBlockNamesIds() const { return m_uniformBlockNamesIds; } - inline QVector storageBlockNamesIds() const { return m_shaderStorageBlockNamesIds; } - inline QVector attributeNamesIds() const { return m_attributeNamesIds; } - - QVector uniformsNames() const; - QVector attributesNames() const; - QVector uniformBlockNames() const; - QVector storageBlockNames() const; QVector shaderCode() const; void setShaderCode(QShaderProgram::ShaderType type, const QByteArray &code); - void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) override; - bool isLoaded() const { QMutexLocker lock(&m_mutex); return m_isLoaded; } - void setLoaded(bool loaded) { QMutexLocker lock(&m_mutex); m_isLoaded = loaded; } - ProgramDNA dna() const Q_DECL_NOTHROW { return m_dna; } - - inline QVector uniforms() const { return m_uniforms; } - inline QVector attributes() const { return m_attributes; } - inline QVector uniformBlocks() const { return m_uniformBlocks; } - inline QVector storageBlocks() const { return m_shaderStorageBlocks; } - - QHash activeUniformsForUniformBlock(int blockIndex) const; - - ShaderUniformBlock uniformBlockForBlockIndex(int blockNameId); - ShaderUniformBlock uniformBlockForBlockNameId(int blockIndex); - ShaderUniformBlock uniformBlockForBlockName(const QString &blockName); - - ShaderStorageBlock storageBlockForBlockIndex(int blockIndex); - ShaderStorageBlock storageBlockForBlockNameId(int blockNameId); - ShaderStorageBlock storageBlockForBlockName(const QString &blockName); + void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime); inline QString log() const { return m_log; } inline QShaderProgram::Status status() const { return m_status; } + bool isDirty() const { return m_dirty; } + void unsetDirty() { m_dirty = false; } inline bool requiresFrontendSync() const { return m_requiresFrontendSync; } inline void unsetRequiresFrontendSync() { m_requiresFrontendSync = false; } private: - QVector m_uniformsNames; - QVector m_uniformsNamesIds; - QVector m_standardUniformNamesIds; - QVector m_uniforms; - - QVector m_attributesNames; - QVector m_attributeNamesIds; - QVector m_attributes; - - QVector m_uniformBlockNames; - QVector m_uniformBlockNamesIds; - QVector m_uniformBlocks; - QHash > m_uniformBlockIndexToShaderUniforms; - - QVector m_shaderStorageBlockNames; - QVector m_shaderStorageBlockNamesIds; - QVector m_shaderStorageBlocks; - - QHash m_fragOutputs; - QVector m_shaderCode; - bool m_isLoaded; - ProgramDNA m_dna; - ProgramDNA m_oldDna; - mutable QMutex m_mutex; - GraphicsContext *m_graphicsContext; - QMetaObject::Connection m_contextConnection; QString m_log; QShaderProgram::Status m_status; bool m_requiresFrontendSync; - - void updateDNA(); - - // Private so that only GraphicContext can call it - void initializeUniforms(const QVector &uniformsDescription); - void initializeAttributes(const QVector &attributesDescription); - void initializeUniformBlocks(const QVector &uniformBlockDescription); - void initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription); + bool m_dirty; void initializeFromReference(const Shader &other); void setLog(const QString &log); @@ -202,11 +130,25 @@ private: inline QDebug operator<<(QDebug dbg, const Shader &shader) { QDebugStateSaver saver(dbg); - dbg << "QNodeId =" << shader.peerId() << "dna =" << shader.dna() << Qt::endl; + dbg << "QNodeId =" << shader.peerId() << Qt::endl; return dbg; } #endif +class ShaderFunctor : public Qt3DCore::QBackendNodeMapper +{ +public: + explicit ShaderFunctor(AbstractRenderer *renderer, + ShaderManager *manager); + Qt3DCore::QBackendNode *create(const Qt3DCore::QNodeCreatedChangeBasePtr &change) const final; + Qt3DCore::QBackendNode *get(Qt3DCore::QNodeId id) const final; + void destroy(Qt3DCore::QNodeId id) const final; + +private: + AbstractRenderer *m_renderer; + ShaderManager *m_shaderManager; +}; + } // namespace Render } // namespace Qt3DRender diff --git a/src/render/materialsystem/shadercache.cpp b/src/render/materialsystem/shadercache.cpp deleted file mode 100644 index 78193755f..000000000 --- a/src/render/materialsystem/shadercache.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL3$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see http://www.qt.io/terms-conditions. For further -** information use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPLv3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or later as published by the Free -** Software Foundation and appearing in the file LICENSE.GPL included in -** the packaging of this file. Please review the following information to -** ensure the GNU General Public License version 2.0 requirements will be -** met: http://www.gnu.org/licenses/gpl-2.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "shadercache_p.h" - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -/*! - * \internal - * - * Destroys the ShaderCache and deletes all cached QOpenGLShaderPrograms - */ -ShaderCache::~ShaderCache() -{ - qDeleteAll(m_programHash); -} - -/*! - * \internal - * - * Looks up the QOpenGLShaderProgram corresponding to \a dna. Also checks to see if the cache - * contains a reference to this shader program from the Shader with peerId of \a shaderPeerId. - * If there is no existing reference for \a shaderPeerId, one is recorded. - * - * \return A pointer to the shader program if it is cached, nullptr otherwise - */ -QOpenGLShaderProgram *ShaderCache::getShaderProgramAndAddRef(ProgramDNA dna, Qt3DCore::QNodeId shaderPeerId, bool *wasPresent) -{ - auto shaderProgram = m_programHash.constFind(dna); - - // Some callers may wish to differentiate between a result of null due to - // not having anything in the cache and a result of null due to the cache - // containing a program the shaders of which failed to compile. - if (wasPresent) - *wasPresent = shaderProgram != m_programHash.constEnd(); - - if (shaderProgram != m_programHash.constEnd()) { - // Ensure we store the fact that shaderPeerId references this shader - QMutexLocker lock(&m_refsMutex); - QVector &programRefs = m_programRefs[dna]; - auto it = std::lower_bound(programRefs.begin(), programRefs.end(), shaderPeerId); - if (*it != shaderPeerId) - programRefs.insert(it, shaderPeerId); - - m_pendingRemoval.removeOne(dna); - - return *shaderProgram; - } - - return nullptr; -} - -/*! - * \internal - * - * Inserts the \a program in the cache indexed by \a dna and adds a reference to it from - * \a shaderPeerId. The cache takes ownership of the \a program. - */ -void ShaderCache::insert(ProgramDNA dna, Qt3DCore::QNodeId shaderPeerId, QOpenGLShaderProgram *program) -{ - Q_ASSERT(!m_programHash.contains(dna)); - m_programHash.insert(dna, program); - QMutexLocker lock(&m_refsMutex); - Q_ASSERT(!m_programRefs.contains(dna)); - QVector programRefs; - programRefs.push_back(shaderPeerId); - m_programRefs.insert(dna, programRefs); -} - -/*! - * \internal - * - * Removes a reference to the shader program indexed by \a dna from the Shader with peerId of - * \a shaderPeerId. If this was the last reference, the dna and corresponding shader are added - * to a list of items to be removed by the next call to purge. - */ -void ShaderCache::removeRef(ProgramDNA dna, Qt3DCore::QNodeId shaderPeerId) -{ - QMutexLocker lock(&m_refsMutex); - auto it = m_programRefs.find(dna); - if (it != m_programRefs.end()) { - QVector &programRefs = it.value(); - programRefs.removeOne(shaderPeerId); - if (programRefs.isEmpty()) - m_pendingRemoval.append(dna); - } -} - -/*! - * \internal - * - * Iterates through a list of program dna's and checks to see if they still have no references - * from Shaders. If so, the dna and corresponding QOpenGLShaderProgram are removed from the cache. - */ -void ShaderCache::purge() -{ - QMutexLocker lock(&m_refsMutex); - for (const ProgramDNA &dna : qAsConst(m_pendingRemoval)) { - QVector &programRefs = m_programRefs[dna]; - if (programRefs.isEmpty()) { - delete m_programHash.take(dna); - m_programRefs.remove(dna); - } - } - - m_pendingRemoval.clear(); -} - -/*! - * \internal - * - * Deletes all cached shader programs and removes any references - */ -void ShaderCache::clear() -{ - QMutexLocker lock(&m_refsMutex); - qDeleteAll(m_programHash); - m_programHash.clear(); - m_programRefs.clear(); - m_pendingRemoval.clear(); -} - -QOpenGLShaderProgram *ShaderCache::getShaderProgramForDNA(ProgramDNA dna) const -{ - return m_programHash.value(dna, nullptr); -} - -QVector ShaderCache::shaderIdsForProgram(ProgramDNA dna) const -{ - return m_programRefs.value(dna); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/materialsystem/shaderimage.cpp b/src/render/materialsystem/shaderimage.cpp index 65a4cf761..59a06ca9c 100644 --- a/src/render/materialsystem/shaderimage.cpp +++ b/src/render/materialsystem/shaderimage.cpp @@ -103,7 +103,6 @@ void ShaderImage::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTi m_format = node->format(); markDirty(AbstractRenderer::ParameterDirty); } - if (node->access() != m_access) { m_access = node->access(); markDirty(AbstractRenderer::ParameterDirty); diff --git a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp b/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp index 9e5b3e158..25543bb19 100644 --- a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp +++ b/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp @@ -60,6 +60,7 @@ #include #include #include +#include #include #if !defined(QT_OPENGL_ES_2) @@ -133,7 +134,6 @@ GraphicsContext::GraphicsContext() , m_defaultFBO(0) , m_gl(nullptr) , m_glHelper(nullptr) - , m_shaderCache(nullptr) , m_debugLogger(nullptr) , m_currentVAO(nullptr) { @@ -153,7 +153,7 @@ void GraphicsContext::initialize() { m_initialized = true; - Q_ASSERT(m_gl && m_shaderCache); + Q_ASSERT(m_gl); m_gl->functions()->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &m_maxTextureUnits); qCDebug(Backend) << "context supports" << m_maxTextureUnits << "texture units"; @@ -231,12 +231,13 @@ void GraphicsContext::doneCurrent() } // Called by GL Command Thread -QOpenGLShaderProgram *GraphicsContext::createShaderProgram(Shader *shaderNode) +GraphicsContext::ShaderCreationInfo GraphicsContext::createShaderProgram(GLShader *shader) { - QScopedPointer shaderProgram(new QOpenGLShaderProgram); + QOpenGLShaderProgram *shaderProgram = shader->shaderProgram(); // Compile shaders - const auto shaderCode = shaderNode->shaderCode(); + const auto shaderCode = shader->shaderCode(); + QString logs; for (int i = QShaderProgram::Vertex; i <= QShaderProgram::Compute; ++i) { const QShaderProgram::ShaderType type = static_cast(i); @@ -251,25 +252,28 @@ QOpenGLShaderProgram *GraphicsContext::createShaderProgram(Shader *shaderNode) // Call glBindFragDataLocation and link the program // Since we are sharing shaders in the backend, we assume that if using custom // fragOutputs, they should all be the same for a given shader - bindFragOutputs(shaderProgram->programId(), shaderNode->fragOutputs()); + bindFragOutputs(shaderProgram->programId(), shader->fragOutputs()); const bool linkSucceeded = shaderProgram->link(); logs += shaderProgram->log(); - shaderNode->setLog(logs); - shaderNode->setStatus(linkSucceeded ? QShaderProgram::Ready : QShaderProgram::Error); - if (!linkSucceeded) - return nullptr; + // Perform shader introspection + introspectShaderInterface(shader); + + ShaderCreationInfo info; + info.linkSucceeded = linkSucceeded; + info.logs = logs; - // take from scoped-pointer so it doesn't get deleted - return shaderProgram.take(); + return info; } // That assumes that the shaderProgram in Shader stays the same -void GraphicsContext::introspectShaderInterface(Shader *shader, QOpenGLShaderProgram *shaderProgram) +void GraphicsContext::introspectShaderInterface(GLShader *shader) { - shader->initializeUniforms(m_glHelper->programUniformsAndLocations(shaderProgram->programId())); - shader->initializeAttributes(m_glHelper->programAttributesAndLocations(shaderProgram->programId())); + QOpenGLShaderProgram *shaderProgram = shader->shaderProgram(); + GraphicsHelperInterface *glHelper = resolveHighestOpenGLFunctions(); + shader->initializeUniforms(glHelper->programUniformsAndLocations(shaderProgram->programId())); + shader->initializeAttributes(glHelper->programAttributesAndLocations(shaderProgram->programId())); if (m_glHelper->supportsFeature(GraphicsHelperInterface::UniformBufferObject)) shader->initializeUniformBlocks(m_glHelper->programUniformBlocks(shaderProgram->programId())); if (m_glHelper->supportsFeature(GraphicsHelperInterface::ShaderStorageObject)) @@ -278,51 +282,47 @@ void GraphicsContext::introspectShaderInterface(Shader *shader, QOpenGLShaderPro // Called by Renderer::updateGLResources -void GraphicsContext::loadShader(Shader *shader, ShaderManager *manager) +void GraphicsContext::loadShader(Shader *shaderNode, + ShaderManager *shaderManager, + GLShaderManager *glShaderManager) { - bool wasPresent = false; - QOpenGLShaderProgram *shaderProgram = m_shaderCache->getShaderProgramAndAddRef(shader->dna(), shader->peerId(), &wasPresent); - if (!shaderProgram && !wasPresent) { - // No matching QOpenGLShader in the cache so create one - shaderProgram = createShaderProgram(shader); + const Qt3DCore::QNodeId shaderId = shaderNode->peerId(); + GLShader *glShader = glShaderManager->lookupResource(shaderId); - // Store in cache (even when failed and shaderProgram is null) - m_shaderCache->insert(shader->dna(), shader->peerId(), shaderProgram); + // We already have a shader associated with the node + if (glShader != nullptr) { + // We need to abandon it + glShaderManager->abandon(glShader, shaderNode); } - // Ensure the Shader node knows about the program interface - if (Q_LIKELY(shaderProgram != nullptr) && !shader->isLoaded()) { - + // We create or adopt an already created glShader + glShader = glShaderManager->createOrAdoptExisting(shaderNode); + + const QVector sharedShaderIds = glShaderManager->shaderIdsForProgram(glShader); + if (sharedShaderIds.size() == 1) { + // Shader in the cache hasn't been loaded yet + glShader->setGraphicsContext(this); + glShader->setShaderCode(shaderNode->shaderCode()); + const ShaderCreationInfo loadResult = createShaderProgram(glShader); + shaderNode->setStatus(loadResult.linkSucceeded ? QShaderProgram::Ready : QShaderProgram::Error); + shaderNode->setLog(loadResult.logs); + // Loaded in the sense we tried to load it (and maybe it failed) + glShader->setLoaded(true); + } else { // Find an already loaded shader that shares the same QOpenGLShaderProgram - Shader *refShader = nullptr; - const QVector sharedShaderIds = m_shaderCache->shaderIdsForProgram(shader->dna()); for (const Qt3DCore::QNodeId sharedShaderId : sharedShaderIds) { - Shader *sharedShader = manager->lookupResource(sharedShaderId); - // Note: no need to check if shader->peerId != sharedShader->peerId - // as we are sure that this code path is executed only if !shared->isLoaded - if (sharedShader->isLoaded()) { - refShader = sharedShader; + if (sharedShaderId != shaderNode->peerId()) { + Shader *refShader = shaderManager->lookupResource(sharedShaderId); + // We only introspect once per actual OpenGL shader program + // rather than once per ShaderNode. + shaderNode->initializeFromReference(*refShader); break; } } - - // We only introspect once per actual OpenGL shader program - // rather than once per ShaderNode. - if (refShader != nullptr) - shader->initializeFromReference(*refShader); - else // Introspect and set up interface description on Shader backend node - introspectShaderInterface(shader, shaderProgram); - - shader->setGraphicsContext(this); - shader->setLoaded(true); - // Will force notifications to be sent to frontend at next frame - shader->markDirty(AbstractRenderer::ShadersDirty); } -} - -void GraphicsContext::removeShaderProgramReference(Shader *shaderNode) -{ - m_shaderCache->removeRef(shaderNode->dna(), shaderNode->peerId()); + shaderNode->unsetDirty(); + // Ensure we will rebuilt material caches + shaderNode->markDirty(AbstractRenderer::AllDirty); } void GraphicsContext::activateDrawBuffers(const AttachmentPack &attachments) diff --git a/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h b/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h index b4f589e71..d3f3615d5 100644 --- a/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h +++ b/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h @@ -68,7 +68,6 @@ #include #include #include -#include #include #include #include @@ -89,6 +88,8 @@ class GraphicsHelperInterface; class RenderTarget; class AttachmentPack; class ShaderManager; +class GLShader; +class GLShaderManager; typedef QPair NamedUniformLocation; @@ -98,9 +99,6 @@ public: GraphicsContext(); ~GraphicsContext(); - void setShaderCache(ShaderCache *shaderCache) { m_shaderCache = shaderCache; } - ShaderCache *shaderCache() const { return m_shaderCache; } - void setOpenGLContext(QOpenGLContext* ctx); QOpenGLContext *openGLContext() { return m_gl; } bool makeCurrent(QSurface *surface); @@ -109,10 +107,15 @@ public: bool isInitialized() const; // Shaders - QOpenGLShaderProgram *createShaderProgram(Shader *shaderNode); - void introspectShaderInterface(Shader *shader, QOpenGLShaderProgram *shaderProgram); - void loadShader(Shader* shader, ShaderManager *manager); - void removeShaderProgramReference(Shader *shaderNode); + struct ShaderCreationInfo + { + bool linkSucceeded = false; + QString logs; + }; + + ShaderCreationInfo createShaderProgram(GLShader *shaderNode); + void introspectShaderInterface(GLShader *shader); + void loadShader(Shader* shader, ShaderManager *shaderManager, GLShaderManager *glShaderManager); GLuint defaultFBO() const { return m_defaultFBO; } @@ -195,7 +198,6 @@ public: QHash m_glHelpers; GraphicsApiFilterData m_contextInfo; - ShaderCache *m_shaderCache; QScopedPointer m_debugLogger; friend class OpenGLVertexArrayObject; diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp index 3a619f361..32852217b 100644 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp +++ b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp @@ -62,6 +62,7 @@ #include #include #include +#include #include #include @@ -363,7 +364,6 @@ SubmissionContext::SubmissionContext() , m_id(nextFreeContextId()) , m_surface(nullptr) , m_activeShader(nullptr) - , m_activeShaderDNA(0) , m_renderTargetFormat(QAbstractTexture::NoFormat) , m_currClearStencilValue(0) , m_currClearDepthValue(1.f) @@ -460,17 +460,9 @@ bool SubmissionContext::beginDrawing(QSurface *surface) if (m_activeShader) { m_activeShader = nullptr; - m_activeShaderDNA = 0; } m_boundArrayBuffer = nullptr; - - static int callCount = 0; - ++callCount; - const int shaderPurgePeriod = 600; - if (callCount % shaderPurgePeriod == 0) - m_shaderCache->purge(); - return true; } @@ -766,7 +758,6 @@ void SubmissionContext::setViewport(const QRectF &viewport, const QSize &surface void SubmissionContext::releaseOpenGL() { - m_shaderCache->clear(); m_renderBufferHash.clear(); // Stop and destroy the OpenGL logger @@ -779,27 +770,25 @@ void SubmissionContext::releaseOpenGL() // The OpenGLContext is not current on any surface at this point void SubmissionContext::setOpenGLContext(QOpenGLContext* ctx) { - Q_ASSERT(ctx && m_shaderCache); + Q_ASSERT(ctx); releaseOpenGL(); m_gl = ctx; } // Called only from RenderThread -bool SubmissionContext::activateShader(ProgramDNA shaderDNA) +bool SubmissionContext::activateShader(GLShader *shader) { - if (shaderDNA != m_activeShaderDNA) { + if (shader->shaderProgram() != m_activeShader) { // Ensure material uniforms are re-applied m_material = nullptr; - m_activeShader = m_shaderCache->getShaderProgramForDNA(shaderDNA); + m_activeShader = shader->shaderProgram(); if (Q_LIKELY(m_activeShader != nullptr)) { m_activeShader->bind(); - m_activeShaderDNA = shaderDNA; } else { m_glHelper->useProgram(0); - qCWarning(Backend) << "No shader program found for DNA"; - m_activeShaderDNA = 0; + qWarning() << "No shader program found"; return false; } } @@ -1334,6 +1323,7 @@ void SubmissionContext::specifyAttribute(const Attribute *attribute, Q_UNREACHABLE(); } + Q_ASSERT(!glBufferHandle.isNull()); VAOVertexAttribute attr; attr.bufferHandle = glBufferHandle; attr.attributeType = attributeType; diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h b/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h index a8700dd3a..d2121a3b7 100644 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h +++ b/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h @@ -60,7 +60,6 @@ #include #include #include -#include #include QT_BEGIN_NAMESPACE @@ -105,7 +104,7 @@ public: QRectF viewport() const { return m_viewport; } // Shaders - bool activateShader(ProgramDNA shaderDNA); + bool activateShader(GLShader *shader); QOpenGLShaderProgram *activeShader() const { return m_activeShader; } // FBO @@ -183,7 +182,6 @@ private: QSize m_surfaceSize; QOpenGLShaderProgram *m_activeShader; - ProgramDNA m_activeShaderDNA; QHash m_renderBufferHash; QHash m_renderTargets; diff --git a/src/render/renderers/opengl/managers/glresourcemanagers.cpp b/src/render/renderers/opengl/managers/glresourcemanagers.cpp index e3be4c7af..2b1b87925 100644 --- a/src/render/renderers/opengl/managers/glresourcemanagers.cpp +++ b/src/render/renderers/opengl/managers/glresourcemanagers.cpp @@ -38,6 +38,7 @@ ****************************************************************************/ #include "glresourcemanagers_p.h" +#include #include QT_BEGIN_NAMESPACE @@ -49,6 +50,7 @@ namespace Render { GLResourceManagers::GLResourceManagers() : m_glBufferManager(new GLBufferManager()) + , m_glShaderManager(new GLShaderManager()) , m_glTextureManager(new GLTextureManager()) , m_glFenceManager(new GLFenceManager()) , m_vaoManager(new VAOManager()) @@ -60,6 +62,7 @@ GLResourceManagers::~GLResourceManagers() delete m_vaoManager; delete m_glFenceManager; delete m_glTextureManager; + delete m_glShaderManager; delete m_glBufferManager; } diff --git a/src/render/renderers/opengl/managers/glresourcemanagers_p.h b/src/render/renderers/opengl/managers/glresourcemanagers_p.h index a2db09316..8c4c46bca 100644 --- a/src/render/renderers/opengl/managers/glresourcemanagers_p.h +++ b/src/render/renderers/opengl/managers/glresourcemanagers_p.h @@ -57,6 +57,8 @@ #include #include #include +#include +#include QT_BEGIN_NAMESPACE @@ -93,6 +95,14 @@ public: QHash texNodeIdForGLTexture; }; +class Q_AUTOTEST_EXPORT GLShaderManager : public APIShaderManager +{ +public: + explicit GLShaderManager() + : APIShaderManager() + {} +}; + class Q_AUTOTEST_EXPORT GLResourceManagers { @@ -101,12 +111,14 @@ public: ~GLResourceManagers(); inline VAOManager *vaoManager() const noexcept { return m_vaoManager; } + inline GLShaderManager *glShaderManager() const noexcept { return m_glShaderManager; } inline GLTextureManager *glTextureManager() const noexcept { return m_glTextureManager; } inline GLBufferManager *glBufferManager() const noexcept { return m_glBufferManager; } inline GLFenceManager *glFenceManager() const noexcept { return m_glFenceManager; } private: GLBufferManager *m_glBufferManager; + GLShaderManager *m_glShaderManager; GLTextureManager *m_glTextureManager; GLFenceManager *m_glFenceManager; VAOManager *m_vaoManager; diff --git a/src/render/renderers/opengl/managers/managers.pri b/src/render/renderers/opengl/managers/managers.pri index 97a4c2c45..56a0732b1 100644 --- a/src/render/renderers/opengl/managers/managers.pri +++ b/src/render/renderers/opengl/managers/managers.pri @@ -3,6 +3,7 @@ INCLUDEPATH += $$PWD HEADERS += \ $$PWD/gl_handle_types_p.h \ $$PWD/glresourcemanagers_p.h + $$PWD/glshadermanager_p.h \ SOURCES += \ $$PWD/glresourcemanagers.cpp diff --git a/src/render/renderers/opengl/renderer/glshader.cpp b/src/render/renderers/opengl/renderer/glshader.cpp new file mode 100644 index 000000000..a6f118d65 --- /dev/null +++ b/src/render/renderers/opengl/renderer/glshader.cpp @@ -0,0 +1,316 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glshader_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +GLShader::GLShader() + : m_isLoaded(false) + , m_graphicsContext(nullptr) +{ + m_shaderCode.resize(static_cast(QShaderProgram::Compute) + 1); +} + +void GLShader::setGraphicsContext(GraphicsContext *context) +{ + QMutexLocker lock(&m_mutex); + m_graphicsContext = context; + if (m_graphicsContext) { + m_contextConnection = QObject::connect(m_graphicsContext->openGLContext(), + &QOpenGLContext::aboutToBeDestroyed, + [this] { setGraphicsContext(nullptr); }); + } +} + +GraphicsContext *GLShader::graphicsContext() +{ + QMutexLocker lock(&m_mutex); + return m_graphicsContext; +} + + +QVector GLShader::uniformsNames() const +{ + return m_uniformsNames; +} + +QVector GLShader::attributesNames() const +{ + return m_attributesNames; +} + +QVector GLShader::uniformBlockNames() const +{ + return m_uniformBlockNames; +} + +QVector GLShader::storageBlockNames() const +{ + return m_shaderStorageBlockNames; +} + +QVector GLShader::shaderCode() const +{ + return m_shaderCode; +} + +QHash GLShader::activeUniformsForUniformBlock(int blockIndex) const +{ + return m_uniformBlockIndexToShaderUniforms.value(blockIndex); +} + +ShaderUniformBlock GLShader::uniformBlockForBlockIndex(int blockIndex) +{ + for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { + if (m_uniformBlocks[i].m_index == blockIndex) { + return m_uniformBlocks[i]; + } + } + return ShaderUniformBlock(); +} + +ShaderUniformBlock GLShader::uniformBlockForBlockNameId(int blockNameId) +{ + for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { + if (m_uniformBlocks[i].m_nameId == blockNameId) { + return m_uniformBlocks[i]; + } + } + return ShaderUniformBlock(); +} + +ShaderUniformBlock GLShader::uniformBlockForBlockName(const QString &blockName) +{ + for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { + if (m_uniformBlocks[i].m_name == blockName) { + return m_uniformBlocks[i]; + } + } + return ShaderUniformBlock(); +} + +ShaderStorageBlock GLShader::storageBlockForBlockIndex(int blockIndex) +{ + for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { + if (m_shaderStorageBlocks[i].m_index == blockIndex) + return m_shaderStorageBlocks[i]; + } + return ShaderStorageBlock(); +} + +ShaderStorageBlock GLShader::storageBlockForBlockNameId(int blockNameId) +{ + for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { + if (m_shaderStorageBlocks[i].m_nameId == blockNameId) + return m_shaderStorageBlocks[i]; + } + return ShaderStorageBlock(); +} + +ShaderStorageBlock GLShader::storageBlockForBlockName(const QString &blockName) +{ + for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { + if (m_shaderStorageBlocks[i].m_name == blockName) + return m_shaderStorageBlocks[i]; + } + return ShaderStorageBlock(); +} + +void GLShader::prepareUniforms(ShaderParameterPack &pack) +{ + const PackUniformHash &values = pack.uniforms(); + + auto it = values.keys.cbegin(); + const auto end = values.keys.cend(); + + while (it != end) { + // Find if there's a uniform with the same name id + for (const ShaderUniform &uniform : qAsConst(m_uniforms)) { + if (uniform.m_nameId == *it) { + pack.setSubmissionUniform(uniform); + break; + } + } + ++it; + } +} + +void GLShader::setFragOutputs(const QHash &fragOutputs) +{ + { + QMutexLocker lock(&m_mutex); + m_fragOutputs = fragOutputs; + } +// updateDNA(); +} + +const QHash GLShader::fragOutputs() const +{ + QMutexLocker lock(&m_mutex); + return m_fragOutputs; +} + +void GLShader::initializeUniforms(const QVector &uniformsDescription) +{ + m_uniforms = uniformsDescription; + m_uniformsNames.resize(uniformsDescription.size()); + m_uniformsNamesIds.reserve(uniformsDescription.size()); + m_standardUniformNamesIds.reserve(5); + QHash activeUniformsInDefaultBlock; + + static const QVector standardUniformNameIds = { + Shader::modelMatrixNameId, + Shader::viewMatrixNameId, + Shader::projectionMatrixNameId, + Shader::modelViewMatrixNameId, + Shader::viewProjectionMatrixNameId, + Shader::modelViewProjectionNameId, + Shader::mvpNameId, + Shader::inverseModelMatrixNameId, + Shader::inverseViewMatrixNameId, + Shader::inverseProjectionMatrixNameId, + Shader::inverseModelViewNameId, + Shader::inverseViewProjectionMatrixNameId, + Shader::inverseModelViewProjectionNameId, + Shader::modelNormalMatrixNameId, + Shader::modelViewNormalNameId, + Shader::viewportMatrixNameId, + Shader::inverseViewportMatrixNameId, + Shader::aspectRatioNameId, + Shader::exposureNameId, + Shader::gammaNameId, + Shader::timeNameId, + Shader::eyePositionNameId, + Shader::skinningPaletteNameId, + }; + + for (int i = 0, m = uniformsDescription.size(); i < m; i++) { + m_uniformsNames[i] = m_uniforms[i].m_name; + const int nameId = StringToInt::lookupId(m_uniformsNames[i]); + m_uniforms[i].m_nameId = nameId; + + // Is the uniform a Qt3D "Standard" uniform or a user defined one? + if (standardUniformNameIds.contains(nameId)) + m_standardUniformNamesIds.push_back(nameId); + else + m_uniformsNamesIds.push_back(nameId); + + if (uniformsDescription[i].m_blockIndex == -1) { // Uniform is in default block + qCDebug(Shaders) << "Active Uniform in Default Block " << uniformsDescription[i].m_name << uniformsDescription[i].m_blockIndex; + activeUniformsInDefaultBlock.insert(uniformsDescription[i].m_name, uniformsDescription[i]); + } + } + m_uniformBlockIndexToShaderUniforms.insert(-1, activeUniformsInDefaultBlock); +} + +void GLShader::initializeAttributes(const QVector &attributesDescription) +{ + m_attributes = attributesDescription; + m_attributesNames.resize(attributesDescription.size()); + m_attributeNamesIds.resize(attributesDescription.size()); + for (int i = 0, m = attributesDescription.size(); i < m; i++) { + m_attributesNames[i] = attributesDescription[i].m_name; + m_attributes[i].m_nameId = StringToInt::lookupId(m_attributesNames[i]); + m_attributeNamesIds[i] = m_attributes[i].m_nameId; + qCDebug(Shaders) << "Active Attribute " << attributesDescription[i].m_name; + } +} + +void GLShader::initializeUniformBlocks(const QVector &uniformBlockDescription) +{ + m_uniformBlocks = uniformBlockDescription; + m_uniformBlockNames.resize(uniformBlockDescription.size()); + m_uniformBlockNamesIds.resize(uniformBlockDescription.size()); + for (int i = 0, m = uniformBlockDescription.size(); i < m; ++i) { + m_uniformBlockNames[i] = m_uniformBlocks[i].m_name; + m_uniformBlockNamesIds[i] = StringToInt::lookupId(m_uniformBlockNames[i]); + m_uniformBlocks[i].m_nameId = m_uniformBlockNamesIds[i]; + qCDebug(Shaders) << "Initializing Uniform Block {" << m_uniformBlockNames[i] << "}"; + + // Find all active uniforms for the shader block + QVector::const_iterator uniformsIt = m_uniforms.cbegin(); + const QVector::const_iterator uniformsEnd = m_uniforms.cend(); + + QVector::const_iterator uniformNamesIt = m_uniformsNames.cbegin(); + const QVector::const_iterator uniformNamesEnd = m_attributesNames.cend(); + + QHash activeUniformsInBlock; + + while (uniformsIt != uniformsEnd && uniformNamesIt != uniformNamesEnd) { + if (uniformsIt->m_blockIndex == uniformBlockDescription[i].m_index) { + QString uniformName = *uniformNamesIt; + if (!m_uniformBlockNames[i].isEmpty() && !uniformName.startsWith(m_uniformBlockNames[i])) + uniformName = m_uniformBlockNames[i] + QLatin1Char('.') + *uniformNamesIt; + activeUniformsInBlock.insert(uniformName, *uniformsIt); + qCDebug(Shaders) << "Active Uniform Block " << uniformName << " in block " << m_uniformBlockNames[i] << " at index " << uniformsIt->m_blockIndex; + } + ++uniformsIt; + ++uniformNamesIt; + } + m_uniformBlockIndexToShaderUniforms.insert(uniformBlockDescription[i].m_index, activeUniformsInBlock); + } +} + +void GLShader::initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription) +{ + m_shaderStorageBlocks = shaderStorageBlockDescription; + m_shaderStorageBlockNames.resize(shaderStorageBlockDescription.size()); + m_shaderStorageBlockNamesIds.resize(shaderStorageBlockDescription.size()); + + for (int i = 0, m = shaderStorageBlockDescription.size(); i < m; ++i) { + m_shaderStorageBlockNames[i] = m_shaderStorageBlocks[i].m_name; + m_shaderStorageBlockNamesIds[i] = StringToInt::lookupId(m_shaderStorageBlockNames[i]); + m_shaderStorageBlocks[i].m_nameId =m_shaderStorageBlockNamesIds[i]; + qCDebug(Shaders) << "Initializing Shader Storage Block {" << m_shaderStorageBlockNames[i] << "}"; + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/glshader_p.h b/src/render/renderers/opengl/renderer/glshader_p.h new file mode 100644 index 000000000..dec085291 --- /dev/null +++ b/src/render/renderers/opengl/renderer/glshader_p.h @@ -0,0 +1,160 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GLSHADER_P_H +#define QT3DRENDER_RENDER_GLSHADER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + + +#include +#include +#include +#include + + +QT_BEGIN_NAMESPACE + +class QOpenGLShaderProgram; + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT GLShader +{ +public: + GLShader(); + + void setGraphicsContext(GraphicsContext *context); + GraphicsContext *graphicsContext(); + + bool isLoaded() const { return m_isLoaded; } + void setLoaded(bool loaded) { m_isLoaded = loaded; } + + void prepareUniforms(ShaderParameterPack &pack); + + void setFragOutputs(const QHash &fragOutputs); + const QHash fragOutputs() const; + + inline QVector uniformsNamesIds() const { return m_uniformsNamesIds; } + inline QVector standardUniformNameIds() const { return m_standardUniformNamesIds; } + inline QVector uniformBlockNamesIds() const { return m_uniformBlockNamesIds; } + inline QVector storageBlockNamesIds() const { return m_shaderStorageBlockNamesIds; } + inline QVector attributeNamesIds() const { return m_attributeNamesIds; } + + QVector uniformsNames() const; + QVector attributesNames() const; + QVector uniformBlockNames() const; + QVector storageBlockNames() const; + + inline QVector uniforms() const { return m_uniforms; } + inline QVector attributes() const { return m_attributes; } + inline QVector uniformBlocks() const { return m_uniformBlocks; } + inline QVector storageBlocks() const { return m_shaderStorageBlocks; } + + QHash activeUniformsForUniformBlock(int blockIndex) const; + + ShaderUniformBlock uniformBlockForBlockIndex(int blockNameId); + ShaderUniformBlock uniformBlockForBlockNameId(int blockIndex); + ShaderUniformBlock uniformBlockForBlockName(const QString &blockName); + + ShaderStorageBlock storageBlockForBlockIndex(int blockIndex); + ShaderStorageBlock storageBlockForBlockNameId(int blockNameId); + ShaderStorageBlock storageBlockForBlockName(const QString &blockName); + + QOpenGLShaderProgram *shaderProgram() { return &m_shader; } + + void setShaderCode(const QVector shaderCode) { m_shaderCode = shaderCode; } + QVector shaderCode() const; + +private: + bool m_isLoaded; + QOpenGLShaderProgram m_shader; + GraphicsContext *m_graphicsContext; + + QVector m_uniformsNames; + QVector m_uniformsNamesIds; + QVector m_standardUniformNamesIds; + QVector m_uniforms; + + QVector m_attributesNames; + QVector m_attributeNamesIds; + QVector m_attributes; + + QVector m_uniformBlockNames; + QVector m_uniformBlockNamesIds; + QVector m_uniformBlocks; + QHash > m_uniformBlockIndexToShaderUniforms; + + QVector m_shaderStorageBlockNames; + QVector m_shaderStorageBlockNamesIds; + QVector m_shaderStorageBlocks; + + QHash m_fragOutputs; + QVector m_shaderCode; + + // Private so that only GraphicContext can call it + void initializeUniforms(const QVector &uniformsDescription); + void initializeAttributes(const QVector &attributesDescription); + void initializeUniformBlocks(const QVector &uniformBlockDescription); + void initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription); + + friend class GraphicsContext; + + mutable QMutex m_mutex; + QMetaObject::Connection m_contextConnection; +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GLSHADER_P_H diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp b/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp index 58ce70c28..25a850a79 100644 --- a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp +++ b/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp @@ -133,7 +133,7 @@ void OpenGLVertexArrayObject::cleanup() } // called from job -bool OpenGLVertexArrayObject::isAbandoned(GeometryManager *geomMgr, ShaderManager *shaderMgr) +bool OpenGLVertexArrayObject::isAbandoned(GeometryManager *geomMgr, GLShaderManager *shaderMgr) { QMutexLocker lock(&m_mutex); @@ -141,7 +141,7 @@ bool OpenGLVertexArrayObject::isAbandoned(GeometryManager *geomMgr, ShaderManage return false; const bool geometryExists = (geomMgr->data(m_owners.first) != nullptr); - const bool shaderExists = (shaderMgr->data(m_owners.second) != nullptr); + const bool shaderExists = (shaderMgr->lookupResource(m_owners.second) != nullptr); return !geometryExists || !shaderExists; } diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h b/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h index 4896df9bf..362c699da 100644 --- a/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h +++ b/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h @@ -60,9 +60,9 @@ namespace Qt3DRender { namespace Render { class GeometryManager; -class ShaderManager; +class GLShaderManager; -typedef QPair VAOIdentifier; +typedef QPair VAOIdentifier; class OpenGLVertexArrayObject { @@ -77,7 +77,7 @@ public: void destroy(); void cleanup(); - bool isAbandoned(GeometryManager *geomMgr, ShaderManager *shaderMgr); + bool isAbandoned(GeometryManager *geomMgr, GLShaderManager *shaderMgr); QOpenGLVertexArrayObject *vao() { return m_vao.data(); } const QOpenGLVertexArrayObject *vao() const { return m_vao.data(); } diff --git a/src/render/renderers/opengl/renderer/rendercommand.cpp b/src/render/renderers/opengl/renderer/rendercommand.cpp index 072127391..c6d42fde1 100644 --- a/src/render/renderers/opengl/renderer/rendercommand.cpp +++ b/src/render/renderers/opengl/renderer/rendercommand.cpp @@ -45,10 +45,10 @@ namespace Qt3DRender { namespace Render { RenderCommand::RenderCommand() - : m_stateSet(nullptr) + : m_glShader(nullptr) + , m_stateSet(nullptr) , m_depth(0.0f) , m_changeCost(0) - , m_shaderDna(0) , m_type(RenderCommand::Draw) , m_primitiveCount(0) , m_primitiveType(QGeometryRenderer::Triangles) @@ -73,10 +73,10 @@ RenderCommand::RenderCommand() bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept { - return (a.m_vao == b.m_vao && a.m_shader == b.m_shader && a.m_material == b.m_material && + return (a.m_vao == b.m_vao && a.m_glShader == b.m_glShader && a.m_material == b.m_material && a.m_stateSet == b.m_stateSet && a.m_geometry == b.m_geometry && a.m_geometryRenderer == b.m_geometryRenderer && a.m_indirectDrawBuffer == b.m_indirectDrawBuffer && a.m_activeAttributes == b.m_activeAttributes && - a.m_depth == b.m_depth && a.m_changeCost == b.m_changeCost && a.m_shaderDna == b.m_shaderDna && + a.m_depth == b.m_depth && a.m_changeCost == b.m_changeCost && a.m_shaderId == b.m_shaderId && a.m_workGroups[0] == b.m_workGroups[0] && a.m_workGroups[1] == b.m_workGroups[1] && a.m_workGroups[2] == b.m_workGroups[2] && a.m_primitiveCount == b.m_primitiveCount && a.m_primitiveType == b.m_primitiveType && a.m_restartIndexValue == b.m_restartIndexValue && a.m_firstInstance == b.m_firstInstance && a.m_firstVertex == b.m_firstVertex && a.m_verticesPerPatch == b.m_verticesPerPatch && diff --git a/src/render/renderers/opengl/renderer/rendercommand_p.h b/src/render/renderers/opengl/renderer/rendercommand_p.h index e1cf7a4e0..44e34ecfb 100644 --- a/src/render/renderers/opengl/renderer/rendercommand_p.h +++ b/src/render/renderers/opengl/renderer/rendercommand_p.h @@ -72,6 +72,7 @@ namespace Render { class RenderStateSet; using RenderStateSetPtr = QSharedPointer; +class GLShader; class Q_AUTOTEST_EXPORT RenderCommand { @@ -79,8 +80,9 @@ public: RenderCommand(); HVao m_vao; // VAO used during the submission step to store all states and VBOs - HShader m_shader; // Shader for given pass and mesh HMaterial m_material; // Purely used to ease sorting (minimize stage changes, binding changes ....) + GLShader *m_glShader; // GL Shader to be used at render time + Qt3DCore::QNodeId m_shaderId; // Shader for given pass and mesh ShaderParameterPack m_parameterPack; // Might need to be reworked so as to be able to destroy the // Texture while submission is happening. RenderStateSetPtr m_stateSet; @@ -97,7 +99,6 @@ public: float m_depth; int m_changeCost; - uint m_shaderDna; enum CommandType { Draw, diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index 21eeae9d8..d09878315 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -244,7 +244,6 @@ Renderer::Renderer(QRenderAspect::RenderType type) , m_lastFrameCorrect(0) , m_glContext(nullptr) , m_shareContext(nullptr) - , m_shaderCache(new ShaderCache()) , m_pickBoundingVolumeJob(PickBoundingVolumeJobPtr::create()) , m_rayCastingJob(RayCastingJobPtr::create()) , m_time(0) @@ -333,7 +332,6 @@ Renderer::~Renderer() delete m_renderQueue; delete m_defaultRenderStateSet; - delete m_shaderCache; delete m_glResourceManagers; if (!m_ownedContext) @@ -431,8 +429,9 @@ QOpenGLContext *Renderer::shareContext() const // Executed in the reloadDirtyShader job void Renderer::loadShader(Shader *shader, HShader shaderHandle) { - Q_UNUSED(shader) - m_dirtyShaders.push_back(shaderHandle); + Q_UNUSED(shader); + if (!m_dirtyShaders.contains(shaderHandle)) + m_dirtyShaders.push_back(shaderHandle); } void Renderer::setOpenGLContext(QOpenGLContext *context) @@ -508,9 +507,6 @@ void Renderer::initialize() m_shareContext->create(); } - // Set shader cache on submission context and command thread - m_submissionContext->setShaderCache(m_shaderCache); - // Note: we don't have a surface at this point // The context will be made current later on (at render time) m_submissionContext->setOpenGLContext(ctx); @@ -622,6 +618,10 @@ void Renderer::releaseGraphicsResources() buffer->destroy(m_submissionContext.data()); } + // Do the same thing with shaders + const QVector shaders = m_glResourceManagers->glShaderManager()->takeActiveResources(); + qDeleteAll(shaders); + // Do the same thing with VAOs const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); for (const HVao &vaoHandle : activeVaos) { @@ -788,6 +788,13 @@ void Renderer::doRender(bool swapBuffers) // 2) Update VAO and copy data into commands to allow concurrent submission prepareCommandsSubmission(renderViews); preprocessingComplete = true; + + // Purge shader which aren't used any longer + static int callCount = 0; + ++callCount; + const int shaderPurgePeriod = 600; + if (callCount % shaderPurgePeriod == 0) + m_glResourceManagers->glShaderManager()->purge(); } } } @@ -956,7 +963,7 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView if (command.m_type == RenderCommand::Draw) { Geometry *rGeometry = m_nodesManager->data(command.m_geometry); GeometryRenderer *rGeometryRenderer = m_nodesManager->data(command.m_geometryRenderer); - Shader *shader = m_nodesManager->data(command.m_shader); + GLShader *shader = command.m_glShader; // We should never have inserted a command for which these are null // in the first place @@ -991,7 +998,7 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView if (!command.m_activeAttributes.isEmpty() && (requiresFullVAOUpdate || requiresPartialVAOUpdate)) { Profiling::GLTimeRecorder recorder(Profiling::VAOUpload, activeProfiler()); // Activate shader - m_submissionContext->activateShader(shader->dna()); + m_submissionContext->activateShader(shader); // Bind VAO vao->bind(); // Update or set Attributes and Buffers for the given rGeometry and Command @@ -1011,7 +1018,7 @@ void Renderer::prepareCommandsSubmission(const QVector &renderView shader->prepareUniforms(command.m_parameterPack); } else if (command.m_type == RenderCommand::Compute) { - Shader *shader = m_nodesManager->data(command.m_shader); + GLShader *shader = command.m_glShader; Q_ASSERT(shader); // Prepare the ShaderParameterPack based on the active uniforms of the shader @@ -1045,7 +1052,7 @@ void Renderer::lookForAbandonedVaos() // Make sure to only mark VAOs for deletion that were already created // (ignore those that might be currently under construction in the render thread) - if (vao && vao->isAbandoned(m_nodesManager->geometryManager(), m_nodesManager->shaderManager())) { + if (vao && vao->isAbandoned(m_nodesManager->geometryManager(), m_glResourceManagers->glShaderManager())) { m_abandonedVaosMutex.lock(); m_abandonedVaos.push_back(handle); m_abandonedVaosMutex.unlock(); @@ -1161,8 +1168,7 @@ void Renderer::reloadDirtyShaders() } } - // If the shader hasn't been loaded, load it - if (shader != nullptr && !shader->isLoaded()) + if (shader != nullptr && shader->isDirty()) loadShader(shader, shaderHandle); } } @@ -1334,7 +1340,7 @@ void Renderer::updateGLResources() continue; // Compile shader - m_submissionContext->loadShader(shader, shaderManager); + m_submissionContext->loadShader(shader, shaderManager, m_glResourceManagers->glShaderManager()); } } #endif @@ -1466,6 +1472,16 @@ void Renderer::cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId) } } +// Render Thread +void Renderer::cleanupShader(const Shader *shader) +{ + GLShaderManager *glShaderManager = m_glResourceManagers->glShaderManager(); + GLShader *glShader = glShaderManager->lookupResource(shader->peerId()); + + if (glShader != nullptr) + glShaderManager->abandon(glShader, shader); +} + // Called by SubmitRenderView void Renderer::downloadGLBuffers() { @@ -2106,7 +2122,8 @@ void Renderer::performCompute(const RenderView *, RenderCommand *command) { { Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler()); - m_submissionContext->activateShader(command->m_shaderDna); + GLShader *shader = m_glResourceManagers->glShaderManager()->lookupResource(command->m_shaderId); + m_submissionContext->activateShader(shader); } { Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler()); @@ -2132,7 +2149,7 @@ void Renderer::createOrUpdateVAO(RenderCommand *command, HVao *previousVaoHandle, OpenGLVertexArrayObject **vao) { - const VAOIdentifier vaoKey(command->m_geometry, command->m_shader); + const VAOIdentifier vaoKey(command->m_geometry, command->m_shaderId); VAOManager *vaoManager = m_glResourceManagers->vaoManager(); command->m_vao = vaoManager->lookupHandle(vaoKey); @@ -2188,7 +2205,8 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) { Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler()); //// We activate the shader here - if (!m_submissionContext->activateShader(command.m_shaderDna)) { + GLShader *shader = command.m_glShader; + if (!m_submissionContext->activateShader(shader)) { allCommandsIssued = false; continue; } @@ -2250,7 +2268,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv) bool Renderer::updateVAOWithAttributes(Geometry *geometry, const RenderCommand *command, - Shader *shader, + GLShader *shader, bool forceUpdate) { m_dirtyAttributes.reserve(m_dirtyAttributes.size() + geometry->attributes().size()); @@ -2355,6 +2373,16 @@ void Renderer::cleanGraphicsResources() m_glResourceManagers->vaoManager()->release(vaoHandle); } } + + // Abandon GL shaders when a Shader node is destroyed Note: We are sure + // that when this gets executed, all scene changes have been received and + // shader nodes updated + const QVector cleanedUpShaderIds = m_nodesManager->shaderManager()->takeShaderIdsToCleanup(); + for (const Qt3DCore::QNodeId shaderCleanedUpId: cleanedUpShaderIds) { + cleanupShader(m_nodesManager->shaderManager()->lookupResource(shaderCleanedUpId)); + // We can really release the texture at this point + m_nodesManager->shaderManager()->releaseResource(shaderCleanedUpId); + } } const GraphicsApiFilterData *Renderer::contextInfo() const diff --git a/src/render/renderers/opengl/renderer/renderer.pri b/src/render/renderers/opengl/renderer/renderer.pri index 849bac702..3e2f9fde9 100644 --- a/src/render/renderers/opengl/renderer/renderer.pri +++ b/src/render/renderers/opengl/renderer/renderer.pri @@ -7,7 +7,8 @@ SOURCES += \ $$PWD/renderqueue.cpp \ $$PWD/renderview.cpp \ $$PWD/renderviewbuilder.cpp \ - $$PWD/shaderparameterpack.cpp + $$PWD/shaderparameterpack.cpp \ + $$PWD/glshader.cpp HEADERS += \ $$PWD/openglvertexarrayobject_p.h \ @@ -18,6 +19,6 @@ HEADERS += \ $$PWD/renderview_p.h \ $$PWD/renderviewbuilder_p.h \ $$PWD/shaderparameterpack_p.h \ - $$PWD/shadervariables_p.h - + $$PWD/shadervariables_p.h \ + $$PWD/glshader_p.h diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index d8f95dc2b..557089b19 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -153,8 +153,8 @@ class RenderStateSet; class VSyncFrameAdvanceService; class PickEventFilter; class NodeManagers; -class ShaderCache; class GLResourceManagers; +class GLShader; class UpdateLevelOfDetailJob; typedef QSharedPointer UpdateLevelOfDetailJobPtr; @@ -267,6 +267,7 @@ public: void updateGLResources(); void updateTexture(Texture *texture); void cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId); + void cleanupShader(const Shader *shader); void downloadGLBuffers(); void blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId, Qt3DCore::QNodeId outputRenderTargetId, @@ -278,7 +279,7 @@ public: bool executeCommandsSubmission(const RenderView *rv); bool updateVAOWithAttributes(Geometry *geometry, const RenderCommand *command, - Shader *shader, + GLShader *shader, bool forceUpdate); bool requiresVAOAttributeUpdate(Geometry *geometry, @@ -365,7 +366,6 @@ private: QOpenGLContext *m_glContext; QOpenGLContext *m_shareContext; mutable QMutex m_shareContextMutex; - ShaderCache *m_shaderCache; PickBoundingVolumeJobPtr m_pickBoundingVolumeJob; RayCastingJobPtr m_rayCastingJob; diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp index 2a16c9bfd..6b6de01a7 100644 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ b/src/render/renderers/opengl/renderer/renderview.cpp @@ -69,6 +69,7 @@ #include #include #include +#include #include #include #include @@ -322,7 +323,7 @@ struct AdjacentSubRangeFinder { static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) { - return a.m_shaderDna == b.m_shaderDna; + return a.m_glShader == b.m_glShader; } }; @@ -410,9 +411,9 @@ struct SubRangeSorter { static void sortSubRange(CommandIt begin, const CommandIt end) { - // First we sort by shaderDNA + // First we sort by shader std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { - return a.m_shaderDna > b.m_shaderDna; + return a.m_glShader > b.m_glShader; }); } }; @@ -537,7 +538,9 @@ void sortCommandRange(QVector &commands, int begin, const int end void RenderView::sort() { - sortCommandRange(m_commands, 0, m_commands.size(), 0, m_data.m_sortingTypes); + // Compares the bitsetKey of the RenderCommands + // Key[Depth | StateCost | Shader] + sortCommandRange(m_commands, 0, m_commands.size(), 0, m_data.m_sortingTypes); // For RenderCommand with the same shader // We compute the adjacent change cost @@ -553,7 +556,8 @@ void RenderView::sort() int j = i; // Advance while commands share the same shader - while (i < commandSize && m_commands[j].m_shaderDna == m_commands[i].m_shaderDna) + while (i < commandSize && + m_commands[j].m_glShader == m_commands[i].m_glShader) ++i; if (i - j > 0) { // Several commands have the same shader, so we minimize uniform changes @@ -635,6 +639,7 @@ void RenderView::addClearBuffers(const ClearBuffers *cb) { EntityRenderCommandData RenderView::buildDrawRenderCommands(const QVector &entities, int offset, int count) const { + GLShaderManager *glShaderManager = m_renderer->glResourceManagers()->glShaderManager(); EntityRenderCommandData commands; commands.reserve(count); @@ -677,7 +682,13 @@ EntityRenderCommandData RenderView::buildDrawRenderCommands(const QVectormerge(m_stateSet); command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); } - command.m_shader = m_manager->lookupHandle(pass->shaderProgram()); + command.m_shaderId = pass->shaderProgram(); + command.m_glShader = glShaderManager->lookupResource(command.m_shaderId); + + // It takes two frames to have a valid command as we can only + // reference a glShader at frame n if it has been loaded at frame n - 1 + if (!command.m_glShader) + continue; { // Scoped to show extent @@ -763,6 +774,7 @@ EntityRenderCommandData RenderView::buildComputeRenderCommands(const QVectorglResourceManagers()->glShaderManager(); commands.reserve(count); @@ -793,7 +805,14 @@ EntityRenderCommandData RenderView::buildComputeRenderCommands(const QVectormerge(m_stateSet); command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); } - command.m_shader = m_manager->lookupHandle(pass->shaderProgram()); + command.m_shaderId = pass->shaderProgram(); + command.m_glShader = glShaderManager->lookupResource(command.m_shaderId); + + // It takes two frames to have a valid command as we can only + // reference a glShader at frame n if it has been loaded at frame n - 1 + if (!command.m_glShader) + continue; + command.m_computeCommand = computeCommandHandle; command.m_type = RenderCommand::Compute; command.m_workGroups[0] = std::max(m_workGroups[0], computeJob->x()); @@ -865,6 +884,7 @@ void RenderView::updateRenderCommand(EntityRenderCommandData *renderCommandData, ParameterInfoList globalParameters = passData.parameterInfo; // setShaderAndUniforms can initialize a localData // make sure this is cleared before we leave this function + setShaderAndUniforms(&command, globalParameters, entity, @@ -944,7 +964,7 @@ void RenderView::setStandardUniformValue(ShaderParameterPack &uniformPack, } void RenderView::setUniformBlockValue(ShaderParameterPack &uniformPack, - Shader *shader, + GLShader *shader, const ShaderUniformBlock &block, const UniformValue &value) const { @@ -965,7 +985,7 @@ void RenderView::setUniformBlockValue(ShaderParameterPack &uniformPack, } void RenderView::setShaderStorageValue(ShaderParameterPack &uniformPack, - Shader *shader, + GLShader *shader, const ShaderStorageBlock &block, const UniformValue &value) const { @@ -983,7 +1003,7 @@ void RenderView::setShaderStorageValue(ShaderParameterPack &uniformPack, } } -void RenderView::setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, Shader *shader, ShaderData *shaderData, const QString &structName) const +void RenderView::setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, GLShader *shader, ShaderData *shaderData, const QString &structName) const { UniformBlockValueBuilder *builder = m_localData.localData(); builder->activeUniformNamesToValue.clear(); @@ -1023,10 +1043,8 @@ void RenderView::setShaderAndUniforms(RenderCommand *command, // For each ParameterBinder in the RenderPass -> create a QUniformPack // Once that works, improve that to try and minimize QUniformPack updates - // Index Shader by Shader UUID - Shader *shader = m_manager->data(command->m_shader); + GLShader *shader = command->m_glShader; if (shader != nullptr && shader->isLoaded()) { - command->m_shaderDna = shader->dna(); // Builds the QUniformPack, sets shader standard uniforms and store attributes name / glname bindings // If a parameter is defined and not found in the bindings it is assumed to be a binding of Uniform type with the glsl name diff --git a/src/render/renderers/opengl/renderer/renderview_p.h b/src/render/renderers/opengl/renderer/renderview_p.h index 6f31e40ef..f00228c84 100644 --- a/src/render/renderers/opengl/renderer/renderview_p.h +++ b/src/render/renderers/opengl/renderer/renderview_p.h @@ -389,15 +389,15 @@ private: Entity *entity, const Matrix4x4 &worldTransform) const; void setUniformBlockValue(ShaderParameterPack &uniformPack, - Shader *shader, + GLShader *shader, const ShaderUniformBlock &block, const UniformValue &value) const; void setShaderStorageValue(ShaderParameterPack &uniformPack, - Shader *shader, + GLShader *shader, const ShaderStorageBlock &block, const UniformValue &value) const; void setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, - Shader *shader, + GLShader *shader, ShaderData *shaderData, const QString &structName) const; }; diff --git a/tests/auto/render/glshadermanager/glshadermanager.pro b/tests/auto/render/glshadermanager/glshadermanager.pro new file mode 100644 index 000000000..27aadf84f --- /dev/null +++ b/tests/auto/render/glshadermanager/glshadermanager.pro @@ -0,0 +1,12 @@ +TEMPLATE = app + +TARGET = tst_glshadermanager + +QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_glshadermanager.cpp + +include(../../core/common/common.pri) +include(../commons/commons.pri) diff --git a/tests/auto/render/glshadermanager/tst_glshadermanager.cpp b/tests/auto/render/glshadermanager/tst_glshadermanager.cpp new file mode 100644 index 000000000..c18fb4793 --- /dev/null +++ b/tests/auto/render/glshadermanager/tst_glshadermanager.cpp @@ -0,0 +1,199 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "qbackendnodetester.h" +#include "testrenderer.h" + +class tst_GLShaderManager : public Qt3DCore::QBackendNodeTester +{ + Q_OBJECT + +private Q_SLOTS: + void adopt(); + void lookupResource(); + void abandon(); + void insertAfterRemoval(); +}; + +void tst_GLShaderManager::adopt() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader1; + Qt3DRender::QShaderProgram frontendShader2; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode1; + Qt3DRender::Render::Shader backendShaderNode2; + + backendShaderNode1.setRenderer(&renderer); + backendShaderNode2.setRenderer(&renderer); + simulateInitialization(&frontendShader1, &backendShaderNode1); + simulateInitialization(&frontendShader2, &backendShaderNode2); + + // THEN + QVERIFY(cache.lookupResource(backendShaderNode1.peerId()) == nullptr); + QVERIFY(cache.lookupResource(backendShaderNode2.peerId()) == nullptr); + QVERIFY(backendShaderNode1.peerId() != backendShaderNode2.peerId()); + + // WHEN + Qt3DRender::Render::GLShader *glShader1 = cache.createOrAdoptExisting(&backendShaderNode1); + + // THEN + QVERIFY(glShader1 != nullptr); + QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); + QCOMPARE(shaderNodeIds.size(), 1); + QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); + + // WHEN + Qt3DRender::Render::GLShader *glShader2 = cache.createOrAdoptExisting(&backendShaderNode2); + + // THEN + QCOMPARE(glShader1, glShader2); + + shaderNodeIds = cache.shaderIdsForProgram(glShader2); + QCOMPARE(shaderNodeIds.size(), 2); + QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); + QCOMPARE(shaderNodeIds.last(), backendShaderNode2.peerId()); +} + +void tst_GLShaderManager::lookupResource() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader1; + Qt3DRender::QShaderProgram frontendShader2; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode1; + Qt3DRender::Render::Shader backendShaderNode2; + + backendShaderNode1.setRenderer(&renderer); + backendShaderNode2.setRenderer(&renderer); + simulateInitialization(&frontendShader1, &backendShaderNode1); + simulateInitialization(&frontendShader2, &backendShaderNode2); + + // WHEN + cache.createOrAdoptExisting(&backendShaderNode1); + cache.createOrAdoptExisting(&backendShaderNode2); + + // THEN + Qt3DRender::Render::GLShader *glShader1 = cache.lookupResource(backendShaderNode1.peerId()); + Qt3DRender::Render::GLShader *glShader2 = cache.lookupResource(backendShaderNode2.peerId()); + QVERIFY(glShader1 != nullptr); + QCOMPARE(glShader1, glShader2); + const QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); + QCOMPARE(shaderNodeIds.size(), 2); + QVERIFY(shaderNodeIds.contains(frontendShader1.id())); + QVERIFY(shaderNodeIds.contains(frontendShader2.id())); +} + +void tst_GLShaderManager::abandon() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader1; + Qt3DRender::QShaderProgram frontendShader2; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode1; + Qt3DRender::Render::Shader backendShaderNode2; + + backendShaderNode1.setRenderer(&renderer); + backendShaderNode2.setRenderer(&renderer); + simulateInitialization(&frontendShader1, &backendShaderNode1); + simulateInitialization(&frontendShader2, &backendShaderNode2); + cache.createOrAdoptExisting(&backendShaderNode1); + cache.createOrAdoptExisting(&backendShaderNode2); + + // WHEN + Qt3DRender::Render::GLShader *glShader = cache.lookupResource(backendShaderNode1.peerId()); + cache.abandon(glShader, &backendShaderNode1); + + // THEN + QVector shaderNodeIds = cache.shaderIdsForProgram(glShader); + QVERIFY(cache.takeAbandonned().isEmpty()); + QCOMPARE(shaderNodeIds.size(), 1); + QCOMPARE(shaderNodeIds.first(), backendShaderNode2.peerId()); + + // WHEN + cache.abandon(glShader, &backendShaderNode2); + + // THEN + shaderNodeIds = cache.shaderIdsForProgram(glShader); + QCOMPARE(shaderNodeIds.size(), 0); + const QVector releasedShaders = cache.takeAbandonned(); + QCOMPARE(releasedShaders.size(), 1); + QCOMPARE(releasedShaders.first(), glShader); +} + +void tst_GLShaderManager::insertAfterRemoval() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode; + + + backendShaderNode.setRenderer(&renderer); + simulateInitialization(&frontendShader, &backendShaderNode); + + // WHEN + Qt3DRender::Render::GLShader *apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); + const Qt3DRender::Render::GLShader *originalApiShader = apiShader1; + + // THEN + auto apiShader2 = cache.lookupResource(frontendShader.id()); + QVERIFY(apiShader1 != nullptr); + QVERIFY(apiShader2 != nullptr); + QVERIFY(apiShader1 == originalApiShader); + QVERIFY(apiShader1 == apiShader2); + + // WHEN + cache.abandon(apiShader1, &backendShaderNode); + + // THEN + Qt3DRender::Render::GLShader *apiShaderEmpty = cache.lookupResource(frontendShader.id()); + QVERIFY(apiShaderEmpty == nullptr); + + // WHEN + apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); + cache.purge(); + apiShader2 = cache.lookupResource(frontendShader.id()); + + // THEN + QVERIFY(apiShader1 != nullptr); + QVERIFY(apiShader2 != nullptr); + QVERIFY(apiShader1 == apiShader2); + QVERIFY(apiShader2 == originalApiShader); +} + +QTEST_APPLESS_MAIN(tst_GLShaderManager) + +#include "tst_glshadermanager.moc" diff --git a/tests/auto/render/render.pro b/tests/auto/render/render.pro index 908426570..2b73ec8b7 100644 --- a/tests/auto/render/render.pro +++ b/tests/auto/render/render.pro @@ -42,7 +42,6 @@ qtConfig(private_tests) { # boundingvolumedebug \ ddstextures \ ktxtextures \ - shadercache \ layerfiltering \ filterentitybycomponent \ genericlambdajob \ @@ -130,6 +129,7 @@ qtConfig(qt3d-opengl-renderer):qtConfig(private_tests) { graphicshelpergl3_3 \ graphicshelpergl3_2 \ graphicshelpergl2 \ + glshadermanager \ materialparametergathererjob \ textures \ renderer \ diff --git a/tests/auto/render/renderviews/tst_renderviews.cpp b/tests/auto/render/renderviews/tst_renderviews.cpp index 086ff0220..b434fe83a 100644 --- a/tests/auto/render/renderviews/tst_renderviews.cpp +++ b/tests/auto/render/renderviews/tst_renderviews.cpp @@ -36,6 +36,9 @@ #include #include #include +#include +#include +#include QT_BEGIN_NAMESPACE @@ -64,6 +67,7 @@ void compareShaderParameterPacks(const ShaderParameterPack &t1, class tst_RenderViews : public Qt3DCore::QBackendNodeTester { Q_OBJECT + private Q_SLOTS: void checkRenderViewSizeFitsWithAllocator() @@ -132,10 +136,15 @@ private Q_SLOTS: void checkRenderCommandBackToFrontSorting() { // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + sortTypes.push_back(QSortPolicy::BackToFront); for (int i = 0; i < 200; ++i) { @@ -156,28 +165,34 @@ private Q_SLOTS: QVERIFY(sortedCommands.at(j - 1).m_depth > sortedCommands.at(j).m_depth); // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); } void checkRenderCommandMaterialSorting() { // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + sortTypes.push_back(QSortPolicy::Material); - ProgramDNA dnas[5] = { - ProgramDNA(250), - ProgramDNA(500), - ProgramDNA(1000), - ProgramDNA(1500), - ProgramDNA(2000), + GLShader *dnas[5] = { + reinterpret_cast(0x250), + reinterpret_cast(0x500), + reinterpret_cast(0x1000), + reinterpret_cast(0x1500), + reinterpret_cast(0x2000) }; for (int i = 0; i < 20; ++i) { RenderCommand c; - c.m_shaderDna = dnas[i % 5]; + c.m_glShader = dnas[i % 5]; rawCommands.push_back(c); } @@ -189,24 +204,25 @@ private Q_SLOTS: // THEN const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands.size(), sortedCommands.size()); - ProgramDNA targetDNA; + GLShader *targetShader; for (int j = 0; j < sortedCommands.size(); ++j) { if (j % 4 == 0) { - targetDNA = sortedCommands.at(j).m_shaderDna; + targetShader = sortedCommands.at(j).m_glShader; if (j > 0) - QVERIFY(targetDNA != sortedCommands.at(j - 1).m_shaderDna); + QVERIFY(targetShader != sortedCommands.at(j - 1).m_glShader); } - QCOMPARE(targetDNA, sortedCommands.at(j).m_shaderDna); + QCOMPARE(targetShader, sortedCommands.at(j).m_glShader); } // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); } void checkRenderViewUniformMinification_data() { - QTest::addColumn>("programDNAs"); + QTest::addColumn>("shaders"); QTest::addColumn>("rawParameters"); QTest::addColumn>("expectedMinimizedParameters"); @@ -217,36 +233,56 @@ private Q_SLOTS: pack1.setUniform(2, UniformValue(1584.0f)); pack1.setTexture(3, 0, fakeTextureNodeId); + QShaderProgram *shader1 = new QShaderProgram(); + QShaderProgram *shader2 = new QShaderProgram(); + + shader1->setShaderCode(QShaderProgram::Vertex, QByteArrayLiteral("1")); + shader2->setShaderCode(QShaderProgram::Vertex, QByteArrayLiteral("2")); + ShaderParameterPack minifiedPack1; QTest::newRow("NoMinification") - << (QVector() << ProgramDNA(883) << ProgramDNA(1584)) + << (QVector() << shader1 << shader2) << (QVector() << pack1 << pack1) << (QVector() << pack1 << pack1); QTest::newRow("SingleShaderMinified") - << (QVector() << ProgramDNA(883) << ProgramDNA(883) << ProgramDNA(883)) + << (QVector() << shader1 << shader1 << shader1) << (QVector() << pack1 << pack1 << pack1) << (QVector() << pack1 << minifiedPack1 << minifiedPack1); QTest::newRow("MultipleShadersMinified") - << (QVector() << ProgramDNA(883) << ProgramDNA(883) << ProgramDNA(883) << ProgramDNA(1584) << ProgramDNA(1584) << ProgramDNA(1584)) + << (QVector() << shader1 << shader1 << shader1 << shader2 << shader2 << shader2) << (QVector() << pack1 << pack1 << pack1 << pack1 << pack1 << pack1) << (QVector() << pack1 << minifiedPack1 << minifiedPack1 << pack1 << minifiedPack1 << minifiedPack1); } void checkRenderViewUniformMinification() { - QFETCH(QVector, programDNAs); + QFETCH(QVector, shaders); QFETCH(QVector, rawParameters); QFETCH(QVector, expectedMinimizedParameters); + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + renderer.setNodeManagers(&nodeManagers); + + GLShaderManager *shaderManager = renderer.glResourceManagers()->glShaderManager(); + for (int i = 0, m = shaders.size(); i < m; ++i) { + Shader* backend = new Shader(); + backend->setRenderer(&renderer); + simulateInitializationSync(shaders.at(i), backend); + shaderManager->createOrAdoptExisting(backend); + } + RenderView renderView; QVector rawCommands; + renderView.setRenderer(&renderer); - for (int i = 0, m = programDNAs.size(); i < m; ++i) { + for (int i = 0, m = shaders.size(); i < m; ++i) { RenderCommand c; - c.m_shaderDna = programDNAs.at(i); + c.m_shaderId = shaders.at(i)->id(); + c.m_glShader = shaderManager->lookupResource(c.m_shaderId); c.m_parameterPack = rawParameters.at(i); rawCommands.push_back(c); } @@ -260,21 +296,28 @@ private Q_SLOTS: const QVector sortedCommands = renderView.commands(); QCOMPARE(rawCommands, sortedCommands); - for (int i = 0, m = programDNAs.size(); i < m; ++i) { + for (int i = 0, m = shaders.size(); i < m; ++i) { const RenderCommand c = sortedCommands.at(i); - QCOMPARE(c.m_shaderDna, programDNAs.at(i)); + QCOMPARE(c.m_shaderId, shaders.at(i)->id()); compareShaderParameterPacks(c.m_parameterPack, expectedMinimizedParameters.at(i)); } + + renderer.shutdown(); } void checkRenderCommandFrontToBackSorting() { // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + sortTypes.push_back(QSortPolicy::FrontToBack); for (int i = 0; i < 200; ++i) { @@ -295,15 +338,21 @@ private Q_SLOTS: QVERIFY(sortedCommands.at(j - 1).m_depth < sortedCommands.at(j).m_depth); // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); } void checkRenderCommandStateCostSorting() { // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + sortTypes.push_back(QSortPolicy::StateChangeCost); for (int i = 0; i < 200; ++i) { @@ -324,24 +373,31 @@ private Q_SLOTS: QVERIFY(sortedCommands.at(j - 1).m_changeCost > sortedCommands.at(j).m_changeCost); // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); } void checkRenderCommandCombinedStateMaterialDepthSorting() { // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + sortTypes.push_back(QSortPolicy::StateChangeCost); sortTypes.push_back(QSortPolicy::Material); sortTypes.push_back(QSortPolicy::BackToFront); - ProgramDNA dna[4] = { - ProgramDNA(250), - ProgramDNA(500), - ProgramDNA(1000), - ProgramDNA(1500) + GLShader *dna[5] = { + reinterpret_cast(0x250), + reinterpret_cast(0x500), + reinterpret_cast(0x1000), + reinterpret_cast(0x1500), + reinterpret_cast(0x2000) }; float depth[3] = { @@ -355,9 +411,9 @@ private Q_SLOTS: 200 }; - auto buildRC = [] (ProgramDNA dna, float depth, int changeCost) { + auto buildRC = [] (GLShader *dna, float depth, int changeCost) { RenderCommand c; - c.m_shaderDna = dna; + c.m_glShader = dna; c.m_depth = depth; c.m_changeCost = changeCost; return c; @@ -400,6 +456,7 @@ private Q_SLOTS: QCOMPARE(c9, sortedCommands.at(6)); // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); } void checkRenderCommandTextureSorting() diff --git a/tests/auto/render/shader/tst_shader.cpp b/tests/auto/render/shader/tst_shader.cpp index d1578aee7..3f0714907 100644 --- a/tests/auto/render/shader/tst_shader.cpp +++ b/tests/auto/render/shader/tst_shader.cpp @@ -79,15 +79,9 @@ void tst_RenderShader::hasCoherentInitialState() { Qt3DRender::Render::Shader *shader = new Qt3DRender::Render::Shader(); - QCOMPARE(shader->isLoaded(), false); - QCOMPARE(shader->dna(), 0U); - QVERIFY(shader->uniformsNames().isEmpty()); - QVERIFY(shader->attributesNames().isEmpty()); - QVERIFY(shader->uniformBlockNames().isEmpty()); - QVERIFY(shader->uniforms().isEmpty()); - QVERIFY(shader->attributes().isEmpty()); - QVERIFY(shader->uniformBlocks().isEmpty()); QCOMPARE(shader->status(), Qt3DRender::QShaderProgram::NotReady); + QVERIFY(shader->log().isEmpty()); + QCOMPARE(shader->isDirty(), false); } void tst_RenderShader::matchesFrontendPeer() @@ -98,8 +92,7 @@ void tst_RenderShader::matchesFrontendPeer() backend.setRenderer(&renderer); simulateInitializationSync(frontend.data(), &backend); - QCOMPARE(backend.isLoaded(), false); - QVERIFY(backend.dna() != 0U); + QCOMPARE(backend.isDirty(), true); for (int i = Qt3DRender::QShaderProgram::Vertex; i <= Qt3DRender::QShaderProgram::Compute; ++i) QCOMPARE(backend.shaderCode()[i], @@ -117,14 +110,7 @@ void tst_RenderShader::cleanupLeavesACoherentState() shader.cleanup(); - QCOMPARE(shader.isLoaded(), false); - QCOMPARE(shader.dna(), 0U); - QVERIFY(shader.uniformsNames().isEmpty()); - QVERIFY(shader.attributesNames().isEmpty()); - QVERIFY(shader.uniformBlockNames().isEmpty()); - QVERIFY(shader.uniforms().isEmpty()); - QVERIFY(shader.attributes().isEmpty()); - QVERIFY(shader.uniformBlocks().isEmpty()); + QCOMPARE(shader.isDirty(), false); QCOMPARE(shader.status(), Qt3DRender::QShaderProgram::NotReady); } @@ -152,7 +138,7 @@ void tst_RenderShader::dealWithPropertyChanges() Qt3DRender::Render::Shader backend; Qt3DRender::QShaderProgram shader; - backend.setLoaded(true); + TestRenderer renderer; backend.setRenderer(&renderer); simulateInitializationSync(&shader, &backend); @@ -162,11 +148,13 @@ void tst_RenderShader::dealWithPropertyChanges() backend.syncFromFrontEnd(&shader, false); // THEN - QCOMPARE(backend.shaderCode().at(type), QByteArrayLiteral("foo")); - QVERIFY(!backend.isLoaded()); + QCOMPARE(backend.shaderCode().at(type), QStringLiteral("foo")); QCOMPARE(renderer.dirtyBits(), Qt3DRender::Render::AbstractRenderer::ShadersDirty); + QCOMPARE(backend.isDirty(), true); + renderer.resetDirty(); - backend.setLoaded(true); + QCOMPARE(renderer.dirtyBits(), 0); + backend.unsetDirty(); // WHEN shader.setShaderCode(type, QByteArrayLiteral("foo")); @@ -174,10 +162,8 @@ void tst_RenderShader::dealWithPropertyChanges() // THEN QCOMPARE(backend.shaderCode().at(type), QByteArrayLiteral("foo")); - QVERIFY(backend.isLoaded()); QCOMPARE(renderer.dirtyBits(), 0); - renderer.resetDirty(); - backend.setLoaded(true); + QCOMPARE(backend.isDirty(), false); // WHEN shader.setShaderCode(type, QByteArrayLiteral("bar")); @@ -185,10 +171,9 @@ void tst_RenderShader::dealWithPropertyChanges() // THEN QCOMPARE(backend.shaderCode().at(type), QByteArrayLiteral("bar")); - QVERIFY(!backend.isLoaded()); QCOMPARE(renderer.dirtyBits(), Qt3DRender::Render::AbstractRenderer::ShadersDirty); renderer.resetDirty(); - backend.setLoaded(true); + QCOMPARE(backend.isDirty(), true); } void tst_RenderShader::checkSetRendererDirtyOnInitialization() @@ -221,7 +206,6 @@ void tst_RenderShader::allowToChangeShaderCode() QFETCH(Qt3DRender::QShaderProgram::ShaderType, type); Qt3DRender::Render::Shader backend; - backend.setLoaded(true); TestRenderer renderer; backend.setRenderer(&renderer); @@ -230,30 +214,24 @@ void tst_RenderShader::allowToChangeShaderCode() // THEN QCOMPARE(backend.shaderCode().at(type), QStringLiteral("foo")); - QVERIFY(!backend.isLoaded()); QCOMPARE(renderer.dirtyBits(), Qt3DRender::Render::AbstractRenderer::ShadersDirty); renderer.resetDirty(); - backend.setLoaded(true); // WHEN backend.setShaderCode(type, QByteArrayLiteral("foo")); // THEN QCOMPARE(backend.shaderCode().at(type), QStringLiteral("foo")); - QVERIFY(backend.isLoaded()); QCOMPARE(renderer.dirtyBits(), 0); renderer.resetDirty(); - backend.setLoaded(true); // WHEN backend.setShaderCode(type, QByteArrayLiteral("bar")); // THEN QCOMPARE(backend.shaderCode().at(type), QStringLiteral("bar")); - QVERIFY(!backend.isLoaded()); QCOMPARE(renderer.dirtyBits(), Qt3DRender::Render::AbstractRenderer::ShadersDirty); renderer.resetDirty(); - backend.setLoaded(true); } QTEST_APPLESS_MAIN(tst_RenderShader) diff --git a/tests/auto/render/shadercache/shadercache.pro b/tests/auto/render/shadercache/shadercache.pro deleted file mode 100644 index 38499588d..000000000 --- a/tests/auto/render/shadercache/shadercache.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app - -TARGET = tst_shadercache - -QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_shadercache.cpp - -include(../../core/common/common.pri) diff --git a/tests/auto/render/shadercache/tst_shadercache.cpp b/tests/auto/render/shadercache/tst_shadercache.cpp deleted file mode 100644 index 261548d69..000000000 --- a/tests/auto/render/shadercache/tst_shadercache.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -using namespace Qt3DCore; - -namespace Qt3DRender { -namespace Render { - -class tst_ShaderCache : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - void insert(); - void insertAfterRemoval(); - void value(); - void removeRef(); - void purge(); - void destruction(); -}; - -void tst_ShaderCache::insert() -{ - // GIVEN - ShaderCache cache; - - // THEN - QCOMPARE(cache.m_programHash.isEmpty(), true); - QCOMPARE(cache.m_programRefs.isEmpty(), true); - QCOMPARE(cache.m_pendingRemoval.isEmpty(), true); - - // WHEN - auto dna = ProgramDNA(12345); - auto nodeId = QNodeId::createId(); - auto shaderProgram = new QOpenGLShaderProgram; - cache.insert(dna, nodeId, shaderProgram); - - // THEN - QCOMPARE(cache.m_programHash.size(), 1); - QCOMPARE(cache.m_programHash.keys().first(), dna); - QCOMPARE(cache.m_programHash.values().first(), shaderProgram); - - QCOMPARE(cache.m_programRefs.size(), 1); - QCOMPARE(cache.m_programRefs.keys().first(), dna); - QCOMPARE(cache.m_programRefs.values().first().size(), 1); - QCOMPARE(cache.m_programRefs.values().first().first(), nodeId); - - QCOMPARE(cache.m_pendingRemoval.isEmpty(), true); -} - -void tst_ShaderCache::insertAfterRemoval() -{ - // GIVEN - ShaderCache cache; - auto dna = ProgramDNA(12345); - auto nodeId = QNodeId::createId(); - - // WHEN - QOpenGLShaderProgram *shaderProgram = new QOpenGLShaderProgram(); - cache.insert(dna, nodeId, shaderProgram); - cache.getShaderProgramAndAddRef(dna, nodeId); - cache.removeRef(dna, nodeId); - shaderProgram = cache.getShaderProgramAndAddRef(dna, nodeId); - - // THEN - QVERIFY(!cache.m_pendingRemoval.contains(dna)); - - // WHEN - cache.removeRef(dna, nodeId); - cache.getShaderProgramAndAddRef(dna, nodeId); - cache.purge(); - - // THEN - QCOMPARE(cache.m_programHash.size(), 1); -} - -void tst_ShaderCache::value() -{ - // GIVEN - ShaderCache cache; - - // WHEN - auto dnaA = ProgramDNA(12345); - auto nodeIdA = QNodeId::createId(); - auto shaderProgramA = new QOpenGLShaderProgram; - cache.insert(dnaA, nodeIdA, shaderProgramA); - auto cachedProgramA = cache.getShaderProgramAndAddRef(dnaA, nodeIdA); - - // THEN - QCOMPARE(shaderProgramA, cachedProgramA); - - // WHEN - auto nodeIdA2 = QNodeId::createId(); - auto cachedProgramA2 = cache.getShaderProgramAndAddRef(dnaA, nodeIdA2); - - // THEN - QCOMPARE(shaderProgramA, cachedProgramA2); - QCOMPARE(cache.m_programHash.size(), 1); - QCOMPARE(cache.m_programHash.keys().first(), dnaA); - QCOMPARE(cache.m_programHash.values().first(), shaderProgramA); - - QCOMPARE(cache.m_programRefs.size(), 1); - QCOMPARE(cache.m_programRefs.keys().first(), dnaA); - const QVector refsA = cache.m_programRefs.values().first(); - QCOMPARE(refsA.size(), 2); - QCOMPARE(refsA.at(0), nodeIdA); - QCOMPARE(refsA.at(1), nodeIdA2); - - // WHEN - auto dnaB = ProgramDNA(67890); - auto nodeIdB = QNodeId::createId(); - auto shaderProgramB = new QOpenGLShaderProgram; - cache.insert(dnaB, nodeIdB, shaderProgramB); - - // THEN - QCOMPARE(cache.m_programHash.size(), 2); - QCOMPARE(cache.m_programRefs.size(), 2); - - // WHEN - auto cachedProgramB = cache.getShaderProgramAndAddRef(dnaB, nodeIdB); - QCOMPARE(shaderProgramB, cachedProgramB); - - // WHEN - auto dnaC = ProgramDNA(54321); - auto uncachedProgram = cache.getShaderProgramAndAddRef(dnaC, nodeIdB); - QVERIFY(uncachedProgram == nullptr); - - cache.clear(); - // Test inserting nullptr. - cache.insert(dnaA, nodeIdA, nullptr); - bool wasPresent = false; - cachedProgramA = cache.getShaderProgramAndAddRef(dnaA, nodeIdA, &wasPresent); - QCOMPARE(wasPresent, true); - QCOMPARE(cachedProgramA, nullptr); - cache.clear(); - // Test wasPresent==false. - cachedProgramB = cache.getShaderProgramAndAddRef(dnaB, nodeIdB, &wasPresent); - QCOMPARE(wasPresent, false); - QCOMPARE(cachedProgramB, nullptr); -} - -void tst_ShaderCache::removeRef() -{ - // GIVEN - ShaderCache cache; - - // WHEN we add 2 references and remove one - auto dnaA = ProgramDNA(12345); - auto nodeIdA = QNodeId::createId(); - auto shaderProgramA = new QOpenGLShaderProgram; - cache.insert(dnaA, nodeIdA, shaderProgramA); - auto cachedProgramA = cache.getShaderProgramAndAddRef(dnaA, nodeIdA); - - auto nodeIdA2 = QNodeId::createId(); - auto cachedProgramA2 = cache.getShaderProgramAndAddRef(dnaA, nodeIdA2); - - cache.removeRef(dnaA, nodeIdA); - - // THEN - QCOMPARE(cachedProgramA, shaderProgramA); - QCOMPARE(cachedProgramA2, shaderProgramA); - QCOMPARE(cache.m_programHash.size(), 1); - QCOMPARE(cache.m_programRefs.size(), 1); - const auto refs = cache.m_programRefs.value(dnaA); - QCOMPARE(refs.size(), 1); - QCOMPARE(refs.first(), nodeIdA2); - QCOMPARE(cache.m_pendingRemoval.size(), 0); - - // WHEN we remove same ref again - cache.removeRef(dnaA, nodeIdA); - - // THEN no change - QCOMPARE(cache.m_programHash.size(), 1); - QCOMPARE(cache.m_programRefs.size(), 1); - const auto refs2 = cache.m_programRefs.value(dnaA); - QCOMPARE(refs2.size(), 1); - QCOMPARE(refs.first(), nodeIdA2); - - // WHEN we remove other reference - cache.removeRef(dnaA, nodeIdA2); - - // THEN - QCOMPARE(cache.m_programHash.size(), 1); - QCOMPARE(cache.m_programRefs.size(), 1); - const auto refs3 = cache.m_programRefs.value(dnaA); - QCOMPARE(refs3.size(), 0); - QCOMPARE(cache.m_pendingRemoval.size(), 1); - QCOMPARE(cache.m_pendingRemoval.first(), dnaA); -} - -void tst_ShaderCache::purge() -{ - // GIVEN - ShaderCache cache; - - // WHEN we add 2 references and remove one and purge - auto dnaA = ProgramDNA(12345); - auto nodeIdA = QNodeId::createId(); - auto shaderProgramA = new QOpenGLShaderProgram; - QPointer progPointer(shaderProgramA); - cache.insert(dnaA, nodeIdA, shaderProgramA); - auto cachedProgramA = cache.getShaderProgramAndAddRef(dnaA, nodeIdA); - - auto nodeIdA2 = QNodeId::createId(); - auto cachedProgramA2 = cache.getShaderProgramAndAddRef(dnaA, nodeIdA2); - - cache.removeRef(dnaA, nodeIdA); - cache.purge(); - - // THEN no removal - QCOMPARE(cachedProgramA, shaderProgramA); - QCOMPARE(cachedProgramA2, shaderProgramA); - QCOMPARE(cache.m_programHash.size(), 1); - QCOMPARE(cache.m_programRefs.size(), 1); - QCOMPARE(cache.m_pendingRemoval.isEmpty(), true); - - // WHEN we remove final ref and purge - cache.removeRef(dnaA, nodeIdA2); - cache.purge(); - - // THEN shader program is removed from cache and deleted - QCOMPARE(cache.m_programHash.isEmpty(), true); - QCOMPARE(cache.m_programRefs.isEmpty(), true); - QCOMPARE(progPointer.isNull(), true); -} - -void tst_ShaderCache::destruction() -{ - // GIVEN - auto cache = new ShaderCache; - - // WHEN - auto dnaA = ProgramDNA(12345); - auto nodeIdA = QNodeId::createId(); - auto shaderProgramA = new QOpenGLShaderProgram; - QPointer progPointerA(shaderProgramA); - - auto dnaB = ProgramDNA(67890); - auto nodeIdB = QNodeId::createId(); - auto shaderProgramB = new QOpenGLShaderProgram; - QPointer progPointerB(shaderProgramB); - - cache->insert(dnaA, nodeIdA, shaderProgramA); - cache->insert(dnaB, nodeIdB, shaderProgramB); - delete cache; - - // THEN - QCOMPARE(progPointerA.isNull(), true); - QCOMPARE(progPointerB.isNull(), true); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -QTEST_APPLESS_MAIN(Qt3DRender::Render::tst_ShaderCache) - -#include "tst_shadercache.moc" -- cgit v1.2.3 From 17822c91e7f128b5d9af525cd638c9a4d35ea8fb Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Thu, 24 Aug 2017 07:20:26 +0200 Subject: QShaderProgram: add a format property Can be either GLSL (default) or SPIRV at the moment. This variable will be used by the rendering backend to know what type of shader code was provided (e.g with Vulkan, the GLSL could be internally converted to SPIRV) Change-Id: I1f9b734a675c581ef0721edc4464e466a18afbb0 Reviewed-by: Paul Lemire --- .../imports/render/qt3dquick3drenderplugin.cpp | 1 + src/render/materialsystem/qshaderprogram.cpp | 44 ++++++++++++++- src/render/materialsystem/qshaderprogram.h | 11 ++++ src/render/materialsystem/qshaderprogram_p.h | 2 + src/render/materialsystem/shader.cpp | 13 +++++ src/render/materialsystem/shader_p.h | 4 ++ .../render/qshaderprogram/tst_qshaderprogram.cpp | 65 ++++++++++++++++++++++ tests/auto/render/shader/tst_shader.cpp | 48 +++++++++++++++- 8 files changed, 185 insertions(+), 3 deletions(-) diff --git a/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp b/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp index e47d28f7c..8acd71715 100644 --- a/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp +++ b/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp @@ -187,6 +187,7 @@ void Qt3DQuick3DRenderPlugin::registerTypes(const char *uri) Qt3DRender::Quick::registerExtendedType("QRenderPass", "Qt3D.Render/RenderPass", uri, 2, 0, "RenderPass"); qmlRegisterType(uri, 2, 0, "ShaderProgram"); qmlRegisterType(uri, 2, 9, "ShaderProgram"); + qmlRegisterType(uri, 2, 15, "ShaderProgram"); qmlRegisterType(uri, 2, 10, "ShaderProgramBuilder"); qmlRegisterType(uri, 2, 13, "ShaderProgramBuilder"); qmlRegisterUncreatableType(uri, 2, 0, "QShaderData", "Quick3D should instantiate Quick3DShaderData only"); diff --git a/src/render/materialsystem/qshaderprogram.cpp b/src/render/materialsystem/qshaderprogram.cpp index c4e14ea2c..49117dd98 100644 --- a/src/render/materialsystem/qshaderprogram.cpp +++ b/src/render/materialsystem/qshaderprogram.cpp @@ -332,6 +332,17 @@ \value Error An error occurred while compiling the shader */ +/*! + \enum QShaderProgram::Format + + This enum identifies the format of the shader code used. + + \value GLSL OpenGL + \value SPIRV Vulkan, OpenGL 5 + + \since 5.15 +*/ + QT_BEGIN_NAMESPACE namespace Qt3DRender { @@ -339,6 +350,7 @@ namespace Qt3DRender { QShaderProgramPrivate::QShaderProgramPrivate() : QNodePrivate() , m_status(QShaderProgram::NotReady) + , m_format(QShaderProgram::GLSL) { } @@ -617,7 +629,7 @@ QString QShaderProgram::log() const } /*! - \qmlproperty string ShaderProgram::status + \qmlproperty enumeration ShaderProgram::status Holds the status of the current shader program. */ @@ -635,6 +647,35 @@ QShaderProgram::Status QShaderProgram::status() const return d->m_status; } +void QShaderProgram::setFormat(QShaderProgram::Format format) +{ + Q_D(QShaderProgram); + if (format != d->m_format) { + d->m_format = format; + emit formatChanged(format); + } +} + +/*! + \qmlproperty enumeration ShaderProgram::format + \since 5.15 + + Holds the format of the code provided on the ShaderProgram. + The default is ShaderProgram.GLSL +*/ +/*! + \property QShaderProgram::format + \since 5.15 + + Holds the format of the code provided on the ShaderProgram. + The default is ShaderProgram.GLSL +*/ +QShaderProgram::Format QShaderProgram::format() const +{ + Q_D(const QShaderProgram); + return d->m_format; +} + QByteArray QShaderProgramPrivate::deincludify(const QString &filePath) { QFile f(filePath); @@ -699,6 +740,7 @@ Qt3DCore::QNodeCreatedChangeBasePtr QShaderProgram::createNodeCreationChange() c data.geometryShaderCode = d->m_geometryShaderCode; data.fragmentShaderCode = d->m_fragmentShaderCode; data.computeShaderCode = d->m_computeShaderCode; + data.format = d->m_format; return creationChange; } diff --git a/src/render/materialsystem/qshaderprogram.h b/src/render/materialsystem/qshaderprogram.h index 49c1076e5..1fc40a216 100644 --- a/src/render/materialsystem/qshaderprogram.h +++ b/src/render/materialsystem/qshaderprogram.h @@ -60,6 +60,7 @@ class Q_3DRENDERSHARED_EXPORT QShaderProgram : public Qt3DCore::QNode Q_PROPERTY(QByteArray computeShaderCode READ computeShaderCode WRITE setComputeShaderCode NOTIFY computeShaderCodeChanged) Q_PROPERTY(QString log READ log NOTIFY logChanged REVISION 9) Q_PROPERTY(Status status READ status NOTIFY statusChanged REVISION 9) + Q_PROPERTY(Format format READ format WRITE setFormat NOTIFY formatChanged REVISION 15) public: explicit QShaderProgram(Qt3DCore::QNode *parent = nullptr); @@ -82,6 +83,12 @@ public: }; Q_ENUM(Status) // LCOV_EXCL_LINE + enum Format { + GLSL = 0, + SPIRV + }; + Q_ENUM(Format) // LCOV_EXCL_LINE + // Source code in-line QByteArray vertexShaderCode() const; QByteArray tessellationControlShaderCode() const; @@ -96,6 +103,9 @@ public: QString log() const; Status status() const; + void setFormat(Format format); + Format format() const; + Q_INVOKABLE static QByteArray loadSource(const QUrl &sourceUrl); public Q_SLOTS: @@ -115,6 +125,7 @@ Q_SIGNALS: void computeShaderCodeChanged(const QByteArray &computeShaderCode); void logChanged(const QString &log); void statusChanged(Status status); + void formatChanged(Format format); protected: explicit QShaderProgram(QShaderProgramPrivate &dd, Qt3DCore::QNode *parent = nullptr); diff --git a/src/render/materialsystem/qshaderprogram_p.h b/src/render/materialsystem/qshaderprogram_p.h index f09b2a30e..d377ef039 100644 --- a/src/render/materialsystem/qshaderprogram_p.h +++ b/src/render/materialsystem/qshaderprogram_p.h @@ -72,6 +72,7 @@ public: QByteArray m_computeShaderCode; QString m_log; QShaderProgram::Status m_status; + QShaderProgram::Format m_format; void setLog(const QString &log); void setStatus(QShaderProgram::Status status); @@ -88,6 +89,7 @@ struct QShaderProgramData QByteArray geometryShaderCode; QByteArray fragmentShaderCode; QByteArray computeShaderCode; + QShaderProgram::Format format; }; } // namespace Qt3DRender diff --git a/src/render/materialsystem/shader.cpp b/src/render/materialsystem/shader.cpp index 00d9d334f..d0069bb4a 100644 --- a/src/render/materialsystem/shader.cpp +++ b/src/render/materialsystem/shader.cpp @@ -86,6 +86,7 @@ Shader::Shader() : BackendNode(ReadWrite) , m_requiresFrontendSync(false) , m_status(QShaderProgram::NotReady) + , m_format(QShaderProgram::GLSL) , m_dirty(false) { m_shaderCode.resize(static_cast(QShaderProgram::Compute) + 1); @@ -99,6 +100,7 @@ void Shader::cleanup() { QBackendNode::setEnabled(false); m_status = QShaderProgram::NotReady; + m_format = QShaderProgram::GLSL; m_log.clear(); m_dirty = false; } @@ -121,6 +123,7 @@ void Shader::syncFromFrontEnd(const QNode *frontEnd, bool firstTime) if (code != m_shaderCode.value(shaderType)) setShaderCode(shaderType, code); } + setFormat(node->format()); } void Shader::setShaderCode(QShaderProgram::ShaderType type, const QByteArray &code) @@ -135,6 +138,16 @@ void Shader::setShaderCode(QShaderProgram::ShaderType type, const QByteArray &co markDirty(AbstractRenderer::ShadersDirty); } +void Shader::setFormat(QShaderProgram::Format format) +{ + if (format == m_format) + return; + m_format = format; + m_dirty = true; + setStatus(QShaderProgram::NotReady); + markDirty(AbstractRenderer::ShadersDirty); +} + QVector Shader::shaderCode() const { return m_shaderCode; diff --git a/src/render/materialsystem/shader_p.h b/src/render/materialsystem/shader_p.h index 8b1941d2c..23d57f25d 100644 --- a/src/render/materialsystem/shader_p.h +++ b/src/render/materialsystem/shader_p.h @@ -105,6 +105,9 @@ public: inline QString log() const { return m_log; } inline QShaderProgram::Status status() const { return m_status; } + + void setFormat(QShaderProgram::Format format); + QShaderProgram::Format format() const { return m_format; } bool isDirty() const { return m_dirty; } void unsetDirty() { m_dirty = false; } @@ -117,6 +120,7 @@ private: QString m_log; QShaderProgram::Status m_status; bool m_requiresFrontendSync; + QShaderProgram::Format m_format; bool m_dirty; void initializeFromReference(const Shader &other); diff --git a/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp b/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp index 18dd1306a..15be26e8e 100644 --- a/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp +++ b/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp @@ -45,6 +45,13 @@ class tst_QShaderProgram : public Qt3DRender::QShaderProgram { Q_OBJECT +public: + tst_QShaderProgram() + : Qt3DRender::QShaderProgram() + { + qRegisterMetaType("Format"); + } + private Q_SLOTS: void checkDefaultConstruction() @@ -61,6 +68,7 @@ private Q_SLOTS: QCOMPARE(shaderProgram.computeShaderCode(), QByteArray()); QCOMPARE(shaderProgram.log(), QString()); QCOMPARE(shaderProgram.status(), Qt3DRender::QShaderProgram::NotReady); + QCOMPARE(shaderProgram.format(), Qt3DRender::QShaderProgram::GLSL); } void checkPropertyChanges() @@ -182,6 +190,25 @@ private Q_SLOTS: QCOMPARE(shaderProgram.computeShaderCode(), newValue); QCOMPARE(spy.count(), 0); } + { + // WHEN + QSignalSpy spy(&shaderProgram, SIGNAL(formatChanged(Format))); + const QShaderProgram::Format newValue = QShaderProgram::SPIRV; + shaderProgram.setFormat(newValue); + + // THEN + QVERIFY(spy.isValid()); + QCOMPARE(shaderProgram.format(), newValue); + QCOMPARE(spy.count(), 1); + + // WHEN + spy.clear(); + shaderProgram.setFormat(newValue); + + // THEN + QCOMPARE(shaderProgram.format(), newValue); + QCOMPARE(spy.count(), 0); + } } void checkCreationData() @@ -195,6 +222,7 @@ private Q_SLOTS: shaderProgram.setGeometryShaderCode(QByteArrayLiteral("Geometry")); shaderProgram.setFragmentShaderCode(QByteArrayLiteral("Fragment")); shaderProgram.setComputeShaderCode(QByteArrayLiteral("Compute")); + shaderProgram.setFormat(QShaderProgram::SPIRV); // WHEN QVector creationChanges; @@ -217,6 +245,7 @@ private Q_SLOTS: QCOMPARE(shaderProgram.geometryShaderCode(), cloneData.geometryShaderCode); QCOMPARE(shaderProgram.fragmentShaderCode(), cloneData.fragmentShaderCode); QCOMPARE(shaderProgram.computeShaderCode(), cloneData.computeShaderCode); + QCOMPARE(shaderProgram.format(), cloneData.format); QCOMPARE(shaderProgram.id(), creationChangeData->subjectId()); QCOMPARE(shaderProgram.isEnabled(), true); QCOMPARE(shaderProgram.isEnabled(), creationChangeData->isNodeEnabled()); @@ -532,6 +561,42 @@ private Q_SLOTS: // THEN QVERIFY(mainContent.indexOf(includedContent) == 0); } + + void checkFormatPropertyUpdate() + { + // GIVEN + TestArbiter arbiter; + Qt3DRender::QShaderProgram shaderProgram; + arbiter.setArbiterOnNode(&shaderProgram); + + QSignalSpy spy(&shaderProgram, SIGNAL(formatChanged(Format))); + + // THEN + QVERIFY(spy.isValid()); + + { + // WHEN + shaderProgram.setFormat(QShaderProgram::SPIRV); + QCoreApplication::processEvents(); + + // THEN + QCOMPARE(spy.count(), 1); + QCOMPARE(arbiter.events.size(), 0); + + spy.clear(); + } + + { + // WHEN + shaderProgram.setFormat(QShaderProgram::SPIRV); + QCoreApplication::processEvents(); + + // THEN + QCOMPARE(spy.count(), 0); + QCOMPARE(arbiter.events.size(), 0); + } + } + }; QTEST_MAIN(tst_QShaderProgram) diff --git a/tests/auto/render/shader/tst_shader.cpp b/tests/auto/render/shader/tst_shader.cpp index 3f0714907..a1f837010 100644 --- a/tests/auto/render/shader/tst_shader.cpp +++ b/tests/auto/render/shader/tst_shader.cpp @@ -42,15 +42,17 @@ private slots: void cleanupLeavesACoherentState(); void dealWithPropertyChanges_data(); void dealWithPropertyChanges(); + void dealWithFormatChanges(); void checkSetRendererDirtyOnInitialization(); void allowToChangeShaderCode_data(); void allowToChangeShaderCode(); }; -Qt3DRender::QShaderProgram *createFrontendShader() +Qt3DRender::QShaderProgram *createFrontendShader(Qt3DRender::QShaderProgram::Format format = Qt3DRender::QShaderProgram::GLSL) { Qt3DRender::QShaderProgram *shader = new Qt3DRender::QShaderProgram(); + shader->setFormat(format); shader->setVertexShaderCode(QByteArrayLiteral( "#version 150"\ @@ -80,6 +82,7 @@ void tst_RenderShader::hasCoherentInitialState() Qt3DRender::Render::Shader *shader = new Qt3DRender::Render::Shader(); QCOMPARE(shader->status(), Qt3DRender::QShaderProgram::NotReady); + QCOMPARE(shader->format(), Qt3DRender::QShaderProgram::GLSL); QVERIFY(shader->log().isEmpty()); QCOMPARE(shader->isDirty(), false); } @@ -97,11 +100,12 @@ void tst_RenderShader::matchesFrontendPeer() for (int i = Qt3DRender::QShaderProgram::Vertex; i <= Qt3DRender::QShaderProgram::Compute; ++i) QCOMPARE(backend.shaderCode()[i], frontend->shaderCode(static_cast(i))); + QCOMPARE(backend.format(), frontend->format()); } void tst_RenderShader::cleanupLeavesACoherentState() { - QScopedPointer frontend(createFrontendShader()); + QScopedPointer frontend(createFrontendShader(Qt3DRender::QShaderProgram::SPIRV)); TestRenderer renderer; Qt3DRender::Render::Shader shader; @@ -112,6 +116,7 @@ void tst_RenderShader::cleanupLeavesACoherentState() QCOMPARE(shader.isDirty(), false); QCOMPARE(shader.status(), Qt3DRender::QShaderProgram::NotReady); + QCOMPARE(shader.format(), Qt3DRender::QShaderProgram::GLSL); } void tst_RenderShader::dealWithPropertyChanges_data() @@ -176,6 +181,45 @@ void tst_RenderShader::dealWithPropertyChanges() QCOMPARE(backend.isDirty(), true); } +void tst_RenderShader::dealWithFormatChanges() +{ + // GIVEN + Qt3DRender::Render::Shader backend; + Qt3DRender::QShaderProgram shader; + TestRenderer renderer; + backend.setRenderer(&renderer); + simulateInitializationSync(&shader, &backend); + + // WHEN + shader.setFormat(Qt3DRender::QShaderProgram::GLSL); + backend.syncFromFrontEnd(&shader, false); + + // THEN + QCOMPARE(backend.format(), Qt3DRender::QShaderProgram::GLSL); + QCOMPARE(backend.isDirty(), false); + QCOMPARE(renderer.dirtyBits(), 0); + + // WHEN + shader.setFormat(Qt3DRender::QShaderProgram::SPIRV); + backend.syncFromFrontEnd(&shader, false); + + // THEN + QCOMPARE(backend.format(), Qt3DRender::QShaderProgram::SPIRV); + QCOMPARE(renderer.dirtyBits(), Qt3DRender::Render::AbstractRenderer::ShadersDirty); + QCOMPARE(backend.isDirty(), true); + + renderer.resetDirty(); + backend.unsetDirty(); + + // WHEN + shader.setFormat(Qt3DRender::QShaderProgram::SPIRV); + backend.syncFromFrontEnd(&shader, false); + + // THEN + QCOMPARE(backend.isDirty(), false); + QCOMPARE(renderer.dirtyBits(), 0); +} + void tst_RenderShader::checkSetRendererDirtyOnInitialization() { // GIVEN -- cgit v1.2.3 From 1e2f6baf6bdcc647b40d346040b8383cf81a2ef3 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Tue, 17 Oct 2017 14:58:54 +0200 Subject: Renderer: stop passing buffer type around It only make sense to pass it for the bind call Change-Id: I8f0cd204c109b2ff24f4eec320811b6cecaf3873 Reviewed-by: Paul Lemire --- .../opengl/graphicshelpers/submissioncontext.cpp | 18 +++++++----------- .../opengl/graphicshelpers/submissioncontext_p.h | 4 ++-- src/render/renderers/opengl/renderer/renderer.cpp | 4 ++-- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp index 32852217b..8afec233d 100644 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp +++ b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp @@ -1212,13 +1212,12 @@ bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) const QVector blockToSSBOs = parameterPack.shaderStorageBuffers(); for (const BlockToSSBO b : blockToSSBOs) { Buffer *cpuBuffer = m_renderer->nodeManagers()->bufferManager()->lookupResource(b.m_bufferID); - GLBuffer *ssbo = glBufferForRenderBuffer(cpuBuffer, GLBuffer::ShaderStorageBuffer); - + GLBuffer *ssbo = glBufferForRenderBuffer(cpuBuffer); // bindShaderStorageBlock // This is currently not required as we are introspecting the bindingIndex // value from the shaders and not replacing them, making such a call useless // bindShaderStorageBlock(shader->programId(), b.m_blockIndex, b.m_bindingIndex); - + bindShaderStorageBlock(shader->programId(), b.m_blockIndex, b.m_bindingIndex); // Needed to avoid conflict where the buffer would already // be bound as a VertexArray bindGLBuffer(ssbo, GLBuffer::ShaderStorageBuffer); @@ -1232,7 +1231,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) int uboIndex = 0; for (const BlockToUBO &b : blockToUBOs) { Buffer *cpuBuffer = m_renderer->nodeManagers()->bufferManager()->lookupResource(b.m_bufferID); - GLBuffer *ubo = glBufferForRenderBuffer(cpuBuffer, GLBuffer::UniformBuffer); + GLBuffer *ubo = glBufferForRenderBuffer(cpuBuffer); bindUniformBlock(shader->programId(), b.m_blockIndex, uboIndex); // Needed to avoid conflict where the buffer would already // be bound as a VertexArray @@ -1347,7 +1346,7 @@ void SubmissionContext::specifyAttribute(const Attribute *attribute, void SubmissionContext::specifyIndices(Buffer *buffer) { - GLBuffer *buf = glBufferForRenderBuffer(buffer, GLBuffer::IndexBuffer); + GLBuffer *buf = glBufferForRenderBuffer(buffer); if (!bindGLBuffer(buf, GLBuffer::IndexBuffer)) qCWarning(Backend) << Q_FUNC_INFO << "binding index buffer failed"; @@ -1395,14 +1394,14 @@ bool SubmissionContext::hasGLBufferForBuffer(Buffer *buffer) return (it != m_renderBufferHash.end()); } -GLBuffer *SubmissionContext::glBufferForRenderBuffer(Buffer *buf, GLBuffer::Type type) +GLBuffer *SubmissionContext::glBufferForRenderBuffer(Buffer *buf) { if (!m_renderBufferHash.contains(buf->peerId())) - m_renderBufferHash.insert(buf->peerId(), createGLBufferFor(buf, type)); + m_renderBufferHash.insert(buf->peerId(), createGLBufferFor(buf)); return m_renderer->glResourceManagers()->glBufferManager()->data(m_renderBufferHash.value(buf->peerId())); } -HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer, GLBuffer::Type type) +HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer) { GLBuffer *b = m_renderer->glResourceManagers()->glBufferManager()->getOrCreateResource(buffer->peerId()); // b.setUsagePattern(static_cast(buffer->usage())); @@ -1410,9 +1409,6 @@ HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer, GLBuffer::Type ty if (!b->create(this)) qCWarning(Render::Io) << Q_FUNC_INFO << "buffer creation failed"; - if (!bindGLBuffer(b, type)) - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer binding failed"; - return m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); } diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h b/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h index d2121a3b7..e7a31e6ce 100644 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h +++ b/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h @@ -130,7 +130,7 @@ public: QByteArray downloadBufferContent(Buffer *buffer); void releaseBuffer(Qt3DCore::QNodeId bufferId); bool hasGLBufferForBuffer(Buffer *buffer); - GLBuffer *glBufferForRenderBuffer(Buffer *buf, GLBuffer::Type type); + GLBuffer *glBufferForRenderBuffer(Buffer *buf); // Parameters bool setParameters(ShaderParameterPack ¶meterPack); @@ -171,7 +171,7 @@ private: GLuint updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, bool isActiveRenderTarget); // Buffers - HGLBuffer createGLBufferFor(Buffer *buffer, GLBuffer::Type type); + HGLBuffer createGLBufferFor(Buffer *buffer); void uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool releaseBuffer = false); QByteArray downloadDataFromGLBuffer(Buffer *buffer, GLBuffer *b); bool bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type); diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index d09878315..31db08d1f 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -1320,7 +1320,7 @@ void Renderer::updateGLResources() // Forces creation if it doesn't exit // Also note the binding point doesn't really matter here, we just upload data if (!m_submissionContext->hasGLBufferForBuffer(buffer)) - m_submissionContext->glBufferForRenderBuffer(buffer, GLBuffer::ArrayBuffer); + m_submissionContext->glBufferForRenderBuffer(buffer); // Update the glBuffer data m_submissionContext->updateBuffer(buffer); buffer->unsetDirty(); @@ -2056,7 +2056,7 @@ void Renderer::performDraw(RenderCommand *command) } // Get GLBuffer from Buffer; - GLBuffer *indirectDrawGLBuffer = m_submissionContext->glBufferForRenderBuffer(indirectDrawBuffer, GLBuffer::DrawIndirectBuffer); + GLBuffer *indirectDrawGLBuffer = m_submissionContext->glBufferForRenderBuffer(indirectDrawBuffer); if (Q_UNLIKELY(indirectDrawGLBuffer == nullptr)) { qWarning() << "Invalid Indirect Draw Buffer - failed to retrieve GLBuffer"; return; -- cgit v1.2.3 From f1f387c22dac8748a7edb1f4aa1ea6dac7dfbdfd Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Thu, 8 Mar 2018 15:23:35 +0100 Subject: ResourceAccessor: make it work with the modular renderer architecture This makes Scene2D work again. Tests restored as well. Change-Id: I4082d362c999a674be2debc297d59075f4b7c9e9 Reviewed-by: Paul Lemire --- src/render/backend/abstractrenderer_p.h | 6 +- src/render/backend/backendnode.cpp | 5 +- src/render/backend/backendnode_p.h | 2 +- src/render/backend/nodemanagers.cpp | 7 -- src/render/backend/nodemanagers_p.h | 5 - src/render/backend/resourceaccessor.cpp | 112 ++++++++++------------ src/render/backend/resourceaccessor_p.h | 11 ++- src/render/renderers/opengl/renderer/renderer.cpp | 36 +++++++ src/render/renderers/opengl/renderer/renderer_p.h | 10 ++ tests/auto/render/commons/testrenderer.h | 16 +++- 10 files changed, 125 insertions(+), 85 deletions(-) diff --git a/src/render/backend/abstractrenderer_p.h b/src/render/backend/abstractrenderer_p.h index 74457e79f..3febf691e 100644 --- a/src/render/backend/abstractrenderer_p.h +++ b/src/render/backend/abstractrenderer_p.h @@ -65,6 +65,7 @@ QT_BEGIN_NAMESPACE class QSurface; class QSize; class QScreen; +class QOpenGLTexture; namespace Qt3DCore { class QAbstractFrameAdvanceService; @@ -87,6 +88,7 @@ class RenderSettings; class BackendNode; class OffscreenSurfaceHelper; class Shader; +class RenderBackendResourceAccessor; class Q_3DRENDERSHARED_PRIVATE_EXPORT AbstractRenderer { @@ -177,10 +179,12 @@ public: virtual QVariant executeCommand(const QStringList &args) = 0; - // For QtQuick rendering + // For QtQuick rendering (Scene2D) virtual void setOpenGLContext(QOpenGLContext *ctx) = 0; virtual void setScreen(QScreen *) {} virtual QScreen *screen() const { return nullptr; } + virtual bool accessOpenGLTexture(Qt3DCore::QNodeId nodeId, QOpenGLTexture **texture, QMutex **lock, bool readonly) = 0; + virtual QSharedPointer resourceAccessor() const = 0; virtual void setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) = 0; virtual QSurfaceFormat format() = 0; diff --git a/src/render/backend/backendnode.cpp b/src/render/backend/backendnode.cpp index 642f6e44d..f85ece1b9 100644 --- a/src/render/backend/backendnode.cpp +++ b/src/render/backend/backendnode.cpp @@ -82,10 +82,9 @@ void BackendNode::markDirty(AbstractRenderer::BackendNodeDirtySet changes) m_renderer->markDirty(changes, this); } -QSharedPointer BackendNode::resourceAccessor() +QSharedPointer BackendNode::resourceAccessor() const { - Render::Renderer *r = static_cast(renderer()); - return r->nodeManagers()->resourceAccessor(); + return m_renderer->resourceAccessor(); } void BackendNode::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) diff --git a/src/render/backend/backendnode_p.h b/src/render/backend/backendnode_p.h index 37f8305af..3b880f759 100644 --- a/src/render/backend/backendnode_p.h +++ b/src/render/backend/backendnode_p.h @@ -81,7 +81,7 @@ public: void setRenderer(AbstractRenderer *renderer); AbstractRenderer *renderer() const; - QSharedPointer resourceAccessor(); + QSharedPointer resourceAccessor() const; protected: explicit BackendNode(Qt3DCore::QBackendNodePrivate &dd); diff --git a/src/render/backend/nodemanagers.cpp b/src/render/backend/nodemanagers.cpp index 8603d4fb9..df660a19e 100644 --- a/src/render/backend/nodemanagers.cpp +++ b/src/render/backend/nodemanagers.cpp @@ -46,7 +46,6 @@ #include #include #include -#include QT_BEGIN_NAMESPACE @@ -92,7 +91,6 @@ NodeManagers::NodeManagers() , m_skeletonManager(new SkeletonManager()) , m_jointManager(new JointManager()) , m_shaderImageManager(new ShaderImageManager()) - , m_resourceAccessor(new ResourceAccessor(this)) { } @@ -139,11 +137,6 @@ NodeManagers::~NodeManagers() delete m_shaderImageManager; } -QSharedPointer NodeManagers::resourceAccessor() -{ - return m_resourceAccessor; -} - template<> CameraManager *NodeManagers::manager() const noexcept { diff --git a/src/render/backend/nodemanagers_p.h b/src/render/backend/nodemanagers_p.h index 62a73b510..e6f7469de 100644 --- a/src/render/backend/nodemanagers_p.h +++ b/src/render/backend/nodemanagers_p.h @@ -140,7 +140,6 @@ class Skeleton; class Joint; class ShaderImage; -class ResourceAccessor; class Q_3DRENDERSHARED_PRIVATE_EXPORT NodeManagers { @@ -219,8 +218,6 @@ public: inline JointManager *jointManager() const noexcept { return m_jointManager; } inline ShaderImageManager *shaderImageManager() const noexcept { return m_shaderImageManager; } - QSharedPointer resourceAccessor(); - private: CameraManager *m_cameraManager; EntityManager *m_renderNodesManager; @@ -258,8 +255,6 @@ private: SkeletonManager *m_skeletonManager; JointManager *m_jointManager; ShaderImageManager *m_shaderImageManager; - - QSharedPointer m_resourceAccessor; }; // Specializations diff --git a/src/render/backend/resourceaccessor.cpp b/src/render/backend/resourceaccessor.cpp index af19546b7..846caca58 100644 --- a/src/render/backend/resourceaccessor.cpp +++ b/src/render/backend/resourceaccessor.cpp @@ -40,10 +40,11 @@ #include #include -#include +#include #include #include +#include #include QT_BEGIN_NAMESPACE @@ -56,70 +57,63 @@ RenderBackendResourceAccessor::~RenderBackendResourceAccessor() } -ResourceAccessor::ResourceAccessor(NodeManagers *mgr) -// : m_glTextureManager(mgr->glTextureManager()) -// , m_textureManager(mgr->textureManager()) -// , m_attachmentManager(mgr->attachmentManager()) -// , m_entityManager(mgr->renderNodesManager()) +ResourceAccessor::ResourceAccessor(AbstractRenderer *renderer, NodeManagers *mgr) + : m_renderer(renderer) + , m_textureManager(mgr->textureManager()) + , m_attachmentManager(mgr->attachmentManager()) + , m_entityManager(mgr->renderNodesManager()) { } // called by render plugins from arbitrary thread -bool ResourceAccessor::accessResource(ResourceType type, Qt3DCore::QNodeId nodeId, void **handle, QMutex **lock) +bool ResourceAccessor::accessResource(ResourceType type, + Qt3DCore::QNodeId nodeId, + void **handle, + QMutex **lock) { -// switch (type) { - -// case RenderBackendResourceAccessor::OGLTextureWrite: -// Q_FALLTHROUGH(); -// case RenderBackendResourceAccessor::OGLTextureRead: -// { -// Texture *tex = m_textureManager->lookupResource(nodeId); -// if (!tex) -// return false; - -// GLTexture *glTex = m_glTextureManager->lookupResource(tex->peerId()); -// if (!glTex) -// return false; - -// if (glTex->isDirty()) -// return false; - -// if (type == RenderBackendResourceAccessor::OGLTextureWrite) -// glTex->setExternalRenderingEnabled(true); - -// QOpenGLTexture **glTextureHandle = reinterpret_cast(handle); -// *glTextureHandle = glTex->getGLTexture(); - -// if (type == RenderBackendResourceAccessor::OGLTextureWrite) -// *lock = glTex->externalRenderingLock(); - -// return true; -// } - -// case RenderBackendResourceAccessor::OutputAttachment: { -// RenderTargetOutput *output = m_attachmentManager->lookupResource(nodeId); -// if (output) { -// Attachment **attachmentData = reinterpret_cast(handle); -// *attachmentData = output->attachment(); -// return true; -// } -// break; -// } - -// case RenderBackendResourceAccessor::EntityHandle: { -// Entity *entity = m_entityManager->lookupResource(nodeId); -// if (entity) { -// Entity **pEntity = reinterpret_cast(handle); -// *pEntity = entity; -// return true; -// } -// break; -// } - -// default: -// break; -// } + switch (type) { + + // This is purely made so that Scene2D works, this should be completely + // redesigned to avoid introducing this kind of coupling and reliance on + // OpenGL + case RenderBackendResourceAccessor::OGLTextureWrite: + Q_FALLTHROUGH(); + case RenderBackendResourceAccessor::OGLTextureRead: + { + if (m_renderer->api() != AbstractRenderer::OpenGL) { + qWarning() << "Renderer plugin is not compatible with Scene2D"; + return false; + } + return m_renderer->accessOpenGLTexture(nodeId, + reinterpret_cast(handle), + lock, + type == RenderBackendResourceAccessor::OGLTextureRead); + } + + case RenderBackendResourceAccessor::OutputAttachment: { + RenderTargetOutput *output = m_attachmentManager->lookupResource(nodeId); + if (output) { + Attachment **attachmentData = reinterpret_cast(handle); + *attachmentData = output->attachment(); + return true; + } + break; + } + + case RenderBackendResourceAccessor::EntityHandle: { + Entity *entity = m_entityManager->lookupResource(nodeId); + if (entity) { + Entity **pEntity = reinterpret_cast(handle); + *pEntity = entity; + return true; + } + break; + } + + default: + break; + } return false; } diff --git a/src/render/backend/resourceaccessor_p.h b/src/render/backend/resourceaccessor_p.h index 6ceb8677b..0645ecfba 100644 --- a/src/render/backend/resourceaccessor_p.h +++ b/src/render/backend/resourceaccessor_p.h @@ -68,6 +68,7 @@ class AttachmentManager; class GLTextureManager; class EntityManager; class NodeManagers; +class AbstractRenderer; class RenderBackendResourceAccessor { @@ -86,13 +87,13 @@ public: class Q_3DRENDERSHARED_PRIVATE_EXPORT ResourceAccessor : public RenderBackendResourceAccessor { public: - ResourceAccessor(NodeManagers *mgr); + ResourceAccessor(AbstractRenderer *renderer, NodeManagers *mgr); bool accessResource(ResourceType type, Qt3DCore::QNodeId nodeId, void **handle, QMutex **lock) final; private: -// GLTextureManager *m_glTextureManager; -// TextureManager *m_textureManager; -// AttachmentManager *m_attachmentManager; -// EntityManager *m_entityManager; + AbstractRenderer *m_renderer; + TextureManager *m_textureManager; + AttachmentManager *m_attachmentManager; + EntityManager *m_entityManager; }; } // namespace Render diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp index 31db08d1f..680040f54 100644 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ b/src/render/renderers/opengl/renderer/renderer.cpp @@ -99,6 +99,7 @@ #endif #include +#include #include #include @@ -378,6 +379,7 @@ void Renderer::setNodeManagers(NodeManagers *managers) { m_nodesManager = managers; m_glResourceManagers = new GLResourceManagers(); + m_scene2DResourceAccessor.reset(new ResourceAccessor(this, m_nodesManager)); m_updateShaderDataTransformJob->setManagers(m_nodesManager); m_cleanupJob->setManagers(m_nodesManager); @@ -449,6 +451,39 @@ QScreen *Renderer::screen() const return m_screen; } +bool Renderer::accessOpenGLTexture(Qt3DCore::QNodeId nodeId, + QOpenGLTexture **texture, + QMutex **lock, + bool readonly) +{ + Texture *tex = m_nodesManager->textureManager()->lookupResource(nodeId); + if (!tex) + return false; + + GLTexture *glTex = m_glResourceManagers->glTextureManager()->lookupResource(tex->peerId()); + if (!glTex) + return false; + + if (glTex->isDirty()) + return false; + + if (!readonly) + glTex->setExternalRenderingEnabled(true); + + GLTexture::TextureUpdateInfo texInfo = glTex->createOrUpdateGLTexture(); + *texture = texInfo.texture; + + if (!readonly) + *lock = glTex->externalRenderingLock(); + + return true; +} + +QSharedPointer Renderer::resourceAccessor() const +{ + return m_scene2DResourceAccessor; +} + // Called in RenderThread context by the run method of RenderThread // RenderThread has locked the mutex already and unlocks it when this // method termintates @@ -885,6 +920,7 @@ void Renderer::enqueueRenderView(Render::RenderView *renderView, int submitOrder } bool Renderer::canRender() const + { // Make sure that we've not been told to terminate if (m_renderThread && !m_running.loadRelaxed()) { diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h index 557089b19..e8929e67a 100644 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ b/src/render/renderers/opengl/renderer/renderer_p.h @@ -155,6 +155,7 @@ class PickEventFilter; class NodeManagers; class GLResourceManagers; class GLShader; +class ResourceAccessor; class UpdateLevelOfDetailJob; typedef QSharedPointer UpdateLevelOfDetailJobPtr; @@ -285,7 +286,15 @@ public: bool requiresVAOAttributeUpdate(Geometry *geometry, const RenderCommand *command) const; + // For Scene2D rendering void setOpenGLContext(QOpenGLContext *context) override; + bool accessOpenGLTexture(Qt3DCore::QNodeId nodeId, + QOpenGLTexture **texture, + QMutex **lock, + bool readonly) override; + QSharedPointer resourceAccessor() const override; + + const GraphicsApiFilterData *contextInfo() const; SubmissionContext *submissionContext() const; @@ -451,6 +460,7 @@ private: QVector m_frameGraphLeaves; QScreen *m_screen = nullptr; + QSharedPointer m_scene2DResourceAccessor; Debug::ImGuiRenderer *m_imGuiRenderer; QList> m_frameMouseEvents; diff --git a/tests/auto/render/commons/testrenderer.h b/tests/auto/render/commons/testrenderer.h index 1241bb0e0..7b3e0a387 100644 --- a/tests/auto/render/commons/testrenderer.h +++ b/tests/auto/render/commons/testrenderer.h @@ -30,6 +30,7 @@ #define TESTRENDERER_H #include +#include QT_BEGIN_NAMESPACE @@ -42,11 +43,15 @@ public: void dumpInfo() const override {} API api() const override { return AbstractRenderer::OpenGL; } qint64 time() const override { return 0; } - void setTime(qint64 time) override { Q_UNUSED(time) } + void setTime(qint64 time) override { Q_UNUSED(time); } + void setNodeManagers(Qt3DRender::Render::NodeManagers *m) override + { + m_managers = m; + m_resourceAccessor.reset(new Qt3DRender::Render::ResourceAccessor(this, m_managers)); + } + void setServices(Qt3DCore::QServiceLocator *services) override { Q_UNUSED(services); } + void setSurfaceExposed(bool exposed) override { Q_UNUSED(exposed); } void setJobsInLastFrame(int jobsInLastFrame) override { Q_UNUSED(jobsInLastFrame) } - void setNodeManagers(Qt3DRender::Render::NodeManagers *m) override { m_managers = m; } - void setServices(Qt3DCore::QServiceLocator *services) override { Q_UNUSED(services) } - void setSurfaceExposed(bool exposed) override { Q_UNUSED(exposed) } Qt3DRender::Render::NodeManagers *nodeManagers() const override { return m_managers; } Qt3DCore::QServiceLocator *services() const override { return nullptr; } void initialize() override {} @@ -87,12 +92,15 @@ public: QSurfaceFormat format() override; void setOpenGLContext(QOpenGLContext *) override {} + bool accessOpenGLTexture(Qt3DCore::QNodeId, QOpenGLTexture **, QMutex **, bool) override { return false; } + QSharedPointer resourceAccessor() const override { return m_resourceAccessor; } void loadShader(Qt3DRender::Render::Shader *, Qt3DRender::Render::HShader) override {} protected: Qt3DRender::Render::AbstractRenderer::BackendNodeDirtySet m_changes; Qt3DRender::Render::NodeManagers *m_managers = nullptr; + QSharedPointer m_resourceAccessor; }; QT_END_NAMESPACE -- cgit v1.2.3 From 0e115ff000fb294de8519bf5b39beee0d6bfa605 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 12 Mar 2018 08:32:35 +0100 Subject: Make the OpenGL renderer a plugin By default the QRenderAspect will try to load this plugin Change-Id: Ie55e207fb8e6d0b64f717bbb99699eb669eaa3f2 Task-number: QTBUG-61151 Reviewed-by: Mike Krus --- src/core/resources/qresourcemanager_p.h | 39 +- src/core/transforms/matrix4x4_avx2_p.h | 1 + src/core/transforms/matrix4x4_sse_p.h | 1 + src/plugins/renderers/dummy/dummy.pro | 0 src/plugins/renderers/opengl/debug/debug.pri | 10 + .../renderers/opengl/debug/imguirenderer.cpp | 705 ++++++ .../renderers/opengl/debug/imguirenderer_p.h | 136 ++ .../opengl/graphicshelpers/graphicscontext.cpp | 1028 ++++++++ .../opengl/graphicshelpers/graphicscontext_p.h | 264 ++ .../opengl/graphicshelpers/graphicshelperes2.cpp | 1034 ++++++++ .../opengl/graphicshelpers/graphicshelperes2_p.h | 182 ++ .../opengl/graphicshelpers/graphicshelperes3.cpp | 768 ++++++ .../opengl/graphicshelpers/graphicshelperes3_1.cpp | 367 +++ .../opengl/graphicshelpers/graphicshelperes3_1_p.h | 87 + .../opengl/graphicshelpers/graphicshelperes3_2.cpp | 193 ++ .../opengl/graphicshelpers/graphicshelperes3_2_p.h | 84 + .../opengl/graphicshelpers/graphicshelperes3_p.h | 108 + .../opengl/graphicshelpers/graphicshelpergl2.cpp | 935 +++++++ .../opengl/graphicshelpers/graphicshelpergl2_p.h | 183 ++ .../opengl/graphicshelpers/graphicshelpergl3_2.cpp | 1245 ++++++++++ .../opengl/graphicshelpers/graphicshelpergl3_2_p.h | 185 ++ .../opengl/graphicshelpers/graphicshelpergl3_3.cpp | 1240 ++++++++++ .../opengl/graphicshelpers/graphicshelpergl3_3_p.h | 185 ++ .../opengl/graphicshelpers/graphicshelpergl4.cpp | 1442 +++++++++++ .../opengl/graphicshelpers/graphicshelpergl4_p.h | 182 ++ .../graphicshelpers/graphicshelperinterface_p.h | 203 ++ .../opengl/graphicshelpers/graphicshelpers.pri | 33 + .../graphicshelpers/imagesubmissioncontext.cpp | 306 +++ .../graphicshelpers/imagesubmissioncontext_p.h | 95 + .../opengl/graphicshelpers/qgraphicsutils_p.h | 410 ++++ .../opengl/graphicshelpers/submissioncontext.cpp | 1574 ++++++++++++ .../opengl/graphicshelpers/submissioncontext_p.h | 234 ++ .../graphicshelpers/texturesubmissioncontext.cpp | 225 ++ .../graphicshelpers/texturesubmissioncontext_p.h | 106 + src/plugins/renderers/opengl/io/glbuffer.cpp | 169 ++ src/plugins/renderers/opengl/io/glbuffer_p.h | 110 + src/plugins/renderers/opengl/io/io.pri | 8 + .../opengl/jobs/filtercompatibletechniquejob.cpp | 95 + .../opengl/jobs/filtercompatibletechniquejob_p.h | 92 + src/plugins/renderers/opengl/jobs/jobs.pri | 17 + .../opengl/jobs/materialparametergathererjob.cpp | 131 + .../opengl/jobs/materialparametergathererjob_p.h | 107 + .../renderers/opengl/jobs/renderviewbuilderjob.cpp | 82 + .../renderers/opengl/jobs/renderviewbuilderjob_p.h | 96 + .../opengl/jobs/renderviewcommandbuilderjob.cpp | 81 + .../opengl/jobs/renderviewcommandbuilderjob_p.h | 96 + .../opengl/jobs/renderviewcommandupdaterjob.cpp | 82 + .../opengl/jobs/renderviewcommandupdaterjob_p.h | 103 + .../opengl/jobs/renderviewinitializerjob.cpp | 104 + .../opengl/jobs/renderviewinitializerjob_p.h | 107 + .../renderers/opengl/jobs/renderviewjobutils.cpp | 574 +++++ .../renderers/opengl/jobs/renderviewjobutils_p.h | 188 ++ src/plugins/renderers/opengl/main.cpp | 59 + .../renderers/opengl/managers/gl_handle_types_p.h | 76 + .../opengl/managers/glresourcemanagers.cpp | 71 + .../opengl/managers/glresourcemanagers_p.h | 135 + src/plugins/renderers/opengl/managers/managers.pri | 8 + src/plugins/renderers/opengl/opengl.pri | 41 + src/plugins/renderers/opengl/opengl.pro | 10 + src/plugins/renderers/opengl/openglrenderer.json | 3 + .../renderers/opengl/renderer/commandexecuter.cpp | 391 +++ .../renderers/opengl/renderer/commandexecuter_p.h | 95 + src/plugins/renderers/opengl/renderer/glfence_p.h | 73 + src/plugins/renderers/opengl/renderer/glshader.cpp | 316 +++ src/plugins/renderers/opengl/renderer/glshader_p.h | 160 ++ src/plugins/renderers/opengl/renderer/logging.cpp | 65 + src/plugins/renderers/opengl/renderer/logging_p.h | 81 + .../opengl/renderer/openglvertexarrayobject.cpp | 165 ++ .../opengl/renderer/openglvertexarrayobject_p.h | 111 + .../renderers/opengl/renderer/rendercommand.cpp | 91 + .../renderers/opengl/renderer/rendercommand_p.h | 182 ++ src/plugins/renderers/opengl/renderer/renderer.cpp | 2459 +++++++++++++++++++ src/plugins/renderers/opengl/renderer/renderer.pri | 28 + src/plugins/renderers/opengl/renderer/renderer_p.h | 479 ++++ .../renderers/opengl/renderer/renderercache_p.h | 97 + .../renderers/opengl/renderer/renderqueue.cpp | 133 + .../renderers/opengl/renderer/renderqueue_p.h | 102 + .../renderers/opengl/renderer/renderview.cpp | 1238 ++++++++++ .../renderers/opengl/renderer/renderview_p.h | 397 +++ .../opengl/renderer/renderviewbuilder.cpp | 803 ++++++ .../opengl/renderer/renderviewbuilder_p.h | 148 ++ .../opengl/renderer/shaderparameterpack.cpp | 112 + .../opengl/renderer/shaderparameterpack_p.h | 221 ++ .../renderers/opengl/renderer/shadervariables_p.h | 152 ++ .../renderers/opengl/textures/gltexture.cpp | 772 ++++++ .../renderers/opengl/textures/gltexture_p.h | 266 ++ .../renderers/opengl/textures/renderbuffer.cpp | 112 + .../renderers/opengl/textures/renderbuffer_p.h | 90 + src/plugins/renderers/opengl/textures/textures.pri | 9 + src/plugins/renderers/renderers.pro | 9 + src/quick3d/quick3dscene2d/items/scene2d.cpp | 2 +- src/render/backend/apishadermanager_p.h | 2 +- src/render/backend/attachmentpack_p.h | 5 +- src/render/backend/backendnode.cpp | 3 +- src/render/backend/cameralens.cpp | 3 +- src/render/backend/commandexecuter.cpp | 391 --- src/render/backend/commandexecuter_p.h | 95 - src/render/backend/computecommand_p.h | 2 +- src/render/backend/entity_p.h | 4 +- src/render/backend/levelofdetail_p.h | 2 +- src/render/backend/managers_p.h | 62 +- src/render/backend/offscreensurfacehelper_p.h | 3 +- src/render/backend/platformsurfacefilter.cpp | 2 +- src/render/backend/platformsurfacefilter_p.h | 2 +- src/render/backend/qgraphicsutils_p.h | 410 ---- src/render/backend/render-backend.pri | 5 +- src/render/backend/rendersettings_p.h | 2 +- src/render/backend/rendertarget_p.h | 2 +- src/render/backend/rendertargetoutput_p.h | 2 +- src/render/backend/renderthread_p.h | 4 +- src/render/backend/resourceaccessor.cpp | 1 - src/render/backend/stringtoint_p.h | 3 +- src/render/backend/transform_p.h | 2 +- src/render/backend/uniform_p.h | 6 +- src/render/framegraph/blitframebuffer_p.h | 2 +- src/render/framegraph/buffercapture_p.h | 2 +- src/render/framegraph/cameraselectornode.cpp | 3 +- src/render/framegraph/cameraselectornode_p.h | 2 +- src/render/framegraph/clearbuffers_p.h | 2 +- src/render/framegraph/dispatchcompute_p.h | 2 +- src/render/framegraph/framegraphnode.cpp | 2 +- src/render/framegraph/framegraphnode_p.h | 2 +- src/render/framegraph/framegraphvisitor.cpp | 2 +- src/render/framegraph/framegraphvisitor_p.h | 3 +- src/render/framegraph/frustumculling_p.h | 2 +- src/render/framegraph/layerfilternode_p.h | 2 +- src/render/framegraph/memorybarrier_p.h | 2 +- src/render/framegraph/nodraw_p.h | 2 +- src/render/framegraph/proximityfilter_p.h | 2 +- src/render/framegraph/rendercapture_p.h | 2 +- src/render/framegraph/renderpassfilternode_p.h | 2 +- src/render/framegraph/rendersurfaceselector.cpp | 1 - src/render/framegraph/rendersurfaceselector_p.h | 2 +- src/render/framegraph/rendertargetselectornode.cpp | 1 - src/render/framegraph/rendertargetselectornode_p.h | 2 +- src/render/framegraph/setfence_p.h | 2 +- src/render/framegraph/sortpolicy_p.h | 2 +- src/render/framegraph/statesetnode_p.h | 2 +- src/render/framegraph/subtreeenabler.cpp | 1 - src/render/framegraph/techniquefilternode_p.h | 2 +- src/render/framegraph/viewportnode_p.h | 2 +- src/render/frontend/qrenderaspect.cpp | 27 +- src/render/frontend/qrenderaspect_p.h | 1 + src/render/frontend/sphere_p.h | 2 - src/render/geometry/armature_p.h | 2 +- src/render/geometry/attribute_p.h | 2 +- src/render/geometry/buffer_p.h | 2 +- src/render/geometry/buffermanager_p.h | 2 +- src/render/geometry/geometry_p.h | 2 +- src/render/geometry/geometryrenderer_p.h | 2 +- src/render/geometry/geometryrenderermanager_p.h | 2 +- src/render/geometry/joint_p.h | 2 +- src/render/geometry/skeleton_p.h | 2 +- src/render/io/scene_p.h | 2 +- src/render/io/scenemanager_p.h | 2 +- src/render/jobs/abstractpickingjob.cpp | 1 - src/render/jobs/abstractpickingjob_p.h | 3 +- .../jobs/computefilteredboundingvolumejob.cpp | 1 - src/render/jobs/expandboundingvolumejob.cpp | 1 - src/render/jobs/filterproximitydistancejob_p.h | 3 +- src/render/jobs/framecleanupjob.cpp | 4 - src/render/jobs/frustumcullingjob.cpp | 1 - src/render/jobs/frustumcullingjob_p.h | 18 +- src/render/jobs/lightgatherer.cpp | 1 + src/render/jobs/lightgatherer_p.h | 3 +- src/render/jobs/loadbufferjob.cpp | 2 +- src/render/jobs/loadbufferjob_p.h | 2 +- src/render/jobs/loadgeometryjob_p.h | 3 +- src/render/jobs/loadscenejob.cpp | 2 +- src/render/jobs/loadscenejob_p.h | 3 +- src/render/jobs/loadskeletonjob.cpp | 3 + src/render/jobs/pickboundingvolumejob.cpp | 1 - src/render/jobs/pickboundingvolumejob_p.h | 3 +- src/render/jobs/raycastingjob.cpp | 1 - src/render/jobs/raycastingjob_p.h | 3 +- src/render/jobs/updateskinningpalettejob_p.h | 3 +- src/render/jobs/updateworldtransformjob.cpp | 1 - src/render/lights/environmentlight_p.h | 2 +- src/render/lights/light_p.h | 2 +- src/render/lights/lightsource_p.h | 4 +- src/render/materialsystem/effect.cpp | 2 +- src/render/materialsystem/effect_p.h | 2 +- src/render/materialsystem/filterkey_p.h | 2 +- src/render/materialsystem/material_p.h | 3 +- src/render/materialsystem/parameter_p.h | 2 +- src/render/materialsystem/qshaderprogram_p.h | 5 +- src/render/materialsystem/renderpass.cpp | 1 - src/render/materialsystem/renderpass_p.h | 2 +- src/render/materialsystem/shader.cpp | 1 - src/render/materialsystem/shader_p.h | 2 +- src/render/materialsystem/shaderdata.cpp | 8 - src/render/materialsystem/shaderdata_p.h | 11 +- src/render/materialsystem/technique.cpp | 1 - src/render/materialsystem/techniquemanager_p.h | 2 +- src/render/picking/objectpicker_p.h | 2 +- src/render/picking/pickeventfilter_p.h | 3 +- src/render/picking/raycaster_p.h | 2 +- src/render/qrendererplugin.cpp | 68 + src/render/qrendererplugin_p.h | 86 + src/render/qrendererpluginfactory.cpp | 102 + src/render/qrendererpluginfactory_p.h | 79 + src/render/render.pro | 15 +- src/render/renderers/opengl/debug/debug.pri | 10 - .../renderers/opengl/debug/imguirenderer.cpp | 705 ------ .../renderers/opengl/debug/imguirenderer_p.h | 136 -- .../renderers/opengl/graphicshelpers/glfence_p.h | 73 - .../opengl/graphicshelpers/graphicscontext.cpp | 1026 -------- .../opengl/graphicshelpers/graphicscontext_p.h | 264 -- .../opengl/graphicshelpers/graphicshelperes2.cpp | 1034 -------- .../opengl/graphicshelpers/graphicshelperes2_p.h | 182 -- .../opengl/graphicshelpers/graphicshelperes3.cpp | 768 ------ .../opengl/graphicshelpers/graphicshelperes3_1.cpp | 367 --- .../opengl/graphicshelpers/graphicshelperes3_1_p.h | 87 - .../opengl/graphicshelpers/graphicshelperes3_2.cpp | 193 -- .../opengl/graphicshelpers/graphicshelperes3_2_p.h | 84 - .../opengl/graphicshelpers/graphicshelperes3_p.h | 108 - .../opengl/graphicshelpers/graphicshelpergl2.cpp | 935 ------- .../opengl/graphicshelpers/graphicshelpergl2_p.h | 183 -- .../opengl/graphicshelpers/graphicshelpergl3_2.cpp | 1245 ---------- .../opengl/graphicshelpers/graphicshelpergl3_2_p.h | 185 -- .../opengl/graphicshelpers/graphicshelpergl3_3.cpp | 1240 ---------- .../opengl/graphicshelpers/graphicshelpergl3_3_p.h | 185 -- .../opengl/graphicshelpers/graphicshelpergl4.cpp | 1442 ----------- .../opengl/graphicshelpers/graphicshelpergl4_p.h | 182 -- .../graphicshelpers/graphicshelperinterface_p.h | 203 -- .../opengl/graphicshelpers/graphicshelpers.pri | 33 - .../graphicshelpers/imagesubmissioncontext.cpp | 306 --- .../graphicshelpers/imagesubmissioncontext_p.h | 95 - .../opengl/graphicshelpers/submissioncontext.cpp | 1574 ------------ .../opengl/graphicshelpers/submissioncontext_p.h | 234 -- .../graphicshelpers/texturesubmissioncontext.cpp | 225 -- .../graphicshelpers/texturesubmissioncontext_p.h | 106 - src/render/renderers/opengl/io/glbuffer.cpp | 169 -- src/render/renderers/opengl/io/glbuffer_p.h | 115 - src/render/renderers/opengl/io/io.pri | 8 - .../opengl/jobs/filtercompatibletechniquejob.cpp | 95 - .../opengl/jobs/filtercompatibletechniquejob_p.h | 92 - src/render/renderers/opengl/jobs/jobs.pri | 17 - .../opengl/jobs/materialparametergathererjob.cpp | 131 - .../opengl/jobs/materialparametergathererjob_p.h | 107 - .../opengl/jobs/renderviewcommandbuilderjob.cpp | 81 - .../opengl/jobs/renderviewcommandbuilderjob_p.h | 96 - .../opengl/jobs/renderviewcommandupdaterjob.cpp | 82 - .../opengl/jobs/renderviewcommandupdaterjob_p.h | 103 - .../opengl/jobs/renderviewinitializerjob.cpp | 104 - .../opengl/jobs/renderviewinitializerjob_p.h | 107 - .../renderers/opengl/jobs/renderviewjobutils.cpp | 574 ----- .../renderers/opengl/jobs/renderviewjobutils_p.h | 187 -- .../renderers/opengl/managers/gl_handle_types_p.h | 76 - .../opengl/managers/glresourcemanagers.cpp | 73 - .../opengl/managers/glresourcemanagers_p.h | 135 - src/render/renderers/opengl/managers/managers.pri | 9 - src/render/renderers/opengl/opengl.pri | 15 - src/render/renderers/opengl/renderer/glshader.cpp | 316 --- src/render/renderers/opengl/renderer/glshader_p.h | 160 -- .../opengl/renderer/openglvertexarrayobject.cpp | 165 -- .../opengl/renderer/openglvertexarrayobject_p.h | 111 - .../renderers/opengl/renderer/rendercommand.cpp | 91 - .../renderers/opengl/renderer/rendercommand_p.h | 182 -- src/render/renderers/opengl/renderer/renderer.cpp | 2458 ------------------- src/render/renderers/opengl/renderer/renderer.pri | 24 - src/render/renderers/opengl/renderer/renderer_p.h | 477 ---- .../renderers/opengl/renderer/renderercache_p.h | 97 - .../renderers/opengl/renderer/renderqueue.cpp | 133 - .../renderers/opengl/renderer/renderqueue_p.h | 102 - .../renderers/opengl/renderer/renderview.cpp | 1236 ---------- .../renderers/opengl/renderer/renderview_p.h | 410 ---- .../opengl/renderer/renderviewbuilder.cpp | 803 ------ .../opengl/renderer/renderviewbuilder_p.h | 147 -- .../opengl/renderer/shaderparameterpack.cpp | 112 - .../opengl/renderer/shaderparameterpack_p.h | 221 -- .../renderers/opengl/renderer/shadervariables_p.h | 152 -- .../renderers/opengl/renderstates/renderstates.pri | 7 - .../opengl/renderstates/renderstateset.cpp | 153 -- .../opengl/renderstates/renderstateset_p.h | 122 - src/render/renderers/opengl/textures/gltexture.cpp | 772 ------ src/render/renderers/opengl/textures/gltexture_p.h | 266 -- .../renderers/opengl/textures/renderbuffer.cpp | 112 - .../renderers/opengl/textures/renderbuffer_p.h | 90 - src/render/renderers/opengl/textures/textures.pri | 9 - src/render/renderers/renderers.pri | 7 - src/render/renderstates/genericstate_p.h | 3 +- src/render/renderstates/renderstatenode_p.h | 3 +- src/render/renderstates/renderstates.cpp | 1 - src/render/renderstates/renderstates.pri | 6 +- src/render/renderstates/renderstates_p.h | 44 +- src/render/renderstates/renderstateset.cpp | 150 ++ src/render/renderstates/renderstateset_p.h | 122 + src/render/renderstates/statevariant_p.h | 2 +- src/render/services/vsyncframeadvanceservice_p.h | 3 +- src/render/texture/qtexture.cpp | 2 +- src/render/texture/qtextureimagedata_p.h | 3 +- src/render/texture/texture.cpp | 2 +- src/render/texture/texture_p.h | 2 +- src/render/texture/texturedatamanager_p.h | 227 ++ src/render/texture/textureimage_p.h | 2 +- src/src.pro | 11 +- .../render/computecommand/tst_computecommand.cpp | 89 - tests/auto/render/effect/tst_effect.cpp | 1 - .../render/filtercompatibletechniquejob/BLACKLIST | 6 - .../filtercompatibletechniquejob.pro | 12 - .../tst_filtercompatibletechniquejob.cpp | 263 -- .../render/glshadermanager/glshadermanager.pro | 12 - .../render/glshadermanager/tst_glshadermanager.cpp | 199 -- .../render/graphicshelpergl2/graphicshelpergl2.pro | 13 - .../graphicshelpergl2/tst_graphicshelpergl2.cpp | 1605 ------------ .../graphicshelpergl3_2/graphicshelpergl3_2.pro | 13 - .../tst_graphicshelpergl3_2.cpp | 2294 ----------------- .../graphicshelpergl3_3/graphicshelpergl3_3.pro | 13 - .../tst_graphicshelpergl3_3.cpp | 2393 ------------------ .../render/graphicshelpergl4/graphicshelpergl4.pro | 13 - .../graphicshelpergl4/tst_graphicshelpergl4.cpp | 2583 -------------------- .../render/layerfiltering/tst_layerfiltering.cpp | 1 + .../materialparametergathererjob.pro | 11 - .../tst_materialparametergathererjob.cpp | 799 ------ .../opengl/computecommand/computecommand.pro | 15 + .../opengl/computecommand/tst_computecommand.cpp | 143 ++ .../opengl/filtercompatibletechniquejob/BLACKLIST | 6 + .../filtercompatibletechniquejob.pro | 15 + .../tst_filtercompatibletechniquejob.cpp | 263 ++ .../opengl/glshadermanager/glshadermanager.pro | 15 + .../opengl/glshadermanager/tst_glshadermanager.cpp | 199 ++ .../opengl/graphicshelpergl2/graphicshelpergl2.pro | 16 + .../graphicshelpergl2/tst_graphicshelpergl2.cpp | 1605 ++++++++++++ .../graphicshelpergl3_2/graphicshelpergl3_2.pro | 16 + .../tst_graphicshelpergl3_2.cpp | 2294 +++++++++++++++++ .../graphicshelpergl3_3/graphicshelpergl3_3.pro | 16 + .../tst_graphicshelpergl3_3.cpp | 2393 ++++++++++++++++++ .../opengl/graphicshelpergl4/graphicshelpergl4.pro | 16 + .../graphicshelpergl4/tst_graphicshelpergl4.cpp | 2583 ++++++++++++++++++++ .../materialparametergathererjob.pro | 14 + .../tst_materialparametergathererjob.cpp | 801 ++++++ tests/auto/render/opengl/opengl.pro | 19 + tests/auto/render/opengl/opengl_render_plugin.pri | 18 + .../opengl/qgraphicsutils/qgraphicsutils.pro | 12 + .../opengl/qgraphicsutils/tst_qgraphicsutils.cpp | 355 +++ tests/auto/render/opengl/renderer/renderer.pro | 12 + tests/auto/render/opengl/renderer/tst_renderer.cpp | 348 +++ .../auto/render/opengl/renderqueue/renderqueue.pro | 14 + .../render/opengl/renderqueue/tst_renderqueue.cpp | 243 ++ .../opengl/renderviewbuilder/renderviewbuilder.pro | 15 + .../renderviewbuilder/tst_renderviewbuilder.cpp | 669 +++++ .../auto/render/opengl/renderviews/renderviews.pro | 15 + .../render/opengl/renderviews/tst_renderviews.cpp | 554 +++++ .../opengl/renderviewutils/renderviewutils.pro | 15 + .../opengl/renderviewutils/tst_renderviewutils.cpp | 801 ++++++ tests/auto/render/opengl/textures/textures.pro | 15 + tests/auto/render/opengl/textures/tst_textures.cpp | 821 +++++++ .../tst_pickboundingvolumejob.cpp | 2 + .../proximityfiltering/tst_proximityfiltering.cpp | 4 + tests/auto/render/qcamera/tst_qcamera.cpp | 1 + .../auto/render/qgraphicsutils/qgraphicsutils.pro | 9 - .../render/qgraphicsutils/tst_qgraphicsutils.cpp | 355 --- .../render/raycastingjob/tst_raycastingjob.cpp | 1 + tests/auto/render/render.pro | 18 +- tests/auto/render/renderer/renderer.pro | 9 - tests/auto/render/renderer/tst_renderer.cpp | 349 --- tests/auto/render/renderqueue/renderqueue.pro | 11 - tests/auto/render/renderqueue/tst_renderqueue.cpp | 243 -- .../render/renderviewbuilder/renderviewbuilder.pro | 12 - .../renderviewbuilder/tst_renderviewbuilder.cpp | 669 ----- tests/auto/render/renderviews/renderviews.pro | 12 - tests/auto/render/renderviews/tst_renderviews.cpp | 552 ----- .../render/renderviewutils/renderviewutils.pro | 12 - .../render/renderviewutils/tst_renderviewutils.cpp | 800 ------ tests/auto/render/technique/tst_technique.cpp | 1 - tests/auto/render/textures/textures.pro | 12 - tests/auto/render/textures/tst_textures.cpp | 821 ------- .../trianglesextractor/tst_trianglesextractor.cpp | 1 - tests/benchmarks/render/jobs/jobs.pro | 4 + tests/benchmarks/render/jobs/tst_bench_jobs.cpp | 2 +- .../materialparametergathering.pro | 3 + .../tst_bench_materialparametergathering.cpp | 2 +- 373 files changed, 41195 insertions(+), 40054 deletions(-) create mode 100644 src/plugins/renderers/dummy/dummy.pro create mode 100644 src/plugins/renderers/opengl/debug/debug.pri create mode 100644 src/plugins/renderers/opengl/debug/imguirenderer.cpp create mode 100644 src/plugins/renderers/opengl/debug/imguirenderer_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri create mode 100644 src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h create mode 100644 src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp create mode 100644 src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h create mode 100644 src/plugins/renderers/opengl/io/glbuffer.cpp create mode 100644 src/plugins/renderers/opengl/io/glbuffer_p.h create mode 100644 src/plugins/renderers/opengl/io/io.pri create mode 100644 src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp create mode 100644 src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h create mode 100644 src/plugins/renderers/opengl/jobs/jobs.pri create mode 100644 src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp create mode 100644 src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h create mode 100644 src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp create mode 100644 src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h create mode 100644 src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp create mode 100644 src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h create mode 100644 src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp create mode 100644 src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h create mode 100644 src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp create mode 100644 src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h create mode 100644 src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp create mode 100644 src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h create mode 100644 src/plugins/renderers/opengl/main.cpp create mode 100644 src/plugins/renderers/opengl/managers/gl_handle_types_p.h create mode 100644 src/plugins/renderers/opengl/managers/glresourcemanagers.cpp create mode 100644 src/plugins/renderers/opengl/managers/glresourcemanagers_p.h create mode 100644 src/plugins/renderers/opengl/managers/managers.pri create mode 100644 src/plugins/renderers/opengl/opengl.pri create mode 100644 src/plugins/renderers/opengl/opengl.pro create mode 100644 src/plugins/renderers/opengl/openglrenderer.json create mode 100644 src/plugins/renderers/opengl/renderer/commandexecuter.cpp create mode 100644 src/plugins/renderers/opengl/renderer/commandexecuter_p.h create mode 100644 src/plugins/renderers/opengl/renderer/glfence_p.h create mode 100644 src/plugins/renderers/opengl/renderer/glshader.cpp create mode 100644 src/plugins/renderers/opengl/renderer/glshader_p.h create mode 100644 src/plugins/renderers/opengl/renderer/logging.cpp create mode 100644 src/plugins/renderers/opengl/renderer/logging_p.h create mode 100644 src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp create mode 100644 src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h create mode 100644 src/plugins/renderers/opengl/renderer/rendercommand.cpp create mode 100644 src/plugins/renderers/opengl/renderer/rendercommand_p.h create mode 100644 src/plugins/renderers/opengl/renderer/renderer.cpp create mode 100644 src/plugins/renderers/opengl/renderer/renderer.pri create mode 100644 src/plugins/renderers/opengl/renderer/renderer_p.h create mode 100644 src/plugins/renderers/opengl/renderer/renderercache_p.h create mode 100644 src/plugins/renderers/opengl/renderer/renderqueue.cpp create mode 100644 src/plugins/renderers/opengl/renderer/renderqueue_p.h create mode 100644 src/plugins/renderers/opengl/renderer/renderview.cpp create mode 100644 src/plugins/renderers/opengl/renderer/renderview_p.h create mode 100644 src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp create mode 100644 src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h create mode 100644 src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp create mode 100644 src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h create mode 100644 src/plugins/renderers/opengl/renderer/shadervariables_p.h create mode 100644 src/plugins/renderers/opengl/textures/gltexture.cpp create mode 100644 src/plugins/renderers/opengl/textures/gltexture_p.h create mode 100644 src/plugins/renderers/opengl/textures/renderbuffer.cpp create mode 100644 src/plugins/renderers/opengl/textures/renderbuffer_p.h create mode 100644 src/plugins/renderers/opengl/textures/textures.pri create mode 100644 src/plugins/renderers/renderers.pro delete mode 100644 src/render/backend/commandexecuter.cpp delete mode 100644 src/render/backend/commandexecuter_p.h delete mode 100644 src/render/backend/qgraphicsutils_p.h create mode 100644 src/render/qrendererplugin.cpp create mode 100644 src/render/qrendererplugin_p.h create mode 100644 src/render/qrendererpluginfactory.cpp create mode 100644 src/render/qrendererpluginfactory_p.h delete mode 100644 src/render/renderers/opengl/debug/debug.pri delete mode 100644 src/render/renderers/opengl/debug/imguirenderer.cpp delete mode 100644 src/render/renderers/opengl/debug/imguirenderer_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/glfence_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes2_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperes3_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/graphicshelpers.pri delete mode 100644 src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h delete mode 100644 src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp delete mode 100644 src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h delete mode 100644 src/render/renderers/opengl/io/glbuffer.cpp delete mode 100644 src/render/renderers/opengl/io/glbuffer_p.h delete mode 100644 src/render/renderers/opengl/io/io.pri delete mode 100644 src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp delete mode 100644 src/render/renderers/opengl/jobs/filtercompatibletechniquejob_p.h delete mode 100644 src/render/renderers/opengl/jobs/jobs.pri delete mode 100644 src/render/renderers/opengl/jobs/materialparametergathererjob.cpp delete mode 100644 src/render/renderers/opengl/jobs/materialparametergathererjob_p.h delete mode 100644 src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp delete mode 100644 src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h delete mode 100644 src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp delete mode 100644 src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h delete mode 100644 src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp delete mode 100644 src/render/renderers/opengl/jobs/renderviewinitializerjob_p.h delete mode 100644 src/render/renderers/opengl/jobs/renderviewjobutils.cpp delete mode 100644 src/render/renderers/opengl/jobs/renderviewjobutils_p.h delete mode 100644 src/render/renderers/opengl/managers/gl_handle_types_p.h delete mode 100644 src/render/renderers/opengl/managers/glresourcemanagers.cpp delete mode 100644 src/render/renderers/opengl/managers/glresourcemanagers_p.h delete mode 100644 src/render/renderers/opengl/managers/managers.pri delete mode 100644 src/render/renderers/opengl/opengl.pri delete mode 100644 src/render/renderers/opengl/renderer/glshader.cpp delete mode 100644 src/render/renderers/opengl/renderer/glshader_p.h delete mode 100644 src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp delete mode 100644 src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h delete mode 100644 src/render/renderers/opengl/renderer/rendercommand.cpp delete mode 100644 src/render/renderers/opengl/renderer/rendercommand_p.h delete mode 100644 src/render/renderers/opengl/renderer/renderer.cpp delete mode 100644 src/render/renderers/opengl/renderer/renderer.pri delete mode 100644 src/render/renderers/opengl/renderer/renderer_p.h delete mode 100644 src/render/renderers/opengl/renderer/renderercache_p.h delete mode 100644 src/render/renderers/opengl/renderer/renderqueue.cpp delete mode 100644 src/render/renderers/opengl/renderer/renderqueue_p.h delete mode 100644 src/render/renderers/opengl/renderer/renderview.cpp delete mode 100644 src/render/renderers/opengl/renderer/renderview_p.h delete mode 100644 src/render/renderers/opengl/renderer/renderviewbuilder.cpp delete mode 100644 src/render/renderers/opengl/renderer/renderviewbuilder_p.h delete mode 100644 src/render/renderers/opengl/renderer/shaderparameterpack.cpp delete mode 100644 src/render/renderers/opengl/renderer/shaderparameterpack_p.h delete mode 100644 src/render/renderers/opengl/renderer/shadervariables_p.h delete mode 100644 src/render/renderers/opengl/renderstates/renderstates.pri delete mode 100644 src/render/renderers/opengl/renderstates/renderstateset.cpp delete mode 100644 src/render/renderers/opengl/renderstates/renderstateset_p.h delete mode 100644 src/render/renderers/opengl/textures/gltexture.cpp delete mode 100644 src/render/renderers/opengl/textures/gltexture_p.h delete mode 100644 src/render/renderers/opengl/textures/renderbuffer.cpp delete mode 100644 src/render/renderers/opengl/textures/renderbuffer_p.h delete mode 100644 src/render/renderers/opengl/textures/textures.pri delete mode 100644 src/render/renderers/renderers.pri create mode 100644 src/render/renderstates/renderstateset.cpp create mode 100644 src/render/renderstates/renderstateset_p.h create mode 100644 src/render/texture/texturedatamanager_p.h delete mode 100644 tests/auto/render/filtercompatibletechniquejob/BLACKLIST delete mode 100644 tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro delete mode 100644 tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp delete mode 100644 tests/auto/render/glshadermanager/glshadermanager.pro delete mode 100644 tests/auto/render/glshadermanager/tst_glshadermanager.cpp delete mode 100644 tests/auto/render/graphicshelpergl2/graphicshelpergl2.pro delete mode 100644 tests/auto/render/graphicshelpergl2/tst_graphicshelpergl2.cpp delete mode 100644 tests/auto/render/graphicshelpergl3_2/graphicshelpergl3_2.pro delete mode 100644 tests/auto/render/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp delete mode 100644 tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro delete mode 100644 tests/auto/render/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp delete mode 100644 tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro delete mode 100644 tests/auto/render/graphicshelpergl4/tst_graphicshelpergl4.cpp delete mode 100644 tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro delete mode 100644 tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp create mode 100644 tests/auto/render/opengl/computecommand/computecommand.pro create mode 100644 tests/auto/render/opengl/computecommand/tst_computecommand.cpp create mode 100644 tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST create mode 100644 tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro create mode 100644 tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp create mode 100644 tests/auto/render/opengl/glshadermanager/glshadermanager.pro create mode 100644 tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp create mode 100644 tests/auto/render/opengl/graphicshelpergl2/graphicshelpergl2.pro create mode 100644 tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp create mode 100644 tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro create mode 100644 tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp create mode 100644 tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro create mode 100644 tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp create mode 100644 tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro create mode 100644 tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp create mode 100644 tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro create mode 100644 tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp create mode 100644 tests/auto/render/opengl/opengl.pro create mode 100644 tests/auto/render/opengl/opengl_render_plugin.pri create mode 100644 tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro create mode 100644 tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp create mode 100644 tests/auto/render/opengl/renderer/renderer.pro create mode 100644 tests/auto/render/opengl/renderer/tst_renderer.cpp create mode 100644 tests/auto/render/opengl/renderqueue/renderqueue.pro create mode 100644 tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp create mode 100644 tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro create mode 100644 tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp create mode 100644 tests/auto/render/opengl/renderviews/renderviews.pro create mode 100644 tests/auto/render/opengl/renderviews/tst_renderviews.cpp create mode 100644 tests/auto/render/opengl/renderviewutils/renderviewutils.pro create mode 100644 tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp create mode 100644 tests/auto/render/opengl/textures/textures.pro create mode 100644 tests/auto/render/opengl/textures/tst_textures.cpp delete mode 100644 tests/auto/render/qgraphicsutils/qgraphicsutils.pro delete mode 100644 tests/auto/render/qgraphicsutils/tst_qgraphicsutils.cpp delete mode 100644 tests/auto/render/renderer/renderer.pro delete mode 100644 tests/auto/render/renderer/tst_renderer.cpp delete mode 100644 tests/auto/render/renderqueue/renderqueue.pro delete mode 100644 tests/auto/render/renderqueue/tst_renderqueue.cpp delete mode 100644 tests/auto/render/renderviewbuilder/renderviewbuilder.pro delete mode 100644 tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp delete mode 100644 tests/auto/render/renderviews/renderviews.pro delete mode 100644 tests/auto/render/renderviews/tst_renderviews.cpp delete mode 100644 tests/auto/render/renderviewutils/renderviewutils.pro delete mode 100644 tests/auto/render/renderviewutils/tst_renderviewutils.cpp delete mode 100644 tests/auto/render/textures/textures.pro delete mode 100644 tests/auto/render/textures/tst_textures.cpp diff --git a/src/core/resources/qresourcemanager_p.h b/src/core/resources/qresourcemanager_p.h index ba39695a4..6e479d5ef 100644 --- a/src/core/resources/qresourcemanager_p.h +++ b/src/core/resources/qresourcemanager_p.h @@ -179,19 +179,7 @@ private: template struct QResourceInfo { - enum - { - needsCleanup = false - }; -}; - -template <> -struct QResourceInfo -{ - enum - { - needsCleanup = false - }; + static const bool needsCleanup = false; }; enum @@ -204,22 +192,10 @@ enum template<> \ struct QResourceInfo \ { \ - enum \ -{ \ - needsCleanup = ((FLAGS & Q_REQUIRES_CLEANUP) == 0) \ -}; \ + static const bool needsCleanup = (FLAGS & Q_REQUIRES_CLEANUP) == 0;\ }; \ } // namespace Qt3DCore -template -struct Int2Type -{ - enum - { - value = v - }; -}; - template class QHandleData : public QHandle::Data { @@ -275,7 +251,7 @@ public: typename Handle::Data *d = handle.data_ptr(); d->nextFree = freeList; freeList = d; - performCleanup(&static_cast *>(d)->data, Int2Type::needsCleanup>()); + performCleanup(&static_cast *>(d)->data, std::integral_constant::needsCleanup>{}); } T *data(Handle h) @@ -349,13 +325,16 @@ private: } } - void performCleanup(T *r, Int2Type) + template + void performCleanup(Q *r, std::integral_constant) { r->cleanup(); } - void performCleanup(T *, Int2Type) - {} + template + void performCleanup(Q *, std::integral_constant) + { + } }; diff --git a/src/core/transforms/matrix4x4_avx2_p.h b/src/core/transforms/matrix4x4_avx2_p.h index 63858b35c..0b35f0016 100644 --- a/src/core/transforms/matrix4x4_avx2_p.h +++ b/src/core/transforms/matrix4x4_avx2_p.h @@ -489,6 +489,7 @@ public: friend Q_3DCORE_PRIVATE_EXPORT Vector3D operator*(const Matrix4x4_AVX2 &matrix, const Vector3D &vector); friend Q_3DCORE_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const Matrix4x4_AVX2 &m); + private: // column major order // aligned on 32 bytes boundaries for AVX, compatible with 16 bytes boundary for SSE diff --git a/src/core/transforms/matrix4x4_sse_p.h b/src/core/transforms/matrix4x4_sse_p.h index 0ea2e37ad..adef74daf 100644 --- a/src/core/transforms/matrix4x4_sse_p.h +++ b/src/core/transforms/matrix4x4_sse_p.h @@ -372,6 +372,7 @@ public: friend Q_ALWAYS_INLINE Vector3D operator*(const Matrix4x4_SSE &matrix, const Vector3D &vector); friend Q_3DCORE_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const Matrix4x4_SSE &m); + private: // Internally we will store the matrix as indicated below // Q_DECL_ALIGN(16) // aligned on 16 bytes boundary for SSE (column major) diff --git a/src/plugins/renderers/dummy/dummy.pro b/src/plugins/renderers/dummy/dummy.pro new file mode 100644 index 000000000..e69de29bb diff --git a/src/plugins/renderers/opengl/debug/debug.pri b/src/plugins/renderers/opengl/debug/debug.pri new file mode 100644 index 000000000..c5153bbf7 --- /dev/null +++ b/src/plugins/renderers/opengl/debug/debug.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD + +include($$QT3D_ROOT/src/3rdparty/imgui/imgui.pri) + +HEADERS += \ + $$PWD/imguirenderer_p.h \ + $$PWD/imconfig.h + +SOURCES += \ + $$PWD/imguirenderer.cpp diff --git a/src/plugins/renderers/opengl/debug/imguirenderer.cpp b/src/plugins/renderers/opengl/debug/imguirenderer.cpp new file mode 100644 index 000000000..acc6e6775 --- /dev/null +++ b/src/plugins/renderers/opengl/debug/imguirenderer.cpp @@ -0,0 +1,705 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + * Based on https://github.com/seanchas116/qtimgui/ + * + * MIT License https://github.com/seanchas116/qtimgui/blob/master/LICENSE + * + */ + +#include "imguirenderer_p.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "imgui.h" + +#ifndef GL_VERTEX_ARRAY_BINDING +// just for building on some platforms, won't run anyway as this requires GL/ES > 2 +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#endif + +QT_BEGIN_NAMESPACE + +using namespace Qt3DRender; +using namespace Render; +using namespace Render::Debug; + +namespace { + + const QHash keyMap = { + { Qt::Key_Tab, ImGuiKey_Tab }, + { Qt::Key_Left, ImGuiKey_LeftArrow }, + { Qt::Key_Right, ImGuiKey_RightArrow }, + { Qt::Key_Up, ImGuiKey_UpArrow }, + { Qt::Key_Down, ImGuiKey_DownArrow }, + { Qt::Key_PageUp, ImGuiKey_PageUp }, + { Qt::Key_PageDown, ImGuiKey_PageDown }, + { Qt::Key_Home, ImGuiKey_Home }, + { Qt::Key_End, ImGuiKey_End }, + { Qt::Key_Delete, ImGuiKey_Delete }, + { Qt::Key_Backspace, ImGuiKey_Backspace }, + { Qt::Key_Enter, ImGuiKey_Enter }, + { Qt::Key_Escape, ImGuiKey_Escape }, + { Qt::Key_A, ImGuiKey_A }, + { Qt::Key_C, ImGuiKey_C }, + { Qt::Key_V, ImGuiKey_V }, + { Qt::Key_X, ImGuiKey_X }, + { Qt::Key_Y, ImGuiKey_Y }, + { Qt::Key_Z, ImGuiKey_Z }, + }; + + QByteArray g_currentClipboardText; + + // doesn't handle primitive restart when using indexes + int vertexToPrimitiveCount(Qt3DRender::QGeometryRenderer::PrimitiveType primitiveType, int numVertices) { + int nPrimitives = 0; + switch (primitiveType) { + case QGeometryRenderer::Points: + case QGeometryRenderer::LineLoop: nPrimitives += numVertices; break; + case QGeometryRenderer::Triangles: nPrimitives += numVertices / 3; break; + case QGeometryRenderer::Lines: nPrimitives += numVertices / 2; break; + case QGeometryRenderer::TriangleFan: + case QGeometryRenderer::TriangleStrip: + case QGeometryRenderer::LineStrip: nPrimitives += numVertices - 1; break; + case QGeometryRenderer::TrianglesAdjacency: nPrimitives += numVertices / 6; break; + case QGeometryRenderer::TriangleStripAdjacency: + case QGeometryRenderer::LineStripAdjacency: nPrimitives += numVertices / 2 - 1; break; + case QGeometryRenderer::LinesAdjacency: nPrimitives += numVertices / 4; break; + case QGeometryRenderer::Patches: nPrimitives += 1; + } + return nPrimitives; + } + + const char *primitiveTypeName(Qt3DRender::QGeometryRenderer::PrimitiveType primitiveType) { + switch (primitiveType) { + case QGeometryRenderer::Points: return "Points"; + case QGeometryRenderer::LineLoop: return "LineLoop"; + case QGeometryRenderer::Triangles: return "Triangles"; + case QGeometryRenderer::TrianglesAdjacency: return "TriangleAdjacency"; + case QGeometryRenderer::TriangleFan: return "TriangleFan"; + case QGeometryRenderer::TriangleStrip: return "TriangleStrip"; + case QGeometryRenderer::TriangleStripAdjacency: return "TriangleStringAdjacency"; + case QGeometryRenderer::LineStrip: return "LineStrip"; + case QGeometryRenderer::LineStripAdjacency: return "LineStripAdjacency"; + case QGeometryRenderer::Lines: return "Lines"; + case QGeometryRenderer::LinesAdjacency: return "LinesAdjacency"; + case QGeometryRenderer::Patches: return "Patches"; + } + return ""; + } +} + +ImGuiRenderer::ImGuiRenderer(Renderer *renderer) + : m_renderer(renderer) +{ + ImGui::CreateContext(); + + ImGuiIO &io = ImGui::GetIO(); + for (ImGuiKey key : keyMap.values()) + io.KeyMap[key] = key; + +#ifndef QT_NO_CLIPBOARD + io.SetClipboardTextFn = [](void *user_data, const char *text) { + Q_UNUSED(user_data) + QGuiApplication::clipboard()->setText(QString::fromLatin1(text)); + }; + io.GetClipboardTextFn = [](void *user_data) { + Q_UNUSED(user_data) + g_currentClipboardText = QGuiApplication::clipboard()->text().toUtf8(); + return static_cast(g_currentClipboardText.data()); + }; +#endif + + std::fill(std::begin(m_fpsLog), std::end(m_fpsLog), 0.f); + std::fill(std::begin(m_jobsLog), std::end(m_jobsLog), 0.f); + m_fpsRange.first = m_fpsRange.second = 0.f; + m_jobsRange.first = m_jobsRange.second = 0.f; +} + +void ImGuiRenderer::renderDebugOverlay(const QVector &renderViews, const RenderView *renderView, int jobsInLastFrame) +{ + if (!newFrame(renderView)) + return; + + const int renderViewsCount = renderViews.size(); + + int logIndex = qMin(IMGUI_PERF_LOG_SIZE - 1, ImGui::GetFrameCount()); + if (logIndex == IMGUI_PERF_LOG_SIZE - 1) { + std::rotate(std::begin(m_fpsLog), std::begin(m_fpsLog) + 1, std::end(m_fpsLog)); + std::rotate(std::begin(m_jobsLog), std::begin(m_jobsLog) + 1, std::end(m_jobsLog)); + } + m_fpsLog[logIndex] = ImGui::GetIO().Framerate; + m_fpsRange.first = m_fpsRange.second = 0.f; + for (float v: m_fpsLog) { + m_fpsRange.first = qMin(m_fpsRange.first, qMax(v - 5.f, 0.f)); + m_fpsRange.second = qMax(m_fpsRange.second, v + 2.f); + } + m_jobsLog[logIndex] = jobsInLastFrame; + m_jobsRange.first = m_jobsRange.second = 0.f; + for (float v: m_jobsLog) { + m_jobsRange.first = qMin(m_jobsRange.first, qMax(v - 5.f, 0.f)); + m_jobsRange.second = qMax(m_jobsRange.second, v + 2.f); + } + + { + bool pj = m_renderer->services()->systemInformation()->isTraceEnabled(); + bool pg = m_renderer->services()->systemInformation()->isGraphicsTraceEnabled(); + + ImGui::Begin("Qt3D Profiling"); + char caption[50]; + sprintf(caption, "Avg %.3f ms/frame (%.1f FPS)", static_cast(1000.0f / ImGui::GetIO().Framerate), static_cast(ImGui::GetIO().Framerate)); + ImGui::PlotLines("FPS", m_fpsLog, logIndex + 1, 0, caption, m_fpsRange.first, m_fpsRange.second, ImVec2(0, 80)); + ImGui::PlotHistogram("Jobs", m_jobsLog, logIndex + 1, 0, nullptr, m_jobsRange.first, m_jobsRange.second, ImVec2(0, 80)); + ImGui::Text("Profiling: "); + ImGui::SameLine(); + if (ImGui::Checkbox("Jobs", &pj)) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "setTraceEnabled", Qt::QueuedConnection, Q_ARG(bool, pj)); + ImGui::SameLine(); + if (ImGui::Checkbox("GL", &pg)) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "setGraphicsTraceEnabled", Qt::QueuedConnection, Q_ARG(bool, pg)); + ImGui::SameLine(); + if (ImGui::Button("Reveal")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "revealLogFolder", Qt::QueuedConnection); + + int nCommands = 0; + int nVertices = 0; + int nPrimitives = 0; + QSet inUseGeometries; + QSet inUseTextures; + for (int j=0; jcommands(); + nCommands += commands.size(); + for (int k=0; knodeManagers()->renderNodesManager()->count()); + column2Numbers(inUseGeometries.size(), m_renderer->nodeManagers()->geometryRendererManager()->count()); + column2Numbers(inUseTextures.size(), m_renderer->nodeManagers()->textureManager()->count()); + + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::AlignTextToFramePadding(); + ImGui::Text("Show:"); + ImGui::SameLine(); + if (ImGui::Button("GL Info")) + m_showGLInfoWindow = !m_showGLInfoWindow; + ImGui::SameLine(); + if (ImGui::Button("Render Views")) + m_showRenderDetailsWindow = !m_showRenderDetailsWindow; + + ImGui::AlignTextToFramePadding(); + ImGui::Text("Dump:"); + ImGui::SameLine(); + if (ImGui::Button("SceneGraph##1")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render scenegraph"))); + ImGui::SameLine(); + if (ImGui::Button("FrameGraph##1")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render framegraph"))); + ImGui::SameLine(); + if (ImGui::Button("FrameGraph Paths##1")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render framepaths"))); + + ImGui::End(); + + if (m_showGLInfoWindow) + showGLInfo(); + if (m_showRenderDetailsWindow) + showRenderDetails(renderViews); + } + + ImGui::Render(); + renderDrawList(ImGui::GetDrawData()); +} + +void ImGuiRenderer::setCapabilities(const QString &capabilities) +{ + m_capabilities = capabilities.toLatin1(); +} + +void ImGuiRenderer::showGLInfo() +{ + ImGui::Begin("Open GL Details", &m_showGLInfoWindow); + ImGui::Text("%s", m_capabilities.data()); + ImGui::End(); +} + +void ImGuiRenderer::showRenderDetails(const QVector &renderViews) +{ + ImGui::Begin("Render Views", &m_showRenderDetailsWindow); + + int i = 1; + for (const RenderView *view: renderViews) { + QString label(QLatin1String("View ") + QString::number(i++)); + if (ImGui::TreeNode(label.toLatin1().data())) { + ImGui::Text("Viewport: (%.1f, %.1f, %.1f, %.1f)", view->viewport().x(), view->viewport().y(), + view->viewport().width(), view->viewport().height()); + ImGui::Text("Surface Size: (%d, %d)", view->surfaceSize().width(), view->surfaceSize().height()); + ImGui::Text("Pixel Ratio: %.1f", view->devicePixelRatio()); + ImGui::Text("No Draw: %s", view->noDraw() ? "TRUE" : "FALSE"); + ImGui::Text("Frustum Culling: %s", view->frustumCulling() ? "TRUE" : "FALSE"); + ImGui::Text("Compute: %s", view->isCompute() ? "TRUE" : "FALSE"); + ImGui::Text("Clear Depth Value: %f", static_cast(view->clearDepthValue())); + ImGui::Text("Clear Stencil Value: %d", view->clearStencilValue()); + int j = 1; + const auto commands = view->commands(); + for (const RenderCommand &command: commands) { + QString label(QLatin1String("Command ") + QString::number(j++)); + if (ImGui::TreeNode(label.toLatin1().data())) { + ImGui::Text("Primitive Type: %s %s", primitiveTypeName(command.m_primitiveType), + command.m_drawIndexed ? "(indexed)" : ""); + ImGui::Text("# Vertices: %d", command.m_primitiveCount); + ImGui::Text("# Primitives: %d", vertexToPrimitiveCount(command.m_primitiveType, command.m_primitiveCount)); + ImGui::Text("# Instances: %d", command.m_instanceCount); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + ImGui::Separator(); + } + } + + if (ImGui::Button("Dump")) + QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", + Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render rendercommands"))); + ImGui::End(); +} + +void ImGuiRenderer::renderDrawList(ImDrawData *draw_data) +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + ImGuiIO& io = ImGui::GetIO(); + int fb_width = int(io.DisplaySize.x * io.DisplayFramebufferScale.x); + int fb_height = int(io.DisplaySize.y * io.DisplayFramebufferScale.y); + if (fb_width == 0 || fb_height == 0) + return; + draw_data->ScaleClipRects(io.DisplayFramebufferScale); + + // Backup GL state + GLint last_active_texture; m_funcs->glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); + m_funcs->glActiveTexture(GL_TEXTURE0); + GLint last_program; m_funcs->glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); + GLint last_texture; m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLint last_array_buffer; m_funcs->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + GLint last_element_array_buffer; m_funcs->glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); + GLint last_vertex_array; m_funcs->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + GLint last_blend_src_rgb; m_funcs->glGetIntegerv(GL_BLEND_SRC_RGB, &last_blend_src_rgb); + GLint last_blend_dst_rgb; m_funcs->glGetIntegerv(GL_BLEND_DST_RGB, &last_blend_dst_rgb); + GLint last_blend_src_alpha; m_funcs->glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha); + GLint last_blend_dst_alpha; m_funcs->glGetIntegerv(GL_BLEND_DST_ALPHA, &last_blend_dst_alpha); + GLint last_blend_equation_rgb; m_funcs->glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); + GLint last_blend_equation_alpha; m_funcs->glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); + GLint last_viewport[4]; m_funcs->glGetIntegerv(GL_VIEWPORT, last_viewport); + GLint last_scissor_box[4]; m_funcs->glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); + GLboolean last_enable_blend = m_funcs->glIsEnabled(GL_BLEND); + GLboolean last_enable_cull_face = m_funcs->glIsEnabled(GL_CULL_FACE); + GLboolean last_enable_depth_test = m_funcs->glIsEnabled(GL_DEPTH_TEST); + GLboolean last_enable_scissor_test = m_funcs->glIsEnabled(GL_SCISSOR_TEST); + + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled + m_funcs->glEnable(GL_BLEND); + m_funcs->glBlendEquation(GL_FUNC_ADD); + m_funcs->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + m_funcs->glDisable(GL_CULL_FACE); + m_funcs->glDisable(GL_DEPTH_TEST); + m_funcs->glEnable(GL_SCISSOR_TEST); + + // Setup viewport, orthographic projection matrix + m_funcs->glViewport(0, 0, static_cast(fb_width), static_cast(fb_height)); + const float ortho_projection[4][4] = { + { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + {-1.0f, 1.0f, 0.0f, 1.0f }, + }; + m_funcs->glUseProgram(m_shaderHandle); + m_funcs->glUniform1i(m_attribLocationTex, 0); + m_funcs->glUniformMatrix4fv(m_attribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); + m_funcs->glBindVertexArray(m_vaoHandle); + + for (int n = 0; n < draw_data->CmdListsCount; n++) { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawIdx* idx_buffer_offset = nullptr; + + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle); + m_funcs->glBufferData(GL_ARRAY_BUFFER, static_cast(cmd_list->VtxBuffer.Size) * sizeof(ImDrawVert), static_cast(cmd_list->VtxBuffer.Data), GL_STREAM_DRAW); + + m_funcs->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementsHandle); + m_funcs->glBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast(cmd_list->IdxBuffer.Size) * sizeof(ImDrawIdx), static_cast(cmd_list->IdxBuffer.Data), GL_STREAM_DRAW); + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) { + pcmd->UserCallback(cmd_list, pcmd); + } else { + m_funcs->glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); + m_funcs->glScissor(static_cast(pcmd->ClipRect.x), static_cast(fb_height - pcmd->ClipRect.w), + static_cast(pcmd->ClipRect.z - pcmd->ClipRect.x), static_cast(pcmd->ClipRect.w - pcmd->ClipRect.y)); + m_funcs->glDrawElements(GL_TRIANGLES, static_cast(pcmd->ElemCount), sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + } + idx_buffer_offset += pcmd->ElemCount; + } + } + + // Restore modified GL state + m_funcs->glUseProgram(last_program); + m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); + m_funcs->glActiveTexture(last_active_texture); + m_funcs->glBindVertexArray(last_vertex_array); + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); + m_funcs->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); + m_funcs->glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); + m_funcs->glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); + if (last_enable_blend) + m_funcs->glEnable(GL_BLEND); else m_funcs->glDisable(GL_BLEND); + if (last_enable_cull_face) + m_funcs->glEnable(GL_CULL_FACE); else m_funcs->glDisable(GL_CULL_FACE); + if (last_enable_depth_test) + m_funcs->glEnable(GL_DEPTH_TEST); else m_funcs->glDisable(GL_DEPTH_TEST); + if (last_enable_scissor_test) + m_funcs->glEnable(GL_SCISSOR_TEST); else m_funcs->glDisable(GL_SCISSOR_TEST); + m_funcs->glViewport(last_viewport[0], last_viewport[1], static_cast(last_viewport[2]), static_cast(last_viewport[3])); + m_funcs->glScissor(last_scissor_box[0], last_scissor_box[1], static_cast(last_scissor_box[2]), static_cast(last_scissor_box[3])); +} + +bool ImGuiRenderer::createFontsTexture() +{ + // Build texture atlas + ImGuiIO& io = ImGui::GetIO(); + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. + + // Upload texture to graphics system + GLint last_texture; + m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + m_funcs->glGenTextures(1, &m_fontTexture); + m_funcs->glBindTexture(GL_TEXTURE_2D, m_fontTexture); + m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + + // Store our identifier + io.Fonts->TexID = (void *)(intptr_t)m_fontTexture; + + // Restore state + m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); + + return true; +} + +bool ImGuiRenderer::createDeviceObjects() +{ + auto *glContext = m_renderer->submissionContext()->openGLContext(); + if (glContext->format().majorVersion() < 3) { + qWarning() << "Qt3D Profiling overlay requires GL or GL ES >= 3"; + return false; + } + + // Backup GL state + GLint last_texture, last_array_buffer, last_vertex_array; + m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + m_funcs->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + m_funcs->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + + const GLchar *vertex_shader = + "#version 330\n" + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n"; + + const GLchar* fragment_shader = + "#version 330\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main()\n" + "{\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n"; + + const GLchar *vertex_shader_es3 = + "#version 110\n" + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n"; + + const GLchar* fragment_shader_es3 = + "#version 110\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" + "}\n"; + +// m_shaderHandle = m_funcs->glCreateProgram(); +// m_vertHandle = m_funcs->glCreateShader(GL_VERTEX_SHADER); +// m_fragHandle = m_funcs->glCreateShader(GL_FRAGMENT_SHADER); +// auto *glContext = m_renderer->submissionContext()->openGLContext(); +// m_funcs->glShaderSource(m_vertHandle, 1, &vertex_shader, nullptr); +// m_funcs->glShaderSource(m_fragHandle, 1, &fragment_shader, nullptr); +// m_funcs->glCompileShader(m_vertHandle); +// m_funcs->glCompileShader(m_fragHandle); +// m_funcs->glAttachShader(m_shaderHandle, m_vertHandle); +// m_funcs->glAttachShader(m_shaderHandle, m_fragHandle); +// m_funcs->glLinkProgram(m_shaderHandle); + + QString logs; + m_shader = new QOpenGLShaderProgram(this); + if (glContext->isOpenGLES()) { + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader_es3)) + logs += m_shader->log(); + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader_es3)) + logs += m_shader->log(); + } else { + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader)) + logs += m_shader->log(); + if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader)) + logs += m_shader->log(); + } + m_shader->link(); + logs += m_shader->log(); + if (!logs.isEmpty()) + qWarning() << logs; + m_shaderHandle = m_shader->programId(); + + m_attribLocationTex = m_funcs->glGetUniformLocation(m_shaderHandle, "Texture"); + m_attribLocationProjMtx = m_funcs->glGetUniformLocation(m_shaderHandle, "ProjMtx"); + m_attribLocationPosition = m_funcs->glGetAttribLocation(m_shaderHandle, "Position"); + m_attribLocationUV = m_funcs->glGetAttribLocation(m_shaderHandle, "UV"); + m_attribLocationColor = m_funcs->glGetAttribLocation(m_shaderHandle, "Color"); + + m_funcs->glGenBuffers(1, &m_vboHandle); + m_funcs->glGenBuffers(1, &m_elementsHandle); + + m_funcs->glGenVertexArrays(1, &m_vaoHandle); + m_funcs->glBindVertexArray(m_vaoHandle); + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle); + m_funcs->glEnableVertexAttribArray(m_attribLocationPosition); + m_funcs->glEnableVertexAttribArray(m_attribLocationUV); + m_funcs->glEnableVertexAttribArray(m_attribLocationColor); + +#define OFFSETOF(TYPE, ELEMENT) (reinterpret_cast(&((static_cast(nullptr))->ELEMENT))) + m_funcs->glVertexAttribPointer(m_attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, pos))); + m_funcs->glVertexAttribPointer(m_attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, uv))); + m_funcs->glVertexAttribPointer(m_attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, col))); +#undef OFFSETOF + + createFontsTexture(); + + // Restore modified GL state + m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); + m_funcs->glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); + m_funcs->glBindVertexArray(last_vertex_array); + + return true; +} + +bool ImGuiRenderer::newFrame(const RenderView *renderView) +{ + if (!m_funcs) + m_funcs = m_renderer->submissionContext()->openGLContext()->extraFunctions(); + if (!m_fontTexture) + createDeviceObjects(); + if (!m_shader) + return false; + + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + io.DisplaySize = ImVec2(renderView->surfaceSize().width() / renderView->devicePixelRatio(), renderView->surfaceSize().height() / renderView->devicePixelRatio()); + io.DisplayFramebufferScale = ImVec2(renderView->devicePixelRatio(), renderView->devicePixelRatio()); + + // Setup time step + double current_time = QDateTime::currentMSecsSinceEpoch() / 1000.; + io.DeltaTime = m_time > 0.0 ? static_cast(current_time - m_time) : 1.0f / 60.0f; + if (io.DeltaTime == 0.f) + io.DeltaTime = 1.0f / 60.0f; + m_time = current_time; + + // Setup inputs + for (int i = 0; i < 3; i++) + io.MouseDown[i] = m_mousePressed[i]; + + io.MouseWheelH = m_mouseWheelH; + io.MouseWheel = m_mouseWheel; + m_mouseWheelH = 0; + m_mouseWheel = 0; + + // Start the frame + ImGui::NewFrame(); + return true; +} + +void ImGuiRenderer::onMouseChange(QMouseEvent *event) +{ + ImGuiIO& io = ImGui::GetIO(); + io.MousePos = ImVec2(event->pos().x(), event->pos().y()); + m_mousePressed[0] = event->buttons() & Qt::LeftButton; + m_mousePressed[1] = event->buttons() & Qt::RightButton; + m_mousePressed[2] = event->buttons() & Qt::MiddleButton; +} + +void ImGuiRenderer::onWheel(QWheelEvent *event) +{ + // 5 lines per unit + m_mouseWheelH += event->pixelDelta().x() / (ImGui::GetTextLineHeight()); + m_mouseWheel += event->pixelDelta().y() / (5.f * ImGui::GetTextLineHeight()); +} + +void ImGuiRenderer::onKeyPressRelease(QKeyEvent *event) +{ + ImGuiIO& io = ImGui::GetIO(); + if (keyMap.contains(event->key())) + io.KeysDown[keyMap[event->key()]] = event->type() == QEvent::KeyPress; + + if (event->type() == QEvent::KeyPress) { + QString text = event->text(); + if (text.size() == 1) + io.AddInputCharacter(static_cast(text.at(0).unicode())); + } + +#ifdef Q_OS_DARWIN + io.KeyCtrl = event->modifiers() & Qt::MetaModifier; + io.KeyShift = event->modifiers() & Qt::ShiftModifier; + io.KeyAlt = event->modifiers() & Qt::AltModifier; + io.KeySuper = event->modifiers() & Qt::ControlModifier; // Command key +#else + io.KeyCtrl = event->modifiers() & Qt::ControlModifier; + io.KeyShift = event->modifiers() & Qt::ShiftModifier; + io.KeyAlt = event->modifiers() & Qt::AltModifier; + io.KeySuper = event->modifiers() & Qt::MetaModifier; +#endif +} + +void ImGuiRenderer::processEvent(QEvent *event) +{ + switch (event->type()) { + case QEvent::MouseMove: + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + this->onMouseChange(static_cast(event)); + break; + case QEvent::Wheel: + this->onWheel(static_cast(event)); + break; + case QEvent::KeyPress: + case QEvent::KeyRelease: + this->onKeyPressRelease(static_cast(event)); + break; + default: + break; + } +} + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/debug/imguirenderer_p.h b/src/plugins/renderers/opengl/debug/imguirenderer_p.h new file mode 100644 index 000000000..e574574be --- /dev/null +++ b/src/plugins/renderers/opengl/debug/imguirenderer_p.h @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3D_RENDER_GL_IMGUIRENDER_H_ +#define QT3D_RENDER_GL_IMGUIRENDER_H_ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include + +struct ImDrawData; + +QT_BEGIN_NAMESPACE + +class QMouseEvent; +class QWheelEvent; +class QKeyEvent; +class QOpenGLExtraFunctions; +class QOpenGLShaderProgram; + +namespace Qt3DCore { +class QServiceLocator; +} + +namespace Qt3DRender { +namespace Render { + +class RenderView; +class Renderer; + +namespace Debug { + +#define IMGUI_PERF_LOG_SIZE 30 + +class ImGuiRenderer : public QObject { + Q_OBJECT +public: + ImGuiRenderer(Qt3DRender::Render::Renderer *renderer); + + void processEvent(QEvent *event); + void renderDebugOverlay(const QVector &renderViews, const Render::RenderView *renderView, int jobsInLastFrame); + + void setCapabilities(const QString &capabilities); + +private: + bool newFrame(const RenderView *renderView); + void renderDrawList(ImDrawData *draw_data); + void onMouseChange(QMouseEvent *event); + void onWheel(QWheelEvent *event); + void onKeyPressRelease(QKeyEvent *event); + void showGLInfo(); + void showRenderDetails(const QVector &renderViews); + + bool createFontsTexture(); + bool createDeviceObjects(); + + double m_time = 0.; + bool m_mousePressed[3] = { false, false, false }; + float m_mouseWheel; + float m_mouseWheelH; + GLuint m_fontTexture = 0; + GLuint m_shaderHandle = 0, m_vertHandle = 0, m_fragHandle = 0; + int m_attribLocationTex = 0, m_attribLocationProjMtx = 0; + int m_attribLocationPosition = 0, m_attribLocationUV = 0, m_attribLocationColor = 0; + unsigned int m_vboHandle = 0, m_vaoHandle = 0, m_elementsHandle = 0; + + Renderer *m_renderer; + QOpenGLExtraFunctions *m_funcs = nullptr; + QOpenGLShaderProgram *m_shader = nullptr; + + bool m_showGLInfoWindow = false; + bool m_showRenderDetailsWindow = false; + + float m_fpsLog[IMGUI_PERF_LOG_SIZE]; + float m_jobsLog[IMGUI_PERF_LOG_SIZE]; + std::pair m_fpsRange; + std::pair m_jobsRange; + + QByteArray m_capabilities; +}; + +} // namespace Debug +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3D_RENDER_GL_IMGUIRENDER_H_ diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp new file mode 100644 index 000000000..abe11fd4d --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp @@ -0,0 +1,1028 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicscontext_p.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(QT_OPENGL_ES_2) +#include +#include +#include +#include +#include +#include +#include +#include +#endif +#include +#include +#include +#include + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +#ifndef GL_READ_FRAMEBUFFER +#define GL_READ_FRAMEBUFFER 0x8CA8 +#endif + +#ifndef GL_DRAW_FRAMEBUFFER +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#endif + +#ifndef GL_MAX_IMAGE_UNITS +#define GL_MAX_IMAGE_UNITS 0x8F38 +#endif + +namespace { + +QOpenGLShader::ShaderType shaderType(Qt3DRender::QShaderProgram::ShaderType type) +{ + switch (type) { + case Qt3DRender::QShaderProgram::Vertex: return QOpenGLShader::Vertex; + case Qt3DRender::QShaderProgram::TessellationControl: return QOpenGLShader::TessellationControl; + case Qt3DRender::QShaderProgram::TessellationEvaluation: return QOpenGLShader::TessellationEvaluation; + case Qt3DRender::QShaderProgram::Geometry: return QOpenGLShader::Geometry; + case Qt3DRender::QShaderProgram::Fragment: return QOpenGLShader::Fragment; + case Qt3DRender::QShaderProgram::Compute: return QOpenGLShader::Compute; + default: Q_UNREACHABLE(); + } +} + +} // anonymous namespace + +namespace Qt3DRender { +namespace Render { + +namespace { + +void logOpenGLDebugMessage(const QOpenGLDebugMessage &debugMessage) +{ + qDebug() << "OpenGL debug message:" << debugMessage; +} + +} // anonymous + +GraphicsContext::GraphicsContext() + : m_initialized(false) + , m_supportsVAO(false) + , m_maxTextureUnits(0) + , m_maxImageUnits(0) + , m_defaultFBO(0) + , m_gl(nullptr) + , m_glHelper(nullptr) + , m_debugLogger(nullptr) + , m_currentVAO(nullptr) +{ +} + +GraphicsContext::~GraphicsContext() +{ +} + +void GraphicsContext::setOpenGLContext(QOpenGLContext* ctx) +{ + Q_ASSERT(ctx); + m_gl = ctx; +} + +void GraphicsContext::initialize() +{ + m_initialized = true; + + Q_ASSERT(m_gl); + + m_gl->functions()->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &m_maxTextureUnits); + qCDebug(Backend) << "context supports" << m_maxTextureUnits << "texture units"; + m_gl->functions()->glGetIntegerv(GL_MAX_IMAGE_UNITS, &m_maxImageUnits); + qCDebug(Backend) << "context supports" << m_maxImageUnits << "image units"; + + if (m_gl->format().majorVersion() >= 3) { + m_supportsVAO = true; + } else { + QSet extensions = m_gl->extensions(); + m_supportsVAO = extensions.contains(QByteArrayLiteral("GL_OES_vertex_array_object")) + || extensions.contains(QByteArrayLiteral("GL_ARB_vertex_array_object")) + || extensions.contains(QByteArrayLiteral("GL_APPLE_vertex_array_object")); + } + + m_defaultFBO = m_gl->defaultFramebufferObject(); + qCDebug(Backend) << "VAO support = " << m_supportsVAO; +} + +void GraphicsContext::clearBackBuffer(QClearBuffers::BufferTypeFlags buffers) +{ + if (buffers != QClearBuffers::None) { + GLbitfield mask = 0; + + if (buffers & QClearBuffers::ColorBuffer) + mask |= GL_COLOR_BUFFER_BIT; + if (buffers & QClearBuffers::DepthBuffer) + mask |= GL_DEPTH_BUFFER_BIT; + if (buffers & QClearBuffers::StencilBuffer) + mask |= GL_STENCIL_BUFFER_BIT; + + m_gl->functions()->glClear(mask); + } +} + +bool GraphicsContext::hasValidGLHelper() const +{ + return m_glHelper != nullptr; +} + +bool GraphicsContext::isInitialized() const +{ + return m_initialized; +} + +bool GraphicsContext::makeCurrent(QSurface *surface) +{ + Q_ASSERT(m_gl); + if (!m_gl->makeCurrent(surface)) { + qCWarning(Backend) << Q_FUNC_INFO << "makeCurrent failed"; + return false; + } + + initializeHelpers(surface); + + return true; +} + +void GraphicsContext::initializeHelpers(QSurface *surface) +{ + // Set the correct GL Helper depending on the surface + // If no helper exists, create one + m_glHelper = m_glHelpers.value(surface); + if (!m_glHelper) { + m_glHelper = resolveHighestOpenGLFunctions(); + m_glHelpers.insert(surface, m_glHelper); + } +} + +void GraphicsContext::doneCurrent() +{ + Q_ASSERT(m_gl); + m_gl->doneCurrent(); + m_glHelper = nullptr; +} + +// Called by GL Command Thread +GraphicsContext::ShaderCreationInfo GraphicsContext::createShaderProgram(GLShader *shader) +{ + QOpenGLShaderProgram *shaderProgram = shader->shaderProgram(); + + // Compile shaders + const auto shaderCode = shader->shaderCode(); + + QString logs; + for (int i = QShaderProgram::Vertex; i <= QShaderProgram::Compute; ++i) { + const QShaderProgram::ShaderType type = static_cast(i); + if (!shaderCode.at(i).isEmpty()) { + // Note: logs only return the error but not all the shader code + // we could append it + if (!shaderProgram->addCacheableShaderFromSourceCode(shaderType(type), shaderCode.at(i))) + logs += shaderProgram->log(); + } + } + + // Call glBindFragDataLocation and link the program + // Since we are sharing shaders in the backend, we assume that if using custom + // fragOutputs, they should all be the same for a given shader + bindFragOutputs(shaderProgram->programId(), shader->fragOutputs()); + + const bool linkSucceeded = shaderProgram->link(); + logs += shaderProgram->log(); + + // Perform shader introspection + introspectShaderInterface(shader); + + ShaderCreationInfo info; + info.linkSucceeded = linkSucceeded; + info.logs = logs; + + return info; +} + +// That assumes that the shaderProgram in Shader stays the same +void GraphicsContext::introspectShaderInterface(GLShader *shader) +{ + QOpenGLShaderProgram *shaderProgram = shader->shaderProgram(); + GraphicsHelperInterface *glHelper = resolveHighestOpenGLFunctions(); + shader->initializeUniforms(glHelper->programUniformsAndLocations(shaderProgram->programId())); + shader->initializeAttributes(glHelper->programAttributesAndLocations(shaderProgram->programId())); + if (m_glHelper->supportsFeature(GraphicsHelperInterface::UniformBufferObject)) + shader->initializeUniformBlocks(m_glHelper->programUniformBlocks(shaderProgram->programId())); + if (m_glHelper->supportsFeature(GraphicsHelperInterface::ShaderStorageObject)) + shader->initializeShaderStorageBlocks(m_glHelper->programShaderStorageBlocks(shaderProgram->programId())); +} + + +// Called by Renderer::updateGLResources +void GraphicsContext::loadShader(Shader *shaderNode, + ShaderManager *shaderManager, + GLShaderManager *glShaderManager) +{ + const Qt3DCore::QNodeId shaderId = shaderNode->peerId(); + GLShader *glShader = glShaderManager->lookupResource(shaderId); + + // We already have a shader associated with the node + if (glShader != nullptr) { + // We need to abandon it + glShaderManager->abandon(glShader, shaderNode); + } + + // We create or adopt an already created glShader + glShader = glShaderManager->createOrAdoptExisting(shaderNode); + + const QVector sharedShaderIds = glShaderManager->shaderIdsForProgram(glShader); + if (sharedShaderIds.size() == 1) { + // Shader in the cache hasn't been loaded yet + glShader->setGraphicsContext(this); + glShader->setShaderCode(shaderNode->shaderCode()); + const ShaderCreationInfo loadResult = createShaderProgram(glShader); + shaderNode->setStatus(loadResult.linkSucceeded ? QShaderProgram::Ready : QShaderProgram::Error); + shaderNode->setLog(loadResult.logs); + // Loaded in the sense we tried to load it (and maybe it failed) + glShader->setLoaded(true); + } else { + // Find an already loaded shader that shares the same QOpenGLShaderProgram + for (const Qt3DCore::QNodeId sharedShaderId : sharedShaderIds) { + if (sharedShaderId != shaderNode->peerId()) { + Shader *refShader = shaderManager->lookupResource(sharedShaderId); + // We only introspect once per actual OpenGL shader program + // rather than once per ShaderNode. + shaderNode->initializeFromReference(*refShader); + break; + } + } + } + shaderNode->unsetDirty(); + // Ensure we will rebuilt material caches + shaderNode->markDirty(AbstractRenderer::AllDirty); +} + +void GraphicsContext::activateDrawBuffers(const AttachmentPack &attachments) +{ + const QVector activeDrawBuffers = attachments.getGlDrawBuffers(); + + if (m_glHelper->checkFrameBufferComplete()) { + if (activeDrawBuffers.size() > 1) {// We need MRT + if (m_glHelper->supportsFeature(GraphicsHelperInterface::MRT)) { + // Set up MRT, glDrawBuffers... + m_glHelper->drawBuffers(activeDrawBuffers.size(), activeDrawBuffers.data()); + } + } + } else { + qWarning() << "FBO incomplete"; + } +} + +void GraphicsContext::rasterMode(GLenum faceMode, GLenum rasterMode) +{ + m_glHelper->rasterMode(faceMode, rasterMode); +} + +/*! + * \internal + * Finds the highest supported opengl version and internally use the most optimized + * helper for a given version. + */ +GraphicsHelperInterface *GraphicsContext::resolveHighestOpenGLFunctions() +{ + Q_ASSERT(m_gl); + GraphicsHelperInterface *glHelper = nullptr; + + if (m_gl->isOpenGLES()) { + if (m_gl->format().majorVersion() >= 3) { + if (m_gl->format().minorVersion() >= 2) { + glHelper = new GraphicsHelperES3_2; + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES 3.2 Helper"; + } else if (m_gl->format().minorVersion() >= 1) { + glHelper = new GraphicsHelperES3_1; + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES 3.1 Helper"; + } else { + glHelper = new GraphicsHelperES3(); + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES 3.0 Helper"; + } + } else { + glHelper = new GraphicsHelperES2(); + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES2 Helper"; + } + glHelper->initializeHelper(m_gl, nullptr); + } +#ifndef QT_OPENGL_ES_2 + else { + QAbstractOpenGLFunctions *glFunctions = nullptr; + if ((glFunctions = m_gl->versionFunctions()) != nullptr) { + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 4.3"; + glHelper = new GraphicsHelperGL4(); + } else if ((glFunctions = m_gl->versionFunctions()) != nullptr) { + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 3.3"; + glHelper = new GraphicsHelperGL3_3(); + } else if ((glFunctions = m_gl->versionFunctions()) != nullptr) { + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 3.2"; + glHelper = new GraphicsHelperGL3_2(); + } else if ((glFunctions = m_gl->versionFunctions()) != nullptr) { + qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 2 Helper"; + glHelper = new GraphicsHelperGL2(); + } + Q_ASSERT_X(glHelper, "GraphicsContext::resolveHighestOpenGLFunctions", "unable to create valid helper for available OpenGL version"); + glHelper->initializeHelper(m_gl, glFunctions); + } +#endif + + // Note: at this point we are certain the context (m_gl) is current with a surface + const QByteArray debugLoggingMode = qgetenv("QT3DRENDER_DEBUG_LOGGING"); + const bool enableDebugLogging = !debugLoggingMode.isEmpty(); + + if (enableDebugLogging && !m_debugLogger) { + if (m_gl->hasExtension("GL_KHR_debug")) { + qCDebug(Backend) << "Qt3D: Enabling OpenGL debug logging"; + m_debugLogger.reset(new QOpenGLDebugLogger); + if (m_debugLogger->initialize()) { + QObject::connect(m_debugLogger.data(), &QOpenGLDebugLogger::messageLogged, &logOpenGLDebugMessage); + const QString mode = QString::fromLocal8Bit(debugLoggingMode); + m_debugLogger->startLogging(mode.startsWith(QLatin1String("sync"), Qt::CaseInsensitive) + ? QOpenGLDebugLogger::SynchronousLogging + : QOpenGLDebugLogger::AsynchronousLogging); + + const auto msgs = m_debugLogger->loggedMessages(); + for (const QOpenGLDebugMessage &msg : msgs) + logOpenGLDebugMessage(msg); + } + } else { + qCDebug(Backend) << "Qt3D: OpenGL debug logging requested but GL_KHR_debug not supported"; + } + } + + + // Set Vendor and Extensions of reference GraphicsApiFilter + // TO DO: would that vary like the glHelper ? + + QStringList extensions; + const auto exts = m_gl->extensions(); + for (const QByteArray &ext : exts) + extensions << QString::fromUtf8(ext); + m_contextInfo.m_major = m_gl->format().version().first; + m_contextInfo.m_minor = m_gl->format().version().second; + m_contextInfo.m_api = m_gl->isOpenGLES() ? QGraphicsApiFilter::OpenGLES : QGraphicsApiFilter::OpenGL; + m_contextInfo.m_profile = static_cast(m_gl->format().profile()); + m_contextInfo.m_extensions = extensions; + m_contextInfo.m_vendor = QString::fromUtf8(reinterpret_cast(m_gl->functions()->glGetString(GL_VENDOR))); + + return glHelper; +} + +const GraphicsApiFilterData *GraphicsContext::contextInfo() const +{ + return &m_contextInfo; +} + +bool GraphicsContext::supportsDrawBuffersBlend() const +{ + return m_glHelper->supportsFeature(GraphicsHelperInterface::DrawBuffersBlend); +} + +/*! + * \internal + * Wraps an OpenGL call to glDrawElementsInstanced. + * If the call is not supported by the system's OpenGL version, + * it is simulated with a loop. + */ +void GraphicsContext::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + m_glHelper->drawElementsInstancedBaseVertexBaseInstance(primitiveType, + primitiveCount, + indexType, + indices, + instances, + baseVertex, + baseInstance); +} + +/*! + * \internal + * Wraps an OpenGL call to glDrawArraysInstanced. + */ +void GraphicsContext::drawArraysInstanced(GLenum primitiveType, + GLint first, + GLsizei count, + GLsizei instances) +{ + m_glHelper->drawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsContext::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseinstance) +{ + m_glHelper->drawArraysInstancedBaseInstance(primitiveType, + first, + count, + instances, + baseinstance); +} + +/*! + * \internal + * Wraps an OpenGL call to glDrawElements. + */ +void GraphicsContext::drawElements(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLint baseVertex) +{ + m_glHelper->drawElements(primitiveType, + primitiveCount, + indexType, + indices, + baseVertex); +} + +void GraphicsContext::drawElementsIndirect(GLenum mode, + GLenum type, + void *indirect) +{ + m_glHelper->drawElementsIndirect(mode, type, indirect); +} + +/*! + * \internal + * Wraps an OpenGL call to glDrawArrays. + */ +void GraphicsContext::drawArrays(GLenum primitiveType, + GLint first, + GLsizei count) +{ + m_glHelper->drawArrays(primitiveType, + first, + count); +} + +void GraphicsContext::drawArraysIndirect(GLenum mode, void *indirect) +{ + m_glHelper->drawArraysIndirect(mode, indirect); +} + +void GraphicsContext::setVerticesPerPatch(GLint verticesPerPatch) +{ + m_glHelper->setVerticesPerPatch(verticesPerPatch); +} + +void GraphicsContext::blendEquation(GLenum mode) +{ + m_glHelper->blendEquation(mode); +} + +void GraphicsContext::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) +{ + m_glHelper->blendFunci(buf, sfactor, dfactor); +} + +void GraphicsContext::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) +{ + m_glHelper->blendFuncSeparatei(buf, sRGB, dRGB, sAlpha, dAlpha); +} + +void GraphicsContext::alphaTest(GLenum mode1, GLenum mode2) +{ + m_glHelper->alphaTest(mode1, mode2); +} + +void GraphicsContext::bindFramebuffer(GLuint fbo, GraphicsHelperInterface::FBOBindMode mode) +{ + m_glHelper->bindFrameBufferObject(fbo, mode); +} + +void GraphicsContext::depthRange(GLdouble nearValue, GLdouble farValue) +{ + m_glHelper->depthRange(nearValue, farValue); +} + +void GraphicsContext::depthTest(GLenum mode) +{ + m_glHelper->depthTest(mode); +} + +void GraphicsContext::depthMask(GLenum mode) +{ + m_glHelper->depthMask(mode); +} + +void GraphicsContext::frontFace(GLenum mode) +{ + m_glHelper->frontFace(mode); +} + +void GraphicsContext::bindFragOutputs(GLuint shader, const QHash &outputs) +{ + if (m_glHelper->supportsFeature(GraphicsHelperInterface::MRT) && + m_glHelper->supportsFeature(GraphicsHelperInterface::BindableFragmentOutputs)) + m_glHelper->bindFragDataLocation(shader, outputs); +} + +void GraphicsContext::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + m_glHelper->bindImageTexture(imageUnit, + texture, + mipLevel, + layered, + layer, + access, + format); +} + +void GraphicsContext::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + m_glHelper->bindUniformBlock(programId, uniformBlockIndex, uniformBlockBinding); +} + +void GraphicsContext::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) +{ + m_glHelper->bindShaderStorageBlock(programId, shaderStorageBlockIndex, shaderStorageBlockBinding); +} + +void GraphicsContext::bindBufferBase(GLenum target, GLuint bindingIndex, GLuint buffer) +{ + m_glHelper->bindBufferBase(target, bindingIndex, buffer); +} + +void GraphicsContext::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + m_glHelper->buildUniformBuffer(v, description, buffer); +} + +void GraphicsContext::setMSAAEnabled(bool enabled) +{ + m_glHelper->setMSAAEnabled(enabled); +} + +void GraphicsContext::setAlphaCoverageEnabled(bool enabled) +{ + m_glHelper->setAlphaCoverageEnabled(enabled); +} + +void GraphicsContext::clearBufferf(GLint drawbuffer, const QVector4D &values) +{ + m_glHelper->clearBufferf(drawbuffer, values); +} + +GLuint GraphicsContext::boundFrameBufferObject() +{ + return m_glHelper->boundFrameBufferObject(); +} + +void GraphicsContext::clearColor(const QColor &color) +{ + m_gl->functions()->glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); +} + +void GraphicsContext::clearDepthValue(float depth) +{ + m_gl->functions()->glClearDepthf(depth); +} + +void GraphicsContext::clearStencilValue(int stencil) +{ + m_gl->functions()->glClearStencil(stencil); +} + +void GraphicsContext::enableClipPlane(int clipPlane) +{ + m_glHelper->enableClipPlane(clipPlane); +} + +void GraphicsContext::disableClipPlane(int clipPlane) +{ + m_glHelper->disableClipPlane(clipPlane); +} + +void GraphicsContext::setClipPlane(int clipPlane, const QVector3D &normal, float distance) +{ + m_glHelper->setClipPlane(clipPlane, normal, distance); +} + +GLint GraphicsContext::maxClipPlaneCount() +{ + return m_glHelper->maxClipPlaneCount(); +} + +GLint GraphicsContext::maxTextureUnitsCount() const +{ + return m_maxTextureUnits; +} + +GLint GraphicsContext::maxImageUnitsCount() const +{ + return m_maxImageUnits; +} + + +void GraphicsContext::enablePrimitiveRestart(int restartIndex) +{ + if (m_glHelper->supportsFeature(GraphicsHelperInterface::PrimitiveRestart)) + m_glHelper->enablePrimitiveRestart(restartIndex); +} + +void GraphicsContext::disablePrimitiveRestart() +{ + if (m_glHelper->supportsFeature(GraphicsHelperInterface::PrimitiveRestart)) + m_glHelper->disablePrimitiveRestart(); +} + +void GraphicsContext::pointSize(bool programmable, GLfloat value) +{ + m_glHelper->pointSize(programmable, value); +} + +void GraphicsContext::dispatchCompute(int x, int y, int z) +{ + if (m_glHelper->supportsFeature(GraphicsHelperInterface::Compute)) + m_glHelper->dispatchCompute(x, y, z); +} + +GLboolean GraphicsContext::unmapBuffer(GLenum target) +{ + return m_glHelper->unmapBuffer(target); +} + +char *GraphicsContext::mapBuffer(GLenum target, GLsizeiptr size) +{ + return m_glHelper->mapBuffer(target, size); +} + +void GraphicsContext::enablei(GLenum cap, GLuint index) +{ + m_glHelper->enablei(cap, index); +} + +void GraphicsContext::disablei(GLenum cap, GLuint index) +{ + m_glHelper->disablei(cap, index); +} + +void GraphicsContext::setSeamlessCubemap(bool enable) +{ + m_glHelper->setSeamlessCubemap(enable); +} + +void GraphicsContext::readBuffer(GLenum mode) +{ + m_glHelper->readBuffer(mode); +} + +void GraphicsContext::drawBuffer(GLenum mode) +{ + m_glHelper->drawBuffer(mode); +} + +void GraphicsContext::drawBuffers(GLsizei n, const int *bufs) +{ + m_glHelper->drawBuffers(n, bufs); +} + +void GraphicsContext::applyUniform(const ShaderUniform &description, const UniformValue &v) +{ + const UniformType type = m_glHelper->uniformTypeFromGLType(description.m_type); + + switch (type) { + case UniformType::Float: + // See QTBUG-57510 and uniform_p.h + if (v.storedType() == Int) { + float value = float(*v.constData()); + UniformValue floatV(value); + applyUniformHelper(description, floatV); + } else { + applyUniformHelper(description, v); + } + break; + case UniformType::Vec2: + applyUniformHelper(description, v); + break; + case UniformType::Vec3: + applyUniformHelper(description, v); + break; + case UniformType::Vec4: + applyUniformHelper(description, v); + break; + + case UniformType::Double: + applyUniformHelper(description, v); + break; + case UniformType::DVec2: + applyUniformHelper(description, v); + break; + case UniformType::DVec3: + applyUniformHelper(description, v); + break; + case UniformType::DVec4: + applyUniformHelper(description, v); + break; + + case UniformType::Sampler: + case UniformType::Image: + case UniformType::Int: + applyUniformHelper(description, v); + break; + case UniformType::IVec2: + applyUniformHelper(description, v); + break; + case UniformType::IVec3: + applyUniformHelper(description, v); + break; + case UniformType::IVec4: + applyUniformHelper(description, v); + break; + + case UniformType::UInt: + applyUniformHelper(description, v); + break; + case UniformType::UIVec2: + applyUniformHelper(description, v); + break; + case UniformType::UIVec3: + applyUniformHelper(description, v); + break; + case UniformType::UIVec4: + applyUniformHelper(description, v); + break; + + case UniformType::Bool: + applyUniformHelper(description, v); + break; + case UniformType::BVec2: + applyUniformHelper(description, v); + break; + case UniformType::BVec3: + applyUniformHelper(description, v); + break; + case UniformType::BVec4: + applyUniformHelper(description, v); + break; + + case UniformType::Mat2: + applyUniformHelper(description, v); + break; + case UniformType::Mat3: + applyUniformHelper(description, v); + break; + case UniformType::Mat4: + applyUniformHelper(description, v); + break; + case UniformType::Mat2x3: + applyUniformHelper(description, v); + break; + case UniformType::Mat3x2: + applyUniformHelper(description, v); + break; + case UniformType::Mat2x4: + applyUniformHelper(description, v); + break; + case UniformType::Mat4x2: + applyUniformHelper(description, v); + break; + case UniformType::Mat3x4: + applyUniformHelper(description, v); + break; + case UniformType::Mat4x3: + applyUniformHelper(description, v); + break; + + default: + break; + } +} + +void GraphicsContext::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + m_glHelper->memoryBarrier(barriers); +} + +GLint GraphicsContext::elementType(GLint type) +{ + switch (type) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + return GL_FLOAT; + +#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 + case GL_DOUBLE: +#ifdef GL_DOUBLE_VEC3 // For compiling on pre GL 4.1 systems + case GL_DOUBLE_VEC2: + case GL_DOUBLE_VEC3: + case GL_DOUBLE_VEC4: +#endif + return GL_DOUBLE; +#endif + default: + qWarning() << Q_FUNC_INFO << "unsupported:" << QString::number(type, 16); + } + + return GL_INVALID_VALUE; +} + +GLint GraphicsContext::tupleSizeFromType(GLint type) +{ + switch (type) { + case GL_FLOAT: +#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 + case GL_DOUBLE: +#endif + case GL_UNSIGNED_BYTE: + case GL_UNSIGNED_INT: + break; // fall through + + case GL_FLOAT_VEC2: +#ifdef GL_DOUBLE_VEC2 // For compiling on pre GL 4.1 systems. + case GL_DOUBLE_VEC2: +#endif + return 2; + + case GL_FLOAT_VEC3: +#ifdef GL_DOUBLE_VEC3 // For compiling on pre GL 4.1 systems. + case GL_DOUBLE_VEC3: +#endif + return 3; + + case GL_FLOAT_VEC4: +#ifdef GL_DOUBLE_VEC4 // For compiling on pre GL 4.1 systems. + case GL_DOUBLE_VEC4: +#endif + return 4; + + default: + qWarning() << Q_FUNC_INFO << "unsupported:" << QString::number(type, 16); + } + + return 1; +} + +GLuint GraphicsContext::byteSizeFromType(GLint type) +{ + switch (type) { + case GL_FLOAT: return sizeof(float); +#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 + case GL_DOUBLE: return sizeof(double); +#endif + case GL_UNSIGNED_BYTE: return sizeof(unsigned char); + case GL_UNSIGNED_INT: return sizeof(GLuint); + + case GL_FLOAT_VEC2: return sizeof(float) * 2; + case GL_FLOAT_VEC3: return sizeof(float) * 3; + case GL_FLOAT_VEC4: return sizeof(float) * 4; +#ifdef GL_DOUBLE_VEC3 // Required to compile on pre GL 4.1 systems + case GL_DOUBLE_VEC2: return sizeof(double) * 2; + case GL_DOUBLE_VEC3: return sizeof(double) * 3; + case GL_DOUBLE_VEC4: return sizeof(double) * 4; +#endif + default: + qWarning() << Q_FUNC_INFO << "unsupported:" << QString::number(type, 16); + } + + return 0; +} + +GLint GraphicsContext::glDataTypeFromAttributeDataType(QAttribute::VertexBaseType dataType) +{ + switch (dataType) { + case QAttribute::Byte: + return GL_BYTE; + case QAttribute::UnsignedByte: + return GL_UNSIGNED_BYTE; + case QAttribute::Short: + return GL_SHORT; + case QAttribute::UnsignedShort: + return GL_UNSIGNED_SHORT; + case QAttribute::Int: + return GL_INT; + case QAttribute::UnsignedInt: + return GL_UNSIGNED_INT; + case QAttribute::HalfFloat: +#ifdef GL_HALF_FLOAT + return GL_HALF_FLOAT; +#endif +#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 + case QAttribute::Double: + return GL_DOUBLE; +#endif + case QAttribute::Float: + break; + default: + qWarning() << Q_FUNC_INFO << "unsupported dataType:" << dataType; + } + return GL_FLOAT; +} + +QT3D_UNIFORM_TYPE_IMPL(UniformType::Float, float, glUniform1fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Vec2, float, glUniform2fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Vec3, float, glUniform3fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Vec4, float, glUniform4fv) + +// OpenGL expects int* as values for booleans +QT3D_UNIFORM_TYPE_IMPL(UniformType::Bool, int, glUniform1iv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::BVec2, int, glUniform2iv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::BVec3, int, glUniform3iv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::BVec4, int, glUniform4iv) + +QT3D_UNIFORM_TYPE_IMPL(UniformType::Int, int, glUniform1iv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::IVec2, int, glUniform2iv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::IVec3, int, glUniform3iv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::IVec4, int, glUniform4iv) + +QT3D_UNIFORM_TYPE_IMPL(UniformType::UInt, uint, glUniform1uiv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::UIVec2, uint, glUniform2uiv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::UIVec3, uint, glUniform3uiv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::UIVec4, uint, glUniform4uiv) + +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat2, float, glUniformMatrix2fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3, float, glUniformMatrix3fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4, float, glUniformMatrix4fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat2x3, float, glUniformMatrix2x3fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3x2, float, glUniformMatrix3x2fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat2x4, float, glUniformMatrix2x4fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4x2, float, glUniformMatrix4x2fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3x4, float, glUniformMatrix3x4fv) +QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4x3, float, glUniformMatrix4x3fv) + +} // namespace Render +} // namespace Qt3DRender of namespace + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h new file mode 100644 index 000000000..07df3e9e4 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h @@ -0,0 +1,264 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSCONTEXT_H +#define QT3DRENDER_RENDER_GRAPHICSCONTEXT_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLShaderProgram; +class QAbstractOpenGLFunctions; +class QOpenGLDebugLogger; + +namespace Qt3DRender { + +namespace Render { + +class GraphicsHelperInterface; +class RenderTarget; +class AttachmentPack; +class ShaderManager; +class GLShader; +class GLShaderManager; + +typedef QPair NamedUniformLocation; + +class Q_AUTOTEST_EXPORT GraphicsContext +{ +public: + GraphicsContext(); + ~GraphicsContext(); + + void setOpenGLContext(QOpenGLContext* ctx); + QOpenGLContext *openGLContext() { return m_gl; } + bool makeCurrent(QSurface *surface); + void doneCurrent(); + bool hasValidGLHelper() const; + bool isInitialized() const; + + // Shaders + struct ShaderCreationInfo + { + bool linkSucceeded = false; + QString logs; + }; + + ShaderCreationInfo createShaderProgram(GLShader *shaderNode); + void introspectShaderInterface(GLShader *shader); + void loadShader(Shader* shader, ShaderManager *shaderManager, GLShaderManager *glShaderManager); + + GLuint defaultFBO() const { return m_defaultFBO; } + + const GraphicsApiFilterData *contextInfo() const; + + // Wrapper methods + void clearBackBuffer(QClearBuffers::BufferTypeFlags buffers); + void alphaTest(GLenum mode1, GLenum mode2); + void bindFramebuffer(GLuint fbo, GraphicsHelperInterface::FBOBindMode mode); + void bindBufferBase(GLenum target, GLuint bindingIndex, GLuint buffer); + void bindFragOutputs(GLuint shader, const QHash &outputs); + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format); + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding); + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding); + void blendEquation(GLenum mode); + void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor); + void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha); + GLuint boundFrameBufferObject(); + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer); + void clearBufferf(GLint drawbuffer, const QVector4D &values); + void clearColor(const QColor &color); + void clearDepthValue(float depth); + void clearStencilValue(int stencil); + void depthRange(GLdouble nearValue, GLdouble farValue); + void depthMask(GLenum mode); + void depthTest(GLenum mode); + void disableClipPlane(int clipPlane); + void disablei(GLenum cap, GLuint index); + void disablePrimitiveRestart(); + void dispatchCompute(int x, int y, int z); + char * mapBuffer(GLenum target, GLsizeiptr size); + GLboolean unmapBuffer(GLenum target); + void drawArrays(GLenum primitiveType, GLint first, GLsizei count); + void drawArraysIndirect(GLenum mode,void *indirect); + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances); + void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseinstance); + void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLint baseVertex); + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect); + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLsizei instances, GLint baseVertex, GLint baseInstance); + void enableClipPlane(int clipPlane); + void enablei(GLenum cap, GLuint index); + void enablePrimitiveRestart(int restartIndex); + void frontFace(GLenum mode); + GLint maxClipPlaneCount(); + GLint maxTextureUnitsCount() const; + GLint maxImageUnitsCount() const; + void pointSize(bool programmable, GLfloat value); + void readBuffer(GLenum mode); + void drawBuffer(GLenum mode); + void drawBuffers(GLsizei n, const int *bufs); + void setMSAAEnabled(bool enabled); + void setAlphaCoverageEnabled(bool enabled); + void setClipPlane(int clipPlane, const QVector3D &normal, float distance); + void setSeamlessCubemap(bool enable); + void setVerticesPerPatch(GLint verticesPerPatch); + void memoryBarrier(QMemoryBarrier::Operations barriers); + void activateDrawBuffers(const AttachmentPack &attachments); + void rasterMode(GLenum faceMode, GLenum rasterMode); + + // Helper methods + static GLint elementType(GLint type); + static GLint tupleSizeFromType(GLint type); + static GLuint byteSizeFromType(GLint type); + static GLint glDataTypeFromAttributeDataType(QAttribute::VertexBaseType dataType); + + bool supportsDrawBuffersBlend() const; + bool supportsVAO() const { return m_supportsVAO; } + + void initialize(); + void initializeHelpers(QSurface *surface); + GraphicsHelperInterface *resolveHighestOpenGLFunctions(); + + bool m_initialized; + bool m_supportsVAO; + GLint m_maxTextureUnits; + GLint m_maxImageUnits; + GLuint m_defaultFBO; + QOpenGLContext *m_gl; + GraphicsHelperInterface *m_glHelper; + + QHash m_glHelpers; + GraphicsApiFilterData m_contextInfo; + QScopedPointer m_debugLogger; + + friend class OpenGLVertexArrayObject; + OpenGLVertexArrayObject *m_currentVAO; + + void applyUniform(const ShaderUniform &description, const UniformValue &v); + + template + void applyUniformHelper(const ShaderUniform &, const UniformValue &) const + { + Q_ASSERT_X(false, Q_FUNC_INFO, "Uniform: Didn't provide specialized apply() implementation"); + } +}; + +#define QT3D_UNIFORM_TYPE_PROTO(UniformTypeEnum, BaseType, Func) \ +template<> \ +void GraphicsContext::applyUniformHelper(const ShaderUniform &description, const UniformValue &value) const; + +#define QT3D_UNIFORM_TYPE_IMPL(UniformTypeEnum, BaseType, Func) \ + template<> \ + void GraphicsContext::applyUniformHelper(const ShaderUniform &description, const UniformValue &value) const \ +{ \ + const int count = qMin(description.m_size, int(value.byteSize() / description.m_rawByteSize)); \ + m_glHelper->Func(description.m_location, count, value.constData()); \ +} + + +QT3D_UNIFORM_TYPE_PROTO(UniformType::Float, float, glUniform1fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Vec2, float, glUniform2fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Vec3, float, glUniform3fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Vec4, float, glUniform4fv) + +// OpenGL expects int* as values for booleans +QT3D_UNIFORM_TYPE_PROTO(UniformType::Bool, int, glUniform1iv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::BVec2, int, glUniform2iv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::BVec3, int, glUniform3iv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::BVec4, int, glUniform4iv) + +QT3D_UNIFORM_TYPE_PROTO(UniformType::Int, int, glUniform1iv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::IVec2, int, glUniform2iv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::IVec3, int, glUniform3iv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::IVec4, int, glUniform4iv) + +QT3D_UNIFORM_TYPE_PROTO(UniformType::UInt, uint, glUniform1uiv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::UIVec2, uint, glUniform2uiv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::UIVec3, uint, glUniform3uiv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::UIVec4, uint, glUniform4uiv) + +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat2, float, glUniformMatrix2fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3, float, glUniformMatrix3fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4, float, glUniformMatrix4fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat2x3, float, glUniformMatrix2x3fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3x2, float, glUniformMatrix3x2fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat2x4, float, glUniformMatrix2x4fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4x2, float, glUniformMatrix4x2fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3x4, float, glUniformMatrix3x4fv) +QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4x3, float, glUniformMatrix4x3fv) + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GRAPHICSCONTEXT_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp new file mode 100644 index 000000000..ba00325b1 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp @@ -0,0 +1,1034 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelperes2_p.h" +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +// ES 3.0+ +#ifndef GL_SAMPLER_3D +#define GL_SAMPLER_3D 0x8B5F +#endif +#ifndef GL_SAMPLER_2D_SHADOW +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#endif +#ifndef GL_SAMPLER_CUBE_SHADOW +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#endif +#ifndef GL_SAMPLER_2D_ARRAY +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#endif +#ifndef GL_SAMPLER_2D_ARRAY_SHADOW +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#endif + +namespace Qt3DRender { +namespace Render { + +GraphicsHelperES2::GraphicsHelperES2() + : m_funcs(0) + , m_supportFramebufferBlit(false) +{ +} + +GraphicsHelperES2::~GraphicsHelperES2() +{ +} + +void GraphicsHelperES2::initializeHelper(QOpenGLContext *context, + QAbstractOpenGLFunctions *) +{ + Q_ASSERT(context); + m_funcs = context->functions(); + Q_ASSERT(m_funcs); + m_ext.reset(new QOpenGLExtensions(context)); + if (m_ext->hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit)) + m_supportFramebufferBlit = true; +} + +void GraphicsHelperES2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; + + if (baseVertex != 0) + qWarning() << "glDrawElementsInstancedBaseVertex is not supported with OpenGL ES 2"; + + for (GLint i = 0; i < instances; i++) + drawElements(primitiveType, + primitiveCount, + indexType, + indices); +} + +void GraphicsHelperES2::drawArraysInstanced(GLenum primitiveType, + GLint first, + GLsizei count, + GLsizei instances) +{ + for (GLint i = 0; i < instances; i++) + drawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperES2::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL ES 2"; + for (GLint i = 0; i < instances; i++) + drawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperES2::drawElements(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLint baseVertex) +{ + if (baseVertex != 0) + qWarning() << "glDrawElementsBaseVertex is not supported with OpenGL ES 2"; + QOpenGLExtensions *xfuncs = static_cast(m_funcs); + if (indexType == GL_UNSIGNED_INT && !xfuncs->hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint)) { + static bool warnShown = false; + if (!warnShown) { + warnShown = true; + qWarning("GL_UNSIGNED_INT index type not supported on this system, skipping draw call."); + } + return; + } + m_funcs->glDrawElements(primitiveType, + primitiveCount, + indexType, + indices); +} + +void GraphicsHelperES2::drawArrays(GLenum primitiveType, + GLint first, + GLsizei count) +{ + m_funcs->glDrawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperES2::drawElementsIndirect(GLenum, GLenum, void *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "Indirect Drawing is not supported with OpenGL ES 2"; +} + +void GraphicsHelperES2::drawArraysIndirect(GLenum , void *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "Indirect Drawing is not supported with OpenGL ES 2"; +} + +void GraphicsHelperES2::setVerticesPerPatch(GLint verticesPerPatch) +{ + Q_UNUSED(verticesPerPatch); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "Tessellation not supported with OpenGL ES 2"; +} + +void GraphicsHelperES2::useProgram(GLuint programId) +{ + m_funcs->glUseProgram(programId); +} + +QVector GraphicsHelperES2::programUniformsAndLocations(GLuint programId) +{ + QVector uniforms; + + GLint nbrActiveUniforms = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); + uniforms.reserve(nbrActiveUniforms); + char uniformName[256]; + for (GLint i = 0; i < nbrActiveUniforms; i++) { + ShaderUniform uniform; + GLsizei uniformNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, + &uniform.m_size, &uniform.m_type, uniformName); + uniformName[sizeof(uniformName) - 1] = '\0'; + uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); + uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); + // Work around for uniform array names that aren't returned with [0] by some drivers + if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) + uniform.m_name.append(QLatin1String("[0]")); + uniform.m_rawByteSize = uniformByteSize(uniform); + uniforms.append(uniform); + } + return uniforms; +} + +QVector GraphicsHelperES2::programAttributesAndLocations(GLuint programId) +{ + QVector attributes; + GLint nbrActiveAttributes = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); + attributes.reserve(nbrActiveAttributes); + char attributeName[256]; + for (GLint i = 0; i < nbrActiveAttributes; i++) { + ShaderAttribute attribute; + GLsizei attributeNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, + &attribute.m_size, &attribute.m_type, attributeName); + attributeName[sizeof(attributeName) - 1] = '\0'; + attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); + attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); + attributes.append(attribute); + } + return attributes; +} + +QVector GraphicsHelperES2::programUniformBlocks(GLuint programId) +{ + Q_UNUSED(programId); + QVector blocks; + static bool showWarning = true; + if (!showWarning) + return blocks; + showWarning = false; + qWarning() << "UBO are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; + return blocks; +} + +QVector GraphicsHelperES2::programShaderStorageBlocks(GLuint programId) +{ + Q_UNUSED(programId); + QVector blocks; + static bool showWarning = true; + if (!showWarning) + return blocks; + showWarning = false; + qWarning() << "SSBO are not supported by OpenGL ES 2.0 (since OpenGL ES 3.1)"; + return blocks; +} + +void GraphicsHelperES2::vertexAttribDivisor(GLuint index, GLuint divisor) +{ + Q_UNUSED(index); + Q_UNUSED(divisor); +} + +void GraphicsHelperES2::vertexAttributePointer(GLenum shaderDataType, + GLuint index, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + const GLvoid *pointer) +{ + switch (shaderDataType) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + case GL_FLOAT_MAT2: + case GL_FLOAT_MAT3: + case GL_FLOAT_MAT4: + m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); + break; + + default: + qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + Q_UNREACHABLE(); + } +} + +void GraphicsHelperES2::readBuffer(GLenum mode) +{ + Q_UNUSED(mode) + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glReadBuffer not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; +} + +void GraphicsHelperES2::drawBuffer(GLenum mode) +{ + Q_UNUSED(mode); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glDrawBuffer is not supported with OpenGL ES 2"; +} + +void *GraphicsHelperES2::fenceSync() +{ + qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; + return nullptr; +} + +void GraphicsHelperES2::clientWaitSync(void *, GLuint64 ) +{ + qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; +} + +void GraphicsHelperES2::waitSync(void *) +{ + qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; +} + +bool GraphicsHelperES2::wasSyncSignaled(void *) +{ + qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; + return false; +} + +void GraphicsHelperES2::deleteSync(void *) +{ + qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; +} + +void GraphicsHelperES2::rasterMode(GLenum faceMode, GLenum rasterMode) +{ + Q_UNUSED(faceMode); + Q_UNUSED(rasterMode); + qWarning() << "glPolyonMode is not supported with OpenGL ES"; +} + +void GraphicsHelperES2::blendEquation(GLenum mode) +{ + m_funcs->glBlendEquation(mode); +} + +void GraphicsHelperES2::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) +{ + Q_UNUSED(buf); + Q_UNUSED(sfactor); + Q_UNUSED(dfactor); + + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glBlendFunci() not supported by OpenGL ES 2.0"; +} + +void GraphicsHelperES2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) +{ + Q_UNUSED(buf); + Q_UNUSED(sRGB); + Q_UNUSED(dRGB); + Q_UNUSED(sAlpha); + Q_UNUSED(dAlpha); + + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glBlendFuncSeparatei() not supported by OpenGL ES 2.0"; +} + +void GraphicsHelperES2::alphaTest(GLenum, GLenum) +{ + qCWarning(Render::Rendering) << Q_FUNC_INFO << "AlphaTest not available with OpenGL ES 2.0"; +} + +void GraphicsHelperES2::depthTest(GLenum mode) +{ + m_funcs->glEnable(GL_DEPTH_TEST); + m_funcs->glDepthFunc(mode); +} + +void GraphicsHelperES2::depthMask(GLenum mode) +{ + m_funcs->glDepthMask(mode); +} + +void GraphicsHelperES2::depthRange(GLdouble nearValue, GLdouble farValue) +{ + m_funcs->glDepthRangef(static_cast(nearValue), static_cast(farValue)); +} + +void GraphicsHelperES2::frontFace(GLenum mode) +{ + m_funcs->glFrontFace(mode); +} + +void GraphicsHelperES2::setMSAAEnabled(bool enabled) +{ + Q_UNUSED(enabled); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "MSAA not available with OpenGL ES 2.0"; +} + +void GraphicsHelperES2::setAlphaCoverageEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) + : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); +} + +GLuint GraphicsHelperES2::createFrameBufferObject() +{ + GLuint id; + m_funcs->glGenFramebuffers(1, &id); + return id; +} + +void GraphicsHelperES2::releaseFrameBufferObject(GLuint frameBufferId) +{ + m_funcs->glDeleteFramebuffers(1, &frameBufferId); +} + +void GraphicsHelperES2::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) +{ + Q_UNUSED(mode) + // For ES2 the spec states for target: The symbolic constant must be GL_FRAMEBUFFER + // so mode is ignored and is always set to GL_FRAMEBUFFER + m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); +} + +void GraphicsHelperES2::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + Q_UNUSED(imageUnit) + Q_UNUSED(texture) + Q_UNUSED(mipLevel) + Q_UNUSED(layered) + Q_UNUSED(layer) + Q_UNUSED(access) + Q_UNUSED(format) + qWarning() << "Shader Images are not supported by ES 2.0 (since ES 3.1)"; + +} + +GLuint GraphicsHelperES2::boundFrameBufferObject() +{ + GLint id = 0; + m_funcs->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id); + return id; +} + +bool GraphicsHelperES2::checkFrameBufferComplete() +{ + return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); +} + +bool GraphicsHelperES2::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + // Use a renderbuffer for depth or stencil attachments since this is + // problematic before GLES 3.2. Keep using textures for everything else. + // For ES2 individual Depth and Stencil buffers need to be an option because + // DepthStencil is an extension. + return attachment.m_point == QRenderTargetOutput::DepthStencil || + attachment.m_point == QRenderTargetOutput::Depth || + attachment.m_point == QRenderTargetOutput::Stencil; +} + +void GraphicsHelperES2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + GLenum attr = GL_COLOR_ATTACHMENT0; + + if (attachment.m_point == QRenderTargetOutput::Color0) + attr = GL_COLOR_ATTACHMENT0; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + else + qCritical() << "Unsupported FBO attachment OpenGL ES 2.0"; + + const QOpenGLTexture::Target target = texture->target(); + + if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face == QAbstractTexture::AllFaces) { + qWarning() << "OpenGL ES 2.0 doesn't handle attaching all the faces of a cube map texture at once to an FBO"; + return; + } + + texture->bind(); + if (target == QOpenGLTexture::Target2D) + m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); + else if (target == QOpenGLTexture::TargetCubeMap) + m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else + qCritical() << "Unsupported Texture FBO attachment format"; + texture->release(); +} + +void GraphicsHelperES2::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) +{ + if (attachment.m_point != QRenderTargetOutput::DepthStencil && + attachment.m_point != QRenderTargetOutput::Depth && + attachment.m_point != QRenderTargetOutput::Stencil) { + qCritical() << "Renderbuffers only supported for combined depth-stencil, depth, or stencil, but got attachment point" + << attachment.m_point; + return; + } + + renderBuffer->bind(); + if (attachment.m_point == QRenderTargetOutput::DepthStencil || + attachment.m_point == QRenderTargetOutput::Depth) + m_funcs->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer->renderBufferId()); + if (attachment.m_point == QRenderTargetOutput::DepthStencil || + attachment.m_point == QRenderTargetOutput::Stencil) + m_funcs->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBuffer->renderBufferId()); + renderBuffer->release(); +} + +bool GraphicsHelperES2::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case RenderBufferDimensionRetrieval: + return true; + case BlitFramebuffer: + return m_supportFramebufferBlit; + default: + return false; + } +} + +void GraphicsHelperES2::drawBuffers(GLsizei, const int *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "drawBuffers is not supported by ES 2.0"; +} + +void GraphicsHelperES2::bindFragDataLocation(GLuint , const QHash &) +{ + qCritical() << "bindFragDataLocation is not supported by ES 2.0"; +} + +void GraphicsHelperES2::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + Q_UNUSED(programId); + Q_UNUSED(uniformBlockIndex); + Q_UNUSED(uniformBlockBinding); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "UBO are not supported by ES 2.0 (since ES 3.0)"; +} + +void GraphicsHelperES2::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) +{ + Q_UNUSED(programId); + Q_UNUSED(shaderStorageBlockIndex); + Q_UNUSED(shaderStorageBlockBinding); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "SSBO are not supported by ES 2.0 (since ES 3.1)"; +} + +void GraphicsHelperES2::bindBufferBase(GLenum target, GLuint index, GLuint buffer) +{ + Q_UNUSED(target); + Q_UNUSED(index); + Q_UNUSED(buffer); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "bindBufferBase is not supported by ES 2.0 (since ES 3.0)"; +} + +void GraphicsHelperES2::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + Q_UNUSED(v); + Q_UNUSED(description); + Q_UNUSED(buffer); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "UBO are not supported by ES 2.0 (since ES 3.0)"; +} + +uint GraphicsHelperES2::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + int arrayStride = qMax(description.m_arrayStride, 0); + int matrixStride = qMax(description.m_matrixStride, 0); + + switch (description.m_type) { + + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + rawByteSize = 8; + break; + + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + rawByteSize = 12; + break; + + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + rawByteSize = 16; + break; + + case GL_FLOAT_MAT2: + rawByteSize = matrixStride ? 2 * matrixStride : 16; + break; + + case GL_FLOAT_MAT3: + rawByteSize = matrixStride ? 3 * matrixStride : 36; + break; + + case GL_FLOAT_MAT4: + rawByteSize = matrixStride ? 4 * matrixStride : 64; + break; + + case GL_BOOL: + rawByteSize = 1; + break; + + case GL_BOOL_VEC2: + rawByteSize = 2; + break; + + case GL_BOOL_VEC3: + rawByteSize = 3; + break; + + case GL_BOOL_VEC4: + rawByteSize = 4; + break; + + case GL_INT: + case GL_FLOAT: + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: + rawByteSize = 4; + break; + } + + return arrayStride ? rawByteSize * arrayStride : rawByteSize; +} + +void GraphicsHelperES2::enableClipPlane(int) +{ +} + +void GraphicsHelperES2::disableClipPlane(int) +{ +} + +void GraphicsHelperES2::setClipPlane(int, const QVector3D &, float) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "Clip planes not supported by OpenGL ES 2.0"; +} + +GLint GraphicsHelperES2::maxClipPlaneCount() +{ + return 0; +} + +void GraphicsHelperES2::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + Q_UNUSED(barriers); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "memory barrier is not supported by OpenGL ES 2.0 (since 4.3)"; +} + +void GraphicsHelperES2::enablePrimitiveRestart(int) +{ +} + +void GraphicsHelperES2::enableVertexAttributeArray(int location) +{ + m_funcs->glEnableVertexAttribArray(location); +} + +void GraphicsHelperES2::disablePrimitiveRestart() +{ +} + +void GraphicsHelperES2::clearBufferf(GLint drawbuffer, const QVector4D &values) +{ + Q_UNUSED(drawbuffer); + Q_UNUSED(values); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glClearBuffer*() not supported by OpenGL ES 2.0"; +} + +void GraphicsHelperES2::pointSize(bool programmable, GLfloat value) +{ + // If this is not a reset to default values, print a warning + if (programmable || !qFuzzyCompare(value, 1.0f)) { + static bool warned = false; + if (!warned) { + qWarning() << "glPointSize() and GL_PROGRAM_POINT_SIZE are not supported by ES 2.0"; + warned = true; + } + } +} + +void GraphicsHelperES2::enablei(GLenum cap, GLuint index) +{ + Q_UNUSED(cap); + Q_UNUSED(index); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glEnablei() not supported by OpenGL ES 2.0"; +} + +void GraphicsHelperES2::disablei(GLenum cap, GLuint index) +{ + Q_UNUSED(cap); + Q_UNUSED(index); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glDisablei() not supported by OpenGL ES 2.0"; +} + +void GraphicsHelperES2::setSeamlessCubemap(bool enable) +{ + Q_UNUSED(enable); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "GL_TEXTURE_CUBE_MAP_SEAMLESS not supported by OpenGL ES 2.0"; +} + +QSize GraphicsHelperES2::getRenderBufferDimensions(GLuint renderBufferId) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); + + return QSize(width, height); +} + +QSize GraphicsHelperES2::getTextureDimensions(GLuint textureId, GLenum target, uint level) +{ + Q_UNUSED(textureId); + Q_UNUSED(target); + Q_UNUSED(level); + qCritical() << "getTextureDimensions is not supported by ES 2.0"; + return QSize(0, 0); +} + +void GraphicsHelperES2::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) +{ + Q_UNUSED(wx); + Q_UNUSED(wy); + Q_UNUSED(wz); + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "Compute Shaders are not supported by ES 2.0 (since ES 3.1)"; +} + +char *GraphicsHelperES2::mapBuffer(GLenum target, GLsizeiptr size) +{ + Q_UNUSED(target); + Q_UNUSED(size); + static bool showWarning = true; + if (!showWarning) + return nullptr; + showWarning = false; + qWarning() << "Map buffer is not a core requirement for ES 2.0"; + return nullptr; +} + +GLboolean GraphicsHelperES2::unmapBuffer(GLenum target) +{ + Q_UNUSED(target); + static bool showWarning = true; + if (!showWarning) + return false; + showWarning = false; + qWarning() << "unMap buffer is not a core requirement for ES 2.0"; + return false; +} + +void GraphicsHelperES2::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform1fv(location, count, values); +} + +void GraphicsHelperES2::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform2fv(location, count, values); +} + +void GraphicsHelperES2::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform3fv(location, count, values); +} + +void GraphicsHelperES2::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform4fv(location, count, values); +} + +void GraphicsHelperES2::glUniform1iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform1iv(location, count, values); +} + +void GraphicsHelperES2::glUniform2iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform2iv(location, count, values); +} + +void GraphicsHelperES2::glUniform3iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform3iv(location, count, values); +} + +void GraphicsHelperES2::glUniform4iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform4iv(location, count, values); +} + +void GraphicsHelperES2::glUniform1uiv(GLint , GLsizei , const GLuint *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniform1uiv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniform2uiv(GLint , GLsizei , const GLuint *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniform2uiv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniform3uiv(GLint , GLsizei , const GLuint *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniform3uiv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniform4uiv(GLint , GLsizei , const GLuint *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniform4uiv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2fv(location, count, false, values); +} + +void GraphicsHelperES2::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3fv(location, count, false, values); +} + +void GraphicsHelperES2::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4fv(location, count, false, values); +} + +void GraphicsHelperES2::glUniformMatrix2x3fv(GLint , GLsizei , const GLfloat *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniformMatrix2x3fv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniformMatrix3x2fv(GLint , GLsizei , const GLfloat *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniformMatrix3x2fv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniformMatrix2x4fv(GLint , GLsizei , const GLfloat *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniformMatrix2x4fv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniformMatrix4x2fv(GLint , GLsizei , const GLfloat *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniformMatrix4x2fv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniformMatrix3x4fv(GLint , GLsizei , const GLfloat *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniformMatrix3x4fv not supported by ES 2"; +} + +void GraphicsHelperES2::glUniformMatrix4x3fv(GLint , GLsizei , const GLfloat *) +{ + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "glUniformMatrix4x3fv not supported by ES 2"; +} + +UniformType GraphicsHelperES2::uniformTypeFromGLType(GLenum type) +{ + switch (type) { + case GL_FLOAT: + return UniformType::Float; + case GL_FLOAT_VEC2: + return UniformType::Vec2; + case GL_FLOAT_VEC3: + return UniformType::Vec3; + case GL_FLOAT_VEC4: + return UniformType::Vec4; + case GL_FLOAT_MAT2: + return UniformType::Mat2; + case GL_FLOAT_MAT3: + return UniformType::Mat3; + case GL_FLOAT_MAT4: + return UniformType::Mat4; + case GL_INT: + return UniformType::Int; + case GL_INT_VEC2: + return UniformType::IVec2; + case GL_INT_VEC3: + return UniformType::IVec3; + case GL_INT_VEC4: + return UniformType::IVec4; + case GL_BOOL: + return UniformType::Bool; + case GL_BOOL_VEC2: + return UniformType::BVec2; + case GL_BOOL_VEC3: + return UniformType::BVec3; + case GL_BOOL_VEC4: + return UniformType::BVec4; + + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: + return UniformType::Sampler; + default: + Q_UNREACHABLE(); + return UniformType::Float; + } +} + +void GraphicsHelperES2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) +{ + if (!m_supportFramebufferBlit) { + static bool showWarning = true; + if (!showWarning) + return; + showWarning = false; + qWarning() << "Framebuffer blits are not supported by ES 2.0 (since ES 3.1)"; + } else + m_ext->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h new file mode 100644 index 000000000..902bd5fb2 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES2_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERES2_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLExtensions; + +namespace Qt3DRender { +namespace Render { + +class GraphicsHelperES2 : public GraphicsHelperInterface +{ +public: + GraphicsHelperES2(); + virtual ~GraphicsHelperES2(); + + // QGraphicHelperInterface interface + void alphaTest(GLenum mode1, GLenum mode2) override; + void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; + void bindFragDataLocation(GLuint shader, const QHash &outputs) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; + void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; + void blendEquation(GLenum mode) override; + void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; + void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; + void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; + GLuint boundFrameBufferObject() override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; + bool checkFrameBufferComplete() override; + void clearBufferf(GLint drawbuffer, const QVector4D &values) override; + GLuint createFrameBufferObject() override; + void depthMask(GLenum mode) override; + void depthRange(GLdouble nearValue, GLdouble farValue) override; + void depthTest(GLenum mode) override; + void disableClipPlane(int clipPlane) override; + void disablei(GLenum cap, GLuint index) override; + void disablePrimitiveRestart() override; + void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; + char *mapBuffer(GLenum target, GLsizeiptr size) override; + GLboolean unmapBuffer(GLenum target) override; + void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; + void drawArraysIndirect(GLenum mode,void *indirect) override; + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; + void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; + void drawBuffers(GLsizei n, const int *bufs) override; + void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + void enableClipPlane(int clipPlane) override; + void enablei(GLenum cap, GLuint index) override; + void enablePrimitiveRestart(int primitiveRestartIndex) override; + void enableVertexAttributeArray(int location) override; + void frontFace(GLenum mode) override; + QSize getRenderBufferDimensions(GLuint renderBufferId) override; + QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; + void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; + void pointSize(bool programmable, GLfloat value) override; + GLint maxClipPlaneCount() override; + void memoryBarrier(QMemoryBarrier::Operations barriers) override; + QVector programUniformBlocks(GLuint programId) override; + QVector programAttributesAndLocations(GLuint programId) override; + QVector programUniformsAndLocations(GLuint programId) override; + QVector programShaderStorageBlocks(GLuint programId) override; + void releaseFrameBufferObject(GLuint frameBufferId) override; + void setMSAAEnabled(bool enable) override; + void setAlphaCoverageEnabled(bool enable) override; + void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; + void setSeamlessCubemap(bool enable) override; + void setVerticesPerPatch(GLint verticesPerPatch) override; + bool supportsFeature(Feature feature) const override; + uint uniformByteSize(const ShaderUniform &description) override; + void useProgram(GLuint programId) override; + void vertexAttribDivisor(GLuint index, GLuint divisor) override; + void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; + void readBuffer(GLenum mode) override; + void drawBuffer(GLenum mode) override; + void rasterMode(GLenum faceMode, GLenum rasterMode) override; + + void *fenceSync() override; + void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; + void waitSync(void *sync) override; + bool wasSyncSignaled(void *sync) override; + void deleteSync(void *sync) override; + + void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; + + void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; + + void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; + + void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; + + UniformType uniformTypeFromGLType(GLenum glType) override; + +protected: + QOpenGLFunctions *m_funcs; + bool m_supportFramebufferBlit; + QScopedPointer m_ext; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES2_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp new file mode 100644 index 000000000..6e299199f --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp @@ -0,0 +1,768 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 Svenn-Arne Dragly. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelperes3_p.h" +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +// ES 3.0+ +#ifndef GL_SAMPLER_3D +#define GL_SAMPLER_3D 0x8B5F +#endif +#ifndef GL_SAMPLER_2D_SHADOW +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#endif +#ifndef GL_SAMPLER_CUBE_SHADOW +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#endif +#ifndef GL_SAMPLER_2D_ARRAY +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#endif +#ifndef GL_SAMPLER_2D_ARRAY_SHADOW +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#endif +#ifndef GL_FLOAT_MAT2x3 +#define GL_FLOAT_MAT2x3 0x8B65 +#endif +#ifndef GL_FLOAT_MAT2x4 +#define GL_FLOAT_MAT2x4 0x8B66 +#endif +#ifndef GL_FLOAT_MAT3x2 +#define GL_FLOAT_MAT3x2 0x8B67 +#endif +#ifndef GL_FLOAT_MAT3x4 +#define GL_FLOAT_MAT3x4 0x8B68 +#endif +#ifndef GL_FLOAT_MAT4x2 +#define GL_FLOAT_MAT4x2 0x8B69 +#endif +#ifndef GL_FLOAT_MAT4x3 +#define GL_FLOAT_MAT4x3 0x8B6A +#endif +#ifndef GL_UNSIGNED_INT_VEC2 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#endif +#ifndef GL_UNSIGNED_INT_VEC3 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#endif +#ifndef GL_UNSIGNED_INT_VEC4 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#endif +#ifndef GL_INT_SAMPLER_2D +#define GL_INT_SAMPLER_2D 0x8DCA +#endif +#ifndef GL_INT_SAMPLER_3D +#define GL_INT_SAMPLER_3D 0x8DCB +#endif +#ifndef GL_INT_SAMPLER_CUBE +#define GL_INT_SAMPLER_CUBE 0x8DCC +#endif +#ifndef GL_INT_SAMPLER_2D_ARRAY +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#endif +#ifndef GL_UNSIGNED_INT_SAMPLER_2D +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#endif +#ifndef GL_UNSIGNED_INT_SAMPLER_3D +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#endif +#ifndef GL_UNSIGNED_INT_SAMPLER_CUBE +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#endif +#ifndef GL_UNSIGNED_INT_SAMPLER_2D_ARRAY +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#endif + +#ifndef GL_ACTIVE_UNIFORM_BLOCKS +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#endif +#ifndef GL_UNIFORM_BLOCK_INDEX +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#endif +#ifndef GL_UNIFORM_OFFSET +#define GL_UNIFORM_OFFSET 0x8A3B +#endif +#ifndef GL_UNIFORM_ARRAY_STRIDE +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#endif +#ifndef GL_UNIFORM_MATRIX_STRIDE +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#endif +#ifndef GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#endif +#ifndef GL_UNIFORM_BLOCK_BINDING +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#endif +#ifndef GL_UNIFORM_BLOCK_DATA_SIZE +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#endif + +#ifndef GL_DRAW_FRAMEBUFFER +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#endif + +#ifndef GL_READ_FRAMEBUFFER +#define GL_READ_FRAMEBUFFER 0x8CA8 +#endif + +#ifndef GL_SIGNALED +#define GL_SIGNALED 0x9119 +#endif + +#ifndef GL_SYNC_STATUS +#define GL_SYNC_STATUS 0x9114 +#endif + +#ifndef GL_TIMEOUT_IGNORED +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#endif + +#ifndef GL_SYNC_GPU_COMMANDS_COMPLETE +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#endif + +#ifndef GL_SYNC_FLUSH_COMMANDS_BIT +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#endif + +namespace Qt3DRender { +namespace Render { + +GraphicsHelperES3::GraphicsHelperES3() +{ +} + +GraphicsHelperES3::~GraphicsHelperES3() +{ +} + +void GraphicsHelperES3::initializeHelper(QOpenGLContext *context, + QAbstractOpenGLFunctions *functions) +{ + GraphicsHelperES2::initializeHelper(context, functions); + m_extraFuncs = context->extraFunctions(); + Q_ASSERT(m_extraFuncs); +} + +void GraphicsHelperES3::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 3"; + + if (baseVertex != 0) + qWarning() << "glDrawElementsInstancedBaseVertex is not supported with OpenGL ES 3"; + + m_extraFuncs->glDrawElementsInstanced(primitiveType, + primitiveCount, + indexType, + indices, + instances); +} + +void GraphicsHelperES3::vertexAttribDivisor(GLuint index, GLuint divisor) +{ + m_extraFuncs->glVertexAttribDivisor(index, divisor); +} + +void GraphicsHelperES3::vertexAttributePointer(GLenum shaderDataType, + GLuint index, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + const GLvoid *pointer) +{ + switch (shaderDataType) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + case GL_FLOAT_MAT2: + case GL_FLOAT_MAT2x3: + case GL_FLOAT_MAT2x4: + case GL_FLOAT_MAT3: + case GL_FLOAT_MAT3x2: + case GL_FLOAT_MAT3x4: + case GL_FLOAT_MAT4x2: + case GL_FLOAT_MAT4x3: + case GL_FLOAT_MAT4: + m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); + break; + + case GL_INT: + case GL_INT_VEC2: + case GL_INT_VEC3: + case GL_INT_VEC4: + case GL_UNSIGNED_INT: + case GL_UNSIGNED_INT_VEC2: + case GL_UNSIGNED_INT_VEC3: + case GL_UNSIGNED_INT_VEC4: + m_extraFuncs->glVertexAttribIPointer(index, size, type, stride, pointer); + break; + + default: + qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + Q_UNREACHABLE(); + } +} + +void GraphicsHelperES3::drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) +{ + m_extraFuncs->glDrawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsHelperES3::readBuffer(GLenum mode) +{ + m_extraFuncs->glReadBuffer(mode); +} + +void GraphicsHelperES3::drawBuffer(GLenum mode) +{ + Q_UNUSED(mode); + qWarning() << "glDrawBuffer is not supported with OpenGL ES 3"; +} + +void GraphicsHelperES3::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + GLenum attr = GL_COLOR_ATTACHMENT0; + + if (attachment.m_point <= QRenderTargetOutput::Color15) + attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + else + qCritical() << "Unsupported FBO attachment OpenGL ES 3.0"; + + const QOpenGLTexture::Target target = texture->target(); + + if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face == QAbstractTexture::AllFaces) { + qWarning() << "OpenGL ES 3.0 doesn't handle attaching all the faces of a cube map texture at once to an FBO"; + return; + } + + texture->bind(); + if (target == QOpenGLTexture::Target2D) + m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); + else if (target == QOpenGLTexture::TargetCubeMap) + m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else + qCritical() << "Unsupported Texture FBO attachment format"; + texture->release(); +} + +void GraphicsHelperES3::bindFrameBufferObject(GLuint frameBufferId, GraphicsHelperInterface::FBOBindMode mode) +{ + switch (mode) { + case FBODraw: + m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); + return; + case FBORead: + m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); + return; + case FBOReadAndDraw: + default: + m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); + return; + } +} + +bool GraphicsHelperES3::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case RenderBufferDimensionRetrieval: + case MRT: + case BlitFramebuffer: + case UniformBufferObject: + case MapBuffer: + case Fences: + return true; + default: + return false; + } +} + +void GraphicsHelperES3::drawBuffers(GLsizei n, const int *bufs) +{ + QVarLengthArray drawBufs(n); + + for (int i = 0; i < n; i++) + drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; + m_extraFuncs->glDrawBuffers(n, drawBufs.constData()); +} + +UniformType GraphicsHelperES3::uniformTypeFromGLType(GLenum glType) +{ + switch (glType) { + case GL_SAMPLER_3D: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_2D_ARRAY: + case GL_SAMPLER_2D_ARRAY_SHADOW: + return UniformType::Sampler; + default: + return GraphicsHelperES2::uniformTypeFromGLType(glType); + } +} + +uint GraphicsHelperES3::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + int arrayStride = qMax(description.m_arrayStride, 0); + int matrixStride = qMax(description.m_matrixStride, 0); + + switch (description.m_type) { + + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + case GL_UNSIGNED_INT_VEC2: + rawByteSize = 8; + break; + + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + case GL_UNSIGNED_INT_VEC3: + rawByteSize = 12; + break; + + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + case GL_UNSIGNED_INT_VEC4: + rawByteSize = 16; + break; + + case GL_FLOAT_MAT2: + rawByteSize = matrixStride ? 2 * matrixStride : 16; + break; + + case GL_FLOAT_MAT2x4: + rawByteSize = matrixStride ? 2 * matrixStride : 32; + break; + + case GL_FLOAT_MAT4x2: + rawByteSize = matrixStride ? 4 * matrixStride : 32; + break; + + case GL_FLOAT_MAT3: + rawByteSize = matrixStride ? 3 * matrixStride : 36; + break; + + case GL_FLOAT_MAT2x3: + rawByteSize = matrixStride ? 2 * matrixStride : 24; + break; + + case GL_FLOAT_MAT3x2: + rawByteSize = matrixStride ? 3 * matrixStride : 24; + break; + + case GL_FLOAT_MAT4: + rawByteSize = matrixStride ? 4 * matrixStride : 64; + break; + + case GL_FLOAT_MAT4x3: + rawByteSize = matrixStride ? 4 * matrixStride : 48; + break; + + case GL_FLOAT_MAT3x4: + rawByteSize = matrixStride ? 3 * matrixStride : 48; + break; + + case GL_BOOL: + rawByteSize = 1; + break; + + case GL_BOOL_VEC2: + rawByteSize = 2; + break; + + case GL_BOOL_VEC3: + rawByteSize = 3; + break; + + case GL_BOOL_VEC4: + rawByteSize = 4; + break; + + case GL_INT: + case GL_FLOAT: + case GL_UNSIGNED_INT: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_2D_ARRAY_SHADOW: + rawByteSize = 4; + break; + } + + return arrayStride ? rawByteSize * arrayStride : rawByteSize; +} + +void *GraphicsHelperES3::fenceSync() +{ + return m_extraFuncs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); +} + +void GraphicsHelperES3::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) +{ + m_extraFuncs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); +} + +void GraphicsHelperES3::waitSync(void *sync) +{ + m_extraFuncs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); +} + +bool GraphicsHelperES3::wasSyncSignaled(void *sync) +{ + GLint v; + m_extraFuncs->glGetSynciv(static_cast(sync), + GL_SYNC_STATUS, + sizeof(v), + nullptr, + &v); + return v == GL_SIGNALED; +} + +void GraphicsHelperES3::deleteSync(void *sync) +{ + m_extraFuncs->glDeleteSync(static_cast(sync)); +} + +void GraphicsHelperES3::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) +{ + m_extraFuncs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +} + +void GraphicsHelperES3::bindBufferBase(GLenum target, GLuint index, GLuint buffer) +{ + m_extraFuncs->glBindBufferBase(target, index, buffer); +} + +bool GraphicsHelperES3::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + // Use a renderbuffer for combined depth+stencil attachments since this is + // problematic before GLES 3.2. Keep using textures for everything else. + return attachment.m_point == QRenderTargetOutput::DepthStencil; +} + +void GraphicsHelperES3::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + m_extraFuncs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); +} + +void GraphicsHelperES3::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + char *bufferData = buffer.data(); + + switch (description.m_type) { + + case GL_FLOAT: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_FLOAT_VEC2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_FLOAT_VEC3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_FLOAT_VEC4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_FLOAT_MAT2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); + break; + } + + case GL_FLOAT_MAT2x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); + break; + } + + case GL_FLOAT_MAT2x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); + break; + } + + case GL_FLOAT_MAT3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); + break; + } + + case GL_FLOAT_MAT3x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); + break; + } + + case GL_FLOAT_MAT3x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); + break; + } + + case GL_FLOAT_MAT4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); + break; + } + + case GL_FLOAT_MAT4x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); + break; + } + + case GL_FLOAT_MAT4x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); + break; + } + + case GL_INT: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_INT_VEC2: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_INT_VEC3: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_INT_VEC4: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_UNSIGNED_INT: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_UNSIGNED_INT_VEC2: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_UNSIGNED_INT_VEC3: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_UNSIGNED_INT_VEC4: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_BOOL: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_BOOL_VEC2: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_BOOL_VEC3: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_BOOL_VEC4: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + // note: only GLES 3.0 supported types, not the same as OpenGL proper + // (also, no MS samplers before ES 3.1) + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_2D_ARRAY_SHADOW: + { + Q_ASSERT(description.m_size == 1); + int value = v.toInt(); + QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); + break; + } + + default: + qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; + break; + } +} + +char *GraphicsHelperES3::mapBuffer(GLenum target, GLsizeiptr size) +{ + return static_cast(m_extraFuncs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); +} + +GLboolean GraphicsHelperES3::unmapBuffer(GLenum target) +{ + return m_extraFuncs->glUnmapBuffer(target); +} + +QVector GraphicsHelperES3::programUniformsAndLocations(GLuint programId) +{ + QVector uniforms; + + GLint nbrActiveUniforms = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); + uniforms.reserve(nbrActiveUniforms); + char uniformName[256]; + for (GLint i = 0; i < nbrActiveUniforms; i++) { + ShaderUniform uniform; + GLsizei uniformNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, + &uniform.m_size, &uniform.m_type, uniformName); + uniformName[sizeof(uniformName) - 1] = '\0'; + uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); + uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); + m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); + m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); + m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); + m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); + uniform.m_rawByteSize = uniformByteSize(uniform); + uniforms.append(uniform); + qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; + } + + return uniforms; +} + +QVector GraphicsHelperES3::programUniformBlocks(GLuint programId) +{ + QVector blocks; + GLint nbrActiveUniformsBlocks = 0; + m_extraFuncs->glGetProgramiv(programId, GL_ACTIVE_UNIFORM_BLOCKS, &nbrActiveUniformsBlocks); + blocks.reserve(nbrActiveUniformsBlocks); + for (GLint i = 0; i < nbrActiveUniformsBlocks; i++) { + QByteArray uniformBlockName(256, '\0'); + GLsizei length = 0; + ShaderUniformBlock uniformBlock; + m_extraFuncs->glGetActiveUniformBlockName(programId, i, 256, &length, uniformBlockName.data()); + uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); + uniformBlock.m_index = i; + m_extraFuncs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &uniformBlock.m_activeUniformsCount); + m_extraFuncs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_BINDING, &uniformBlock.m_binding); + m_extraFuncs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.m_size); + blocks.append(uniformBlock); + } + return blocks; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp new file mode 100644 index 000000000..dc042b0c6 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp @@ -0,0 +1,367 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelperes3_1_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +// ES 3.1+ +#ifndef GL_SAMPLER_2D_MULTISAMPLE +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#endif +#ifndef GL_INT_SAMPLER_2D_MULTISAMPLE +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#endif +#ifndef GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#endif +#ifndef GL_ACTIVE_RESOURCES +#define GL_ACTIVE_RESOURCES 0x92F5 +#endif +#ifndef GL_BUFFER_BINDING +#define GL_BUFFER_BINDING 0x9302 +#endif +#ifndef GL_BUFFER_DATA_SIZE +#define GL_BUFFER_DATA_SIZE 0x9303 +#endif +#ifndef GL_NUM_ACTIVE_VARIABLES +#define GL_NUM_ACTIVE_VARIABLES 0x9304 +#endif +#ifndef GL_SHADER_STORAGE_BLOCK +#define GL_SHADER_STORAGE_BLOCK 0x92E6 +#endif +#ifndef GL_ALL_BARRIER_BITS +#define GL_ALL_BARRIER_BITS 0xFFFFFFFF +#endif +#ifndef GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 +#endif +#ifndef GL_ELEMENT_ARRAY_BARRIER_BIT +#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 +#endif +#ifndef GL_UNIFORM_BARRIER_BIT +#define GL_UNIFORM_BARRIER_BIT 0x00000004 +#endif +#ifndef GL_TEXTURE_FETCH_BARRIER_BIT +#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 +#endif +#ifndef GL_SHADER_IMAGE_ACCESS_BARRIER_BIT +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 +#endif +#ifndef GL_COMMAND_BARRIER_BIT +#define GL_COMMAND_BARRIER_BIT 0x00000040 +#endif +#ifndef GL_PIXEL_BUFFER_BARRIER_BIT +#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 +#endif +#ifndef GL_TEXTURE_UPDATE_BARRIER_BIT +#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 +#endif +#ifndef GL_BUFFER_UPDATE_BARRIER_BIT +#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 +#endif +#ifndef GL_FRAMEBUFFER_BARRIER_BIT +#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 +#endif +#ifndef GL_TRANSFORM_FEEDBACK_BARRIER_BIT +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 +#endif +#ifndef GL_ATOMIC_COUNTER_BARRIER_BIT +#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 +#endif +#ifndef GL_SHADER_STORAGE_BARRIER_BIT +#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +#endif +#ifndef GL_IMAGE_2D +#define GL_IMAGE_2D 0x904D +#endif +#ifndef GL_IMAGE_3D +#define GL_IMAGE_3D 0x904E +#endif +#ifndef GL_IMAGE_CUBE +#define GL_IMAGE_CUBE 0x9050 +#endif +#ifndef GL_IMAGE_2D_ARRAY +#define GL_IMAGE_2D_ARRAY 0x9053 +#endif +#ifndef GL_INT_IMAGE_2D +#define GL_INT_IMAGE_2D 0x9058 +#endif +#ifndef GL_INT_IMAGE_3D +#define GL_INT_IMAGE_3D 0x9059 +#endif +#ifndef GL_INT_IMAGE_CUBE +#define GL_INT_IMAGE_CUBE 0x905B +#endif +#ifndef GL_INT_IMAGE_2D_ARRAY +#define GL_INT_IMAGE_2D_ARRAY 0x905E +#endif +#ifndef GL_UNSIGNED_INT_IMAGE_2D +#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +#endif +#ifndef GL_UNSIGNED_INT_IMAGE_3D +#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +#endif +#ifndef GL_UNSIGNED_INT_IMAGE_CUBE +#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +#endif +#ifndef GL_UNSIGNED_INT_IMAGE_2D_ARRAY +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +#endif + + +namespace Qt3DRender { +namespace Render { + +namespace { + +GLbitfield memoryBarrierGLBitfield(QMemoryBarrier::Operations barriers) +{ + GLbitfield bits = 0; + + if (barriers.testFlag(QMemoryBarrier::All)) { + bits |= GL_ALL_BARRIER_BITS; + return bits; + } + + if (barriers.testFlag(QMemoryBarrier::VertexAttributeArray)) + bits |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::ElementArray)) + bits |= GL_ELEMENT_ARRAY_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::Uniform)) + bits |= GL_UNIFORM_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::TextureFetch)) + bits |= GL_TEXTURE_FETCH_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::ShaderImageAccess)) + bits |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::Command)) + bits |= GL_COMMAND_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::PixelBuffer)) + bits |= GL_PIXEL_BUFFER_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::TextureUpdate)) + bits |= GL_TEXTURE_UPDATE_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::BufferUpdate)) + bits |= GL_BUFFER_UPDATE_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::FrameBuffer)) + bits |= GL_FRAMEBUFFER_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::TransformFeedback)) + bits |= GL_TRANSFORM_FEEDBACK_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::AtomicCounter)) + bits |= GL_ATOMIC_COUNTER_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::ShaderStorage)) + bits |= GL_SHADER_STORAGE_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::QueryBuffer)) + qWarning() << "QueryBuffer barrier not supported by ES 3.1"; + + return bits; +} + +} // anonymous + + +GraphicsHelperES3_1::GraphicsHelperES3_1() +{ +} + +GraphicsHelperES3_1::~GraphicsHelperES3_1() +{ +} + +bool GraphicsHelperES3_1::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case GraphicsHelperInterface::Compute: + case GraphicsHelperInterface::ShaderStorageObject: + case GraphicsHelperInterface::IndirectDrawing: + case GraphicsHelperInterface::ShaderImage: + return true; + default: + break; + } + return GraphicsHelperES3::supportsFeature(feature); +} + +void GraphicsHelperES3_1::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + m_extraFuncs->glBindImageTexture(imageUnit, + texture, + mipLevel, + layered, + layer, + access, + format); +} + +void GraphicsHelperES3_1::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) +{ + m_extraFuncs->glDispatchCompute(wx, wy, wz); +} + +void GraphicsHelperES3_1::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + m_extraFuncs->glMemoryBarrier(memoryBarrierGLBitfield(barriers)); +} + +void GraphicsHelperES3_1::drawArraysIndirect(GLenum mode, void *indirect) +{ + m_extraFuncs->glDrawArraysIndirect(mode, indirect); +} + +void GraphicsHelperES3_1::drawElementsIndirect(GLenum mode, GLenum type, void *indirect) +{ + m_extraFuncs->glDrawElementsIndirect(mode, type, indirect); +} + +void GraphicsHelperES3_1::bindShaderStorageBlock(GLuint , GLuint , GLuint ) +{ + // ES 3.1 has no API for that, bindings have to be specified directly in the shader + // with layout(std430, binding = 3) + qWarning() << "ES 3.1 has no bindShaderStorageBlock API, it uses binding declaration from the shader storage block"; +} + +QVector GraphicsHelperES3_1::programShaderStorageBlocks(GLuint programId) +{ + QVector blocks; + GLint nbrActiveShaderStorageBlocks = 0; + m_extraFuncs->glGetProgramInterfaceiv(programId, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &nbrActiveShaderStorageBlocks); + blocks.reserve(nbrActiveShaderStorageBlocks); + for (GLint i = 0; i < nbrActiveShaderStorageBlocks; ++i) { + QByteArray storageBlockName(256, '\0'); + GLsizei length = 0; + ShaderStorageBlock storageBlock; + m_extraFuncs->glGetProgramResourceName(programId, GL_SHADER_STORAGE_BLOCK, i, 256, &length, storageBlockName.data()); + storageBlock.m_index = i; + storageBlock.m_name = QString::fromUtf8(storageBlockName.left(length)); + GLenum prop = GL_BUFFER_BINDING; + m_extraFuncs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_binding); + prop = GL_BUFFER_DATA_SIZE; + m_extraFuncs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_size); + prop = GL_NUM_ACTIVE_VARIABLES; + m_extraFuncs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_activeVariablesCount); + blocks.push_back(storageBlock); + } + return blocks; +} + +UniformType GraphicsHelperES3_1::uniformTypeFromGLType(GLenum glType) +{ + switch (glType) { + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + return UniformType::Sampler; + case GL_IMAGE_2D: + case GL_IMAGE_3D: + case GL_IMAGE_CUBE: + case GL_IMAGE_2D_ARRAY: + case GL_INT_IMAGE_2D: + case GL_INT_IMAGE_3D: + case GL_INT_IMAGE_CUBE: + case GL_INT_IMAGE_2D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D: + case GL_UNSIGNED_INT_IMAGE_3D: + case GL_UNSIGNED_INT_IMAGE_CUBE: + case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: + return UniformType::Image; + + default: + return GraphicsHelperES3::uniformTypeFromGLType(glType); + } +} + +uint GraphicsHelperES3_1::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + + switch (description.m_type) { + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_IMAGE_2D: + case GL_IMAGE_3D: + case GL_IMAGE_CUBE: + case GL_IMAGE_2D_ARRAY: + case GL_INT_IMAGE_2D: + case GL_INT_IMAGE_3D: + case GL_INT_IMAGE_CUBE: + case GL_INT_IMAGE_2D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D: + case GL_UNSIGNED_INT_IMAGE_3D: + case GL_UNSIGNED_INT_IMAGE_CUBE: + case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: + rawByteSize = 4; + break; + + default: + rawByteSize = GraphicsHelperES3::uniformByteSize(description); + break; + } + + return rawByteSize; +} + +void GraphicsHelperES3_1::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + char *bufferData = buffer.data(); + + switch (description.m_type) { + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + { + Q_ASSERT(description.m_size == 1); + int value = v.toInt(); + QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); + break; + } + + default: + GraphicsHelperES3::buildUniformBuffer(v, description, buffer); + break; + } +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h new file mode 100644 index 000000000..7eab61c60 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** Copyright (C) 2018 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_1_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_1_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class GraphicsHelperES3_1 : public GraphicsHelperES3 +{ +public: + GraphicsHelperES3_1(); + ~GraphicsHelperES3_1(); + + bool supportsFeature(Feature feature) const override; + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; + void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; + void memoryBarrier(QMemoryBarrier::Operations barriers) override; + void drawArraysIndirect(GLenum mode,void *indirect) override; + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; + QVector programShaderStorageBlocks(GLuint programId) override; + + // QGraphicHelperInterface interface + UniformType uniformTypeFromGLType(GLenum glType) override; + uint uniformByteSize(const ShaderUniform &description) override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_1_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp new file mode 100644 index 000000000..9d0988410 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp @@ -0,0 +1,193 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelperes3_2_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +#ifndef GL_DRAW_FRAMEBUFFER +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#endif + +#ifndef GL_DEPTH_STENCIL_ATTACHMENT +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#endif + +#ifndef GL_PATCH_VERTICES +#define GL_PATCH_VERTICES 36466 +#endif + +#ifndef GL_IMAGE_BUFFER +#define GL_IMAGE_BUFFER 0x9051 +#endif +#ifndef GL_IMAGE_CUBE_MAP_ARRAY +#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +#endif +#ifndef GL_INT_IMAGE_BUFFER +#define GL_INT_IMAGE_BUFFER 0x905C +#endif +#ifndef GL_INT_IMAGE_CUBE_MAP_ARRAY +#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +#endif +#ifndef GL_UNSIGNED_INT_IMAGE_BUFFER +#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +#endif +#ifndef GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +#endif + +namespace Qt3DRender { +namespace Render { + +GraphicsHelperES3_2::GraphicsHelperES3_2() +{ +} + +GraphicsHelperES3_2::~GraphicsHelperES3_2() +{ +} + +bool GraphicsHelperES3_2::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case GraphicsHelperInterface::Tessellation: + return true; + default: + break; + } + return GraphicsHelperES3_1::supportsFeature(feature); +} + +bool GraphicsHelperES3_2::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + Q_UNUSED(attachment); + // This is first ES version where we have glFramebufferTexture, so + // attaching a D24S8 texture to the combined depth-stencil attachment point + // should work. + return false; +} + +void GraphicsHelperES3_2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + GLenum attr = GL_COLOR_ATTACHMENT0; + + if (attachment.m_point <= QRenderTargetOutput::Color15) + attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::DepthStencil) + attr = GL_DEPTH_STENCIL_ATTACHMENT; + else + qCritical() << "Unsupported FBO attachment OpenGL ES 3.2"; + + const QOpenGLTexture::Target target = texture->target(); + + texture->bind(); + if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face != QAbstractTexture::AllFaces) + m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else + m_extraFuncs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); + texture->release(); +} + +void GraphicsHelperES3_2::setVerticesPerPatch(GLint verticesPerPatch) +{ + m_extraFuncs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); +} + +void GraphicsHelperES3_2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex, GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; + + m_extraFuncs->glDrawElementsInstancedBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + instances, + baseVertex); +} + +UniformType GraphicsHelperES3_2::uniformTypeFromGLType(GLenum glType) +{ + switch (glType) { + case GL_IMAGE_BUFFER: + case GL_IMAGE_CUBE_MAP_ARRAY: + case GL_INT_IMAGE_BUFFER: + case GL_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_UNSIGNED_INT_IMAGE_BUFFER: + case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: + return UniformType::Image; + + default: + return GraphicsHelperES3_1::uniformTypeFromGLType(glType); + } +} + +uint GraphicsHelperES3_2::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + + switch (description.m_type) { + case GL_IMAGE_BUFFER: + case GL_IMAGE_CUBE_MAP_ARRAY: + case GL_INT_IMAGE_BUFFER: + case GL_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_UNSIGNED_INT_IMAGE_BUFFER: + case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: + rawByteSize = 4; + break; + + default: + rawByteSize = GraphicsHelperES3_1::uniformByteSize(description); + break; + } + + return rawByteSize; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h new file mode 100644 index 000000000..9552e656a --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class GraphicsHelperES3_2 : public GraphicsHelperES3_1 +{ +public: + GraphicsHelperES3_2(); + ~GraphicsHelperES3_2(); + + bool supportsFeature(Feature feature) const override; + + // QGraphicHelperInterface interface + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void setVerticesPerPatch(GLint verticesPerPatch) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + UniformType uniformTypeFromGLType(GLenum glType) override; + uint uniformByteSize(const ShaderUniform &description) override; + +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h new file mode 100644 index 000000000..c985ba24a --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h @@ -0,0 +1,108 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 Svenn-Arne Dragly. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class GraphicsHelperES3 : public GraphicsHelperES2 +{ +public: + GraphicsHelperES3(); + ~GraphicsHelperES3(); + + // QGraphicHelperInterface interface + void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; + void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; + void drawBuffers(GLsizei n, const int *bufs) override; + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + void readBuffer(GLenum mode) override; + void drawBuffer(GLenum mode) override; + void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; + char *mapBuffer(GLenum target, GLsizeiptr size) override; + QVector programUniformsAndLocations(GLuint programId) override; + QVector programUniformBlocks(GLuint programId) override; + bool supportsFeature(Feature feature) const override; + GLboolean unmapBuffer(GLenum target) override; + void vertexAttribDivisor(GLuint index, GLuint divisor) override; + void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; + + UniformType uniformTypeFromGLType(GLenum glType) override; + uint uniformByteSize(const ShaderUniform &description) override; + + void *fenceSync() override; + void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; + void waitSync(void *sync) override; + bool wasSyncSignaled(void *sync) override; + void deleteSync(void *sync) override; + +protected: + QOpenGLExtraFunctions *m_extraFuncs = nullptr; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp new file mode 100644 index 000000000..3afc29d2f --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp @@ -0,0 +1,935 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelpergl2_p.h" +#ifndef QT_OPENGL_ES_2 +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +GraphicsHelperGL2::GraphicsHelperGL2() + : m_funcs(nullptr) + , m_fboFuncs(nullptr) +{ + +} + +void GraphicsHelperGL2::initializeHelper(QOpenGLContext *context, + QAbstractOpenGLFunctions *functions) +{ + Q_UNUSED(context); + m_funcs = static_cast(functions); + const bool ok = m_funcs->initializeOpenGLFunctions(); + Q_ASSERT(ok); + Q_UNUSED(ok); + if (context->hasExtension(QByteArrayLiteral("GL_ARB_framebuffer_object"))) { + m_fboFuncs = new QOpenGLExtension_ARB_framebuffer_object(); + const bool extensionOk = m_fboFuncs->initializeOpenGLFunctions(); + Q_ASSERT(extensionOk); + Q_UNUSED(extensionOk); + } +} + +void GraphicsHelperGL2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; + + if (baseVertex != 0) + qWarning() << "glDrawElementsInstancedBaseVertex is not supported with OpenGL ES 2"; + + for (GLint i = 0; i < instances; i++) + drawElements(primitiveType, + primitiveCount, + indexType, + indices); +} + +void GraphicsHelperGL2::drawArraysInstanced(GLenum primitiveType, + GLint first, + GLsizei count, + GLsizei instances) +{ + for (GLint i = 0; i < instances; i++) + drawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperGL2::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL 2"; + for (GLint i = 0; i < instances; i++) + drawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperGL2::drawElements(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLint baseVertex) +{ + if (baseVertex != 0) + qWarning() << "glDrawElementsBaseVertex is not supported with OpenGL 2"; + + m_funcs->glDrawElements(primitiveType, + primitiveCount, + indexType, + indices); +} + +void GraphicsHelperGL2::drawArrays(GLenum primitiveType, + GLint first, + GLsizei count) +{ + m_funcs->glDrawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperGL2::drawElementsIndirect(GLenum, GLenum, void *) +{ + qWarning() << "Indirect Drawing is not supported with OpenGL 2"; +} + +void GraphicsHelperGL2::drawArraysIndirect(GLenum , void *) +{ + qWarning() << "Indirect Drawing is not supported with OpenGL 2"; +} + +void GraphicsHelperGL2::setVerticesPerPatch(GLint verticesPerPatch) +{ + Q_UNUSED(verticesPerPatch); + qWarning() << "Tessellation not supported with OpenGL 2"; +} + +void GraphicsHelperGL2::useProgram(GLuint programId) +{ + m_funcs->glUseProgram(programId); +} + +QVector GraphicsHelperGL2::programUniformsAndLocations(GLuint programId) +{ + QVector uniforms; + + GLint nbrActiveUniforms = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); + uniforms.reserve(nbrActiveUniforms); + char uniformName[256]; + for (GLint i = 0; i < nbrActiveUniforms; i++) { + ShaderUniform uniform; + GLsizei uniformNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, + &uniform.m_size, &uniform.m_type, uniformName); + uniformName[sizeof(uniformName) - 1] = '\0'; + uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); + uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); + // Work around for uniform array names that aren't returned with [0] by some drivers + if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) + uniform.m_name.append(QLatin1String("[0]")); + uniform.m_rawByteSize = uniformByteSize(uniform); + uniforms.append(uniform); + } + return uniforms; +} + +QVector GraphicsHelperGL2::programAttributesAndLocations(GLuint programId) +{ + QVector attributes; + GLint nbrActiveAttributes = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); + attributes.reserve(nbrActiveAttributes); + char attributeName[256]; + for (GLint i = 0; i < nbrActiveAttributes; i++) { + ShaderAttribute attribute; + GLsizei attributeNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, + &attribute.m_size, &attribute.m_type, attributeName); + attributeName[sizeof(attributeName) - 1] = '\0'; + attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); + attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); + attributes.append(attribute); + } + return attributes; +} + +QVector GraphicsHelperGL2::programUniformBlocks(GLuint programId) +{ + Q_UNUSED(programId); + QVector blocks; + qWarning() << "UBO are not supported by OpenGL 2.0 (since OpenGL 3.1)"; + return blocks; +} + +QVector GraphicsHelperGL2::programShaderStorageBlocks(GLuint programId) +{ + Q_UNUSED(programId); + qWarning() << "SSBO are not supported by OpenGL 2.0 (since OpenGL 4.3)"; + return QVector(); +} + +void GraphicsHelperGL2::vertexAttribDivisor(GLuint index, + GLuint divisor) +{ + Q_UNUSED(index); + Q_UNUSED(divisor); +} + +void GraphicsHelperGL2::vertexAttributePointer(GLenum shaderDataType, + GLuint index, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + const GLvoid *pointer) +{ + switch (shaderDataType) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + case GL_FLOAT_MAT2: + case GL_FLOAT_MAT2x3: + case GL_FLOAT_MAT2x4: + case GL_FLOAT_MAT3: + case GL_FLOAT_MAT3x2: + case GL_FLOAT_MAT3x4: + case GL_FLOAT_MAT4x2: + case GL_FLOAT_MAT4x3: + case GL_FLOAT_MAT4: + m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); + break; + + default: + qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + Q_UNREACHABLE(); + } +} + +void GraphicsHelperGL2::readBuffer(GLenum mode) +{ + m_funcs->glReadBuffer(mode); +} + +void GraphicsHelperGL2::drawBuffer(GLenum mode) +{ + m_funcs->glDrawBuffer(mode); +} + +void *GraphicsHelperGL2::fenceSync() +{ + qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; + return nullptr; +} + +void GraphicsHelperGL2::clientWaitSync(void *, GLuint64 ) +{ + qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; +} + +void GraphicsHelperGL2::waitSync(void *) +{ + qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; +} + +bool GraphicsHelperGL2::wasSyncSignaled(void *) +{ + qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; + return false; +} + +void GraphicsHelperGL2::deleteSync(void *) +{ + qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; +} + +void GraphicsHelperGL2::rasterMode(GLenum faceMode, GLenum rasterMode) +{ + m_funcs->glPolygonMode(faceMode, rasterMode); +} + +void GraphicsHelperGL2::blendEquation(GLenum mode) +{ + m_funcs->glBlendEquation(mode); +} + +void GraphicsHelperGL2::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) +{ + Q_UNUSED(buf); + Q_UNUSED(sfactor); + Q_UNUSED(dfactor); + + qWarning() << "glBlendFunci() not supported by OpenGL 2.0 (since OpenGL 4.0)"; +} + +void GraphicsHelperGL2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) +{ + Q_UNUSED(buf); + Q_UNUSED(sRGB); + Q_UNUSED(dRGB); + Q_UNUSED(sAlpha); + Q_UNUSED(dAlpha); + + qWarning() << "glBlendFuncSeparatei() not supported by OpenGL 2.0 (since OpenGL 4.0)"; +} + +void GraphicsHelperGL2::alphaTest(GLenum mode1, GLenum mode2) +{ + m_funcs->glEnable(GL_ALPHA_TEST); + m_funcs->glAlphaFunc(mode1, mode2); +} + +void GraphicsHelperGL2::depthTest(GLenum mode) +{ + m_funcs->glEnable(GL_DEPTH_TEST); + m_funcs->glDepthFunc(mode); +} + +void GraphicsHelperGL2::depthMask(GLenum mode) +{ + m_funcs->glDepthMask(mode); +} + +void GraphicsHelperGL2::depthRange(GLdouble nearValue, GLdouble farValue) +{ + m_funcs->glDepthRange(nearValue, farValue); +} + +void GraphicsHelperGL2::frontFace(GLenum mode) +{ + m_funcs->glFrontFace(mode); +} + +void GraphicsHelperGL2::setMSAAEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_MULTISAMPLE) + : m_funcs->glDisable(GL_MULTISAMPLE); +} + +void GraphicsHelperGL2::setAlphaCoverageEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) + : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); +} + +GLuint GraphicsHelperGL2::createFrameBufferObject() +{ + if (m_fboFuncs != nullptr) { + GLuint id; + m_fboFuncs->glGenFramebuffers(1, &id); + return id; + } + qWarning() << "FBO not supported by your OpenGL hardware"; + return 0; +} + +void GraphicsHelperGL2::releaseFrameBufferObject(GLuint frameBufferId) +{ + if (m_fboFuncs != nullptr) + m_fboFuncs->glDeleteFramebuffers(1, &frameBufferId); + else + qWarning() << "FBO not supported by your OpenGL hardware"; +} + +bool GraphicsHelperGL2::checkFrameBufferComplete() +{ + if (m_fboFuncs != nullptr) + return (m_fboFuncs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); + return false; +} + +bool GraphicsHelperGL2::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + Q_UNUSED(attachment); + return false; +} + +void GraphicsHelperGL2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + if (m_fboFuncs != nullptr) { + GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; + + if (attachment.m_point <= QRenderTargetOutput::Color15) + attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + else + qCritical() << "DepthStencil Attachment not supported on OpenGL 2.0"; + + const QOpenGLTexture::Target target = texture->target(); + + if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face == QAbstractTexture::AllFaces) { + qWarning() << "OpenGL 2.0 doesn't handle attaching all the faces of a cube map texture at once to an FBO"; + return; + } + + texture->bind(); + if (target == QOpenGLTexture::Target3D) + m_fboFuncs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMap) + m_fboFuncs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else if (target == QOpenGLTexture::Target1D) + m_fboFuncs->glFramebufferTexture1D(GL_DRAW_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); + else if (target == QOpenGLTexture::Target2D || target == QOpenGLTexture::TargetRectangle) + m_fboFuncs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); + else + qCritical() << "Texture format not supported for Attachment on OpenGL 2.0"; + texture->release(); + } +} + +void GraphicsHelperGL2::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) +{ + Q_UNUSED(renderBuffer); + Q_UNUSED(attachment); + Q_UNREACHABLE(); +} + +bool GraphicsHelperGL2::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case MRT: + return (m_fboFuncs != nullptr); + case TextureDimensionRetrieval: + case MapBuffer: + return true; + default: + return false; + } +} + +void GraphicsHelperGL2::drawBuffers(GLsizei n, const int *bufs) +{ + QVarLengthArray drawBufs(n); + + for (int i = 0; i < n; i++) + drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; + m_funcs->glDrawBuffers(n, drawBufs.constData()); +} + +void GraphicsHelperGL2::bindFragDataLocation(GLuint, const QHash &) +{ + qCritical() << "bindFragDataLocation is not supported by GL 2.0"; +} + +void GraphicsHelperGL2::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) +{ + if (m_fboFuncs != nullptr) { + switch (mode) { + case FBODraw: + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); + return; + case FBORead: + m_fboFuncs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); + return; + case FBOReadAndDraw: + default: + m_fboFuncs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); + return; + } + } else { + qWarning() << "FBO not supported by your OpenGL hardware"; + } +} + +void GraphicsHelperGL2::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + Q_UNUSED(imageUnit) + Q_UNUSED(texture) + Q_UNUSED(mipLevel) + Q_UNUSED(layered) + Q_UNUSED(layer) + Q_UNUSED(access) + Q_UNUSED(format) + qWarning() << "Shader Images are not supported by OpenGL 2.0 (since OpenGL 4.2)"; + +} + +GLuint GraphicsHelperGL2::boundFrameBufferObject() +{ + GLint id = 0; + m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); + return id; +} + +void GraphicsHelperGL2::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + Q_UNUSED(programId); + Q_UNUSED(uniformBlockIndex); + Q_UNUSED(uniformBlockBinding); + qWarning() << "UBO are not supported by OpenGL 2.0 (since OpenGL 3.1)"; +} + +void GraphicsHelperGL2::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) +{ + Q_UNUSED(programId); + Q_UNUSED(shaderStorageBlockIndex); + Q_UNUSED(shaderStorageBlockBinding); + qWarning() << "SSBO are not supported by OpenGL 2.0 (since OpenGL 4.3)"; +} + +void GraphicsHelperGL2::bindBufferBase(GLenum target, GLuint index, GLuint buffer) +{ + Q_UNUSED(target); + Q_UNUSED(index); + Q_UNUSED(buffer); + qWarning() << "bindBufferBase is not supported by OpenGL 2.0 (since OpenGL 3.0)"; +} + +void GraphicsHelperGL2::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + Q_UNUSED(v); + Q_UNUSED(description); + Q_UNUSED(buffer); + qWarning() << "UBO are not supported by OpenGL 2.0 (since OpenGL 3.1)"; +} + +uint GraphicsHelperGL2::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + int arrayStride = qMax(description.m_arrayStride, 0); + int matrixStride = qMax(description.m_matrixStride, 0); + + switch (description.m_type) { + + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + rawByteSize = 8; + break; + + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + rawByteSize = 12; + break; + + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + rawByteSize = 16; + break; + + case GL_FLOAT_MAT2: + rawByteSize = matrixStride ? 2 * matrixStride : 16; + break; + + case GL_FLOAT_MAT2x4: + rawByteSize = matrixStride ? 2 * matrixStride : 32; + break; + + case GL_FLOAT_MAT4x2: + rawByteSize = matrixStride ? 4 * matrixStride : 32; + break; + + case GL_FLOAT_MAT3: + rawByteSize = matrixStride ? 3 * matrixStride : 36; + break; + + case GL_FLOAT_MAT2x3: + rawByteSize = matrixStride ? 2 * matrixStride : 24; + break; + + case GL_FLOAT_MAT3x2: + rawByteSize = matrixStride ? 3 * matrixStride : 24; + break; + + case GL_FLOAT_MAT4: + rawByteSize = matrixStride ? 4 * matrixStride : 64; + break; + + case GL_FLOAT_MAT4x3: + rawByteSize = matrixStride ? 4 * matrixStride : 48; + break; + + case GL_FLOAT_MAT3x4: + rawByteSize = matrixStride ? 3 * matrixStride : 48; + break; + + case GL_BOOL: + rawByteSize = 1; + break; + + case GL_BOOL_VEC2: + rawByteSize = 2; + break; + + case GL_BOOL_VEC3: + rawByteSize = 3; + break; + + case GL_BOOL_VEC4: + rawByteSize = 4; + break; + + case GL_INT: + case GL_FLOAT: + case GL_SAMPLER_1D: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + rawByteSize = 4; + break; + + default: + Q_UNREACHABLE(); + } + + return arrayStride ? rawByteSize * arrayStride : rawByteSize; +} + +void GraphicsHelperGL2::enableClipPlane(int clipPlane) +{ + m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL2::disableClipPlane(int clipPlane) +{ + m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL2::setClipPlane(int clipPlane, const QVector3D &normal, float distance) +{ + double plane[4]; + plane[0] = normal.x(); + plane[1] = normal.y(); + plane[2] = normal.z(); + plane[3] = distance; + + m_funcs->glClipPlane(GL_CLIP_PLANE0 + clipPlane, plane); +} + +GLint GraphicsHelperGL2::maxClipPlaneCount() +{ + GLint max = 0; + m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); + return max; +} + +void GraphicsHelperGL2::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + Q_UNUSED(barriers); + qWarning() << "memory barrier is not supported by OpenGL 2.0 (since 4.3)"; +} + +void GraphicsHelperGL2::enablePrimitiveRestart(int) +{ +} + +void GraphicsHelperGL2::enableVertexAttributeArray(int location) +{ + m_funcs->glEnableVertexAttribArray(location); +} + +void GraphicsHelperGL2::disablePrimitiveRestart() +{ +} + +void GraphicsHelperGL2::clearBufferf(GLint drawbuffer, const QVector4D &values) +{ + Q_UNUSED(drawbuffer); + Q_UNUSED(values); + qWarning() << "glClearBuffer*() not supported by OpenGL 2.0"; +} + +void GraphicsHelperGL2::pointSize(bool programmable, GLfloat value) +{ + m_funcs->glEnable(GL_POINT_SPRITE); + if (programmable) + m_funcs->glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); + else + m_funcs->glPointSize(value); +} + +void GraphicsHelperGL2::enablei(GLenum cap, GLuint index) +{ + Q_UNUSED(cap); + Q_UNUSED(index); + qWarning() << "glEnablei() not supported by OpenGL 2.0 (since 3.0)"; +} + +void GraphicsHelperGL2::disablei(GLenum cap, GLuint index) +{ + Q_UNUSED(cap); + Q_UNUSED(index); + qWarning() << "glDisablei() not supported by OpenGL 2.0 (since 3.0)"; +} + +void GraphicsHelperGL2::setSeamlessCubemap(bool enable) +{ + Q_UNUSED(enable); + qWarning() << "GL_TEXTURE_CUBE_MAP_SEAMLESS not supported by OpenGL 2.0 (since 3.2)"; +} + +QSize GraphicsHelperGL2::getRenderBufferDimensions(GLuint renderBufferId) +{ + Q_UNUSED(renderBufferId); + qCritical() << "RenderBuffer dimensions retrival not supported on OpenGL 2.0"; + return QSize(0,0); +} + +QSize GraphicsHelperGL2::getTextureDimensions(GLuint textureId, GLenum target, uint level) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindTexture(target, textureId); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); + m_funcs->glBindTexture(target, 0); + + return QSize(width, height); +} + +void GraphicsHelperGL2::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) +{ + Q_UNUSED(wx); + Q_UNUSED(wy); + Q_UNUSED(wz); + qWarning() << "Compute Shaders are not supported by OpenGL 2.0 (since OpenGL 4.3)"; +} + +char *GraphicsHelperGL2::mapBuffer(GLenum target, GLsizeiptr size) +{ + Q_UNUSED(size); + return static_cast(m_funcs->glMapBuffer(target, GL_READ_WRITE)); +} + +GLboolean GraphicsHelperGL2::unmapBuffer(GLenum target) +{ + return m_funcs->glUnmapBuffer(target); +} + +void GraphicsHelperGL2::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform1fv(location, count, values); +} + +void GraphicsHelperGL2::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform2fv(location, count, values); +} + +void GraphicsHelperGL2::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform3fv(location, count, values); +} + +void GraphicsHelperGL2::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform4fv(location, count, values); +} + +void GraphicsHelperGL2::glUniform1iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform1iv(location, count, values); +} + +void GraphicsHelperGL2::glUniform2iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform2iv(location, count, values); +} + +void GraphicsHelperGL2::glUniform3iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform3iv(location, count, values); +} + +void GraphicsHelperGL2::glUniform4iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform4iv(location, count, values); +} + +void GraphicsHelperGL2::glUniform1uiv(GLint , GLsizei , const GLuint *) +{ + qWarning() << "glUniform1uiv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniform2uiv(GLint , GLsizei , const GLuint *) +{ + qWarning() << "glUniform2uiv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniform3uiv(GLint , GLsizei , const GLuint *) +{ + qWarning() << "glUniform3uiv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniform4uiv(GLint , GLsizei , const GLuint *) +{ + qWarning() << "glUniform4uiv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2fv(location, count, false, values); +} + +void GraphicsHelperGL2::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3fv(location, count, false, values); +} + +void GraphicsHelperGL2::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4fv(location, count, false, values); +} + +void GraphicsHelperGL2::glUniformMatrix2x3fv(GLint , GLsizei , const GLfloat *) +{ + qWarning() << "glUniformMatrix2x3fv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniformMatrix3x2fv(GLint , GLsizei , const GLfloat *) +{ + qWarning() << "glUniformMatrix3x2fv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniformMatrix2x4fv(GLint , GLsizei , const GLfloat *) +{ + qWarning() << "glUniformMatrix2x4fv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniformMatrix4x2fv(GLint , GLsizei , const GLfloat *) +{ + qWarning() << "glUniformMatrix4x2fv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniformMatrix3x4fv(GLint , GLsizei , const GLfloat *) +{ + qWarning() << "glUniformMatrix3x4fv not supported by GL 2"; +} + +void GraphicsHelperGL2::glUniformMatrix4x3fv(GLint , GLsizei , const GLfloat *) +{ + qWarning() << "glUniformMatrix4x3fv not supported by GL 2"; +} + +UniformType GraphicsHelperGL2::uniformTypeFromGLType(GLenum type) +{ + switch (type) { + case GL_FLOAT: + return UniformType::Float; + case GL_FLOAT_VEC2: + return UniformType::Vec2; + case GL_FLOAT_VEC3: + return UniformType::Vec3; + case GL_FLOAT_VEC4: + return UniformType::Vec4; + case GL_FLOAT_MAT2: + return UniformType::Mat2; + case GL_FLOAT_MAT3: + return UniformType::Mat3; + case GL_FLOAT_MAT4: + return UniformType::Mat4; + case GL_INT: + return UniformType::Int; + case GL_INT_VEC2: + return UniformType::IVec2; + case GL_INT_VEC3: + return UniformType::IVec3; + case GL_INT_VEC4: + return UniformType::IVec4; + case GL_BOOL: + return UniformType::Bool; + case GL_BOOL_VEC2: + return UniformType::BVec2; + case GL_BOOL_VEC3: + return UniformType::BVec3; + case GL_BOOL_VEC4: + return UniformType::BVec4; + + case GL_SAMPLER_1D: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_3D: + return UniformType::Sampler; + + default: + Q_UNREACHABLE(); + return UniformType::Float; + } +} + +void GraphicsHelperGL2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) +{ + Q_UNUSED(srcX0); + Q_UNUSED(srcX1); + Q_UNUSED(srcY0); + Q_UNUSED(srcY1); + Q_UNUSED(dstX0); + Q_UNUSED(dstX1); + Q_UNUSED(dstY0); + Q_UNUSED(dstY1); + Q_UNUSED(mask); + Q_UNUSED(filter); + qWarning() << "Framebuffer blits are not supported by ES 2.0 (since ES 3.1)"; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h new file mode 100644 index 000000000..35391471f --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h @@ -0,0 +1,183 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +#ifndef QT_OPENGL_ES_2 + +QT_BEGIN_NAMESPACE + +class QOpenGLFunctions_2_0; +class QOpenGLExtension_ARB_framebuffer_object; + +namespace Qt3DRender { +namespace Render { + +class Q_AUTOTEST_EXPORT GraphicsHelperGL2 : public GraphicsHelperInterface +{ +public: + GraphicsHelperGL2(); + + // QGraphicHelperInterface interface + void alphaTest(GLenum mode1, GLenum mode2) override; + void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; + void bindFragDataLocation(GLuint shader, const QHash &outputs) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; + void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; + void blendEquation(GLenum mode) override; + void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; + void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; + void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; + GLuint boundFrameBufferObject() override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; + bool checkFrameBufferComplete() override; + void clearBufferf(GLint drawbuffer, const QVector4D &values) override; + GLuint createFrameBufferObject() override; + void depthMask(GLenum mode) override; + void depthRange(GLdouble nearValue, GLdouble farValue) override; + void depthTest(GLenum mode) override; + void disableClipPlane(int clipPlane) override; + void disablei(GLenum cap, GLuint index) override; + void disablePrimitiveRestart() override; + void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; + char *mapBuffer(GLenum target, GLsizeiptr size) override; + GLboolean unmapBuffer(GLenum target) override; + void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; + void drawArraysIndirect(GLenum mode,void *indirect) override; + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; + void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; + void drawBuffers(GLsizei n, const int *bufs) override; + void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + void enableClipPlane(int clipPlane) override; + void enablei(GLenum cap, GLuint index) override; + void enablePrimitiveRestart(int primitiveRestartIndex) override; + void enableVertexAttributeArray(int location) override; + void frontFace(GLenum mode) override; + QSize getRenderBufferDimensions(GLuint renderBufferId) override; + QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; + void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; + void pointSize(bool programmable, GLfloat value) override; + GLint maxClipPlaneCount() override; + void memoryBarrier(QMemoryBarrier::Operations barriers) override; + QVector programUniformBlocks(GLuint programId) override; + QVector programAttributesAndLocations(GLuint programId) override; + QVector programUniformsAndLocations(GLuint programId) override; + QVector programShaderStorageBlocks(GLuint programId) override; + void releaseFrameBufferObject(GLuint frameBufferId) override; + void setMSAAEnabled(bool enable) override; + void setAlphaCoverageEnabled(bool enable) override; + void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; + void setSeamlessCubemap(bool enable) override; + void setVerticesPerPatch(GLint verticesPerPatch) override; + bool supportsFeature(Feature feature) const override; + uint uniformByteSize(const ShaderUniform &description) override; + void useProgram(GLuint programId) override; + void vertexAttribDivisor(GLuint index, GLuint divisor) override; + void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; + void readBuffer(GLenum mode) override; + void drawBuffer(GLenum mode) override; + void rasterMode(GLenum faceMode, GLenum rasterMode) override; + + void *fenceSync() override; + void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; + void waitSync(void *sync) override; + bool wasSyncSignaled(void *sync) override; + void deleteSync(void *sync) override; + + void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; + + void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; + + void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; + + void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; + + UniformType uniformTypeFromGLType(GLenum glType) override; + +private: + QOpenGLFunctions_2_0 *m_funcs; + QOpenGLExtension_ARB_framebuffer_object *m_fboFuncs; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp new file mode 100644 index 000000000..17850cf00 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp @@ -0,0 +1,1245 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelpergl3_2_p.h" + +#ifndef QT_OPENGL_ES_2 +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +# ifndef QT_OPENGL_3 +# define GL_PATCH_VERTICES 36466 +# define GL_ACTIVE_RESOURCES 0x92F5 +# define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +# define GL_BUFFER_BINDING 0x9302 +# define GL_BUFFER_DATA_SIZE 0x9303 +# define GL_NUM_ACTIVE_VARIABLES 0x9304 +# define GL_SHADER_STORAGE_BLOCK 0x92E6 +# define GL_UNIFORM 0x92E1 +# define GL_UNIFORM_BLOCK 0x92E2 +# define GL_UNIFORM_BLOCK_INDEX 0x8A3A +# define GL_UNIFORM_OFFSET 0x8A3B +# define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +# define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +# define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +# define GL_UNIFORM_BLOCK_BINDING 0x8A3F +# define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +# endif + +namespace Qt3DRender { +namespace Render { + +GraphicsHelperGL3_2::GraphicsHelperGL3_2() + : m_funcs(nullptr) + , m_tessFuncs() +{ +} + +GraphicsHelperGL3_2::~GraphicsHelperGL3_2() +{ +} + +void GraphicsHelperGL3_2::initializeHelper(QOpenGLContext *context, + QAbstractOpenGLFunctions *functions) +{ + m_funcs = static_cast(functions); + const bool ok = m_funcs->initializeOpenGLFunctions(); + Q_ASSERT(ok); + Q_UNUSED(ok); + + if (context->hasExtension(QByteArrayLiteral("GL_ARB_tessellation_shader"))) { + m_tessFuncs.reset(new QOpenGLExtension_ARB_tessellation_shader); + m_tessFuncs->initializeOpenGLFunctions(); + } +} + +void GraphicsHelperGL3_2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; + + // glDrawElements OpenGL 3.1 or greater + m_funcs->glDrawElementsInstancedBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + instances, + baseVertex); +} + +void GraphicsHelperGL3_2::drawArraysInstanced(GLenum primitiveType, + GLint first, + GLsizei count, + GLsizei instances) +{ + // glDrawArraysInstanced OpenGL 3.1 or greater + m_funcs->glDrawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsHelperGL3_2::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL 3"; + m_funcs->glDrawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsHelperGL3_2::drawElements(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLint baseVertex) +{ + m_funcs->glDrawElementsBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + baseVertex); +} + +void GraphicsHelperGL3_2::drawArrays(GLenum primitiveType, + GLint first, + GLsizei count) +{ + m_funcs->glDrawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperGL3_2::drawElementsIndirect(GLenum, GLenum, void *) +{ + qWarning() << "Indirect Drawing is not supported with OpenGL 3.2"; +} + +void GraphicsHelperGL3_2::drawArraysIndirect(GLenum , void *) +{ + qWarning() << "Indirect Drawing is not supported with OpenGL 3.2"; +} + +void GraphicsHelperGL3_2::setVerticesPerPatch(GLint verticesPerPatch) +{ +#if defined(QT_OPENGL_4) + if (!m_tessFuncs) { + qWarning() << "Tessellation not supported with OpenGL 3 without GL_ARB_tessellation_shader"; + return; + } + + m_tessFuncs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); +#else + Q_UNUSED(verticesPerPatch); + qWarning() << "Tessellation not supported"; +#endif +} + +void GraphicsHelperGL3_2::useProgram(GLuint programId) +{ + m_funcs->glUseProgram(programId); +} + +QVector GraphicsHelperGL3_2::programUniformsAndLocations(GLuint programId) +{ + QVector uniforms; + + GLint nbrActiveUniforms = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); + uniforms.reserve(nbrActiveUniforms); + char uniformName[256]; + for (GLint i = 0; i < nbrActiveUniforms; i++) { + ShaderUniform uniform; + GLsizei uniformNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, + &uniform.m_size, &uniform.m_type, uniformName); + uniformName[sizeof(uniformName) - 1] = '\0'; + uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); + uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); + // Work around for uniform array names that aren't returned with [0] by some drivers + if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) + uniform.m_name.append(QLatin1String("[0]")); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); + uniform.m_rawByteSize = uniformByteSize(uniform); + uniforms.append(uniform); + qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; + } + + return uniforms; +} + +QVector GraphicsHelperGL3_2::programAttributesAndLocations(GLuint programId) +{ + QVector attributes; + GLint nbrActiveAttributes = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); + attributes.reserve(nbrActiveAttributes); + char attributeName[256]; + for (GLint i = 0; i < nbrActiveAttributes; i++) { + ShaderAttribute attribute; + GLsizei attributeNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, + &attribute.m_size, &attribute.m_type, attributeName); + attributeName[sizeof(attributeName) - 1] = '\0'; + attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); + attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); + attributes.append(attribute); + } + return attributes; +} + +QVector GraphicsHelperGL3_2::programUniformBlocks(GLuint programId) +{ + QVector blocks; + GLint nbrActiveUniformsBlocks = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORM_BLOCKS, &nbrActiveUniformsBlocks); + blocks.reserve(nbrActiveUniformsBlocks); + for (GLint i = 0; i < nbrActiveUniformsBlocks; i++) { + QByteArray uniformBlockName(256, '\0'); + GLsizei length = 0; + ShaderUniformBlock uniformBlock; + m_funcs->glGetActiveUniformBlockName(programId, i, 256, &length, uniformBlockName.data()); + uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); + uniformBlock.m_index = i; + m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &uniformBlock.m_activeUniformsCount); + m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_BINDING, &uniformBlock.m_binding); + m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.m_size); + blocks.append(uniformBlock); + } + return blocks; +} + +QVector GraphicsHelperGL3_2::programShaderStorageBlocks(GLuint programId) +{ + Q_UNUSED(programId); + QVector blocks; + qWarning() << "SSBO are not supported by OpenGL 3.2 (since OpenGL 4.3)"; + return blocks; +} + +void GraphicsHelperGL3_2::vertexAttribDivisor(GLuint index, GLuint divisor) +{ + Q_UNUSED(index); + Q_UNUSED(divisor); + qCWarning(Render::Rendering) << "Vertex attribute divisor not available with OpenGL 3.2 core"; +} + +void GraphicsHelperGL3_2::vertexAttributePointer(GLenum shaderDataType, + GLuint index, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + const GLvoid *pointer) +{ + switch (shaderDataType) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + case GL_FLOAT_MAT2: + case GL_FLOAT_MAT2x3: + case GL_FLOAT_MAT2x4: + case GL_FLOAT_MAT3: + case GL_FLOAT_MAT3x2: + case GL_FLOAT_MAT3x4: + case GL_FLOAT_MAT4x2: + case GL_FLOAT_MAT4x3: + case GL_FLOAT_MAT4: + m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); + break; + + case GL_INT: + case GL_INT_VEC2: + case GL_INT_VEC3: + case GL_INT_VEC4: + case GL_UNSIGNED_INT: + case GL_UNSIGNED_INT_VEC2: + case GL_UNSIGNED_INT_VEC3: + case GL_UNSIGNED_INT_VEC4: + m_funcs->glVertexAttribIPointer(index, size, type, stride, pointer); + break; + + default: + qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + Q_UNREACHABLE(); + } +} + +void GraphicsHelperGL3_2::readBuffer(GLenum mode) +{ + m_funcs->glReadBuffer(mode); +} + +void GraphicsHelperGL3_2::drawBuffer(GLenum mode) +{ + m_funcs->glDrawBuffer(mode); +} + +void *GraphicsHelperGL3_2::fenceSync() +{ + return m_funcs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); +} + +void GraphicsHelperGL3_2::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) +{ + m_funcs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); +} + +void GraphicsHelperGL3_2::waitSync(void *sync) +{ + m_funcs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); +} + +bool GraphicsHelperGL3_2::wasSyncSignaled(void *sync) +{ + GLint v; + m_funcs->glGetSynciv(static_cast(sync), + GL_SYNC_STATUS, + sizeof(v), + nullptr, + &v); + return v == GL_SIGNALED; +} + +void GraphicsHelperGL3_2::deleteSync(void *sync) +{ + m_funcs->glDeleteSync(static_cast(sync)); +} + +void GraphicsHelperGL3_2::rasterMode(GLenum faceMode, GLenum rasterMode) +{ + m_funcs->glPolygonMode(faceMode, rasterMode); +} + +void GraphicsHelperGL3_2::blendEquation(GLenum mode) +{ + m_funcs->glBlendEquation(mode); +} + +void GraphicsHelperGL3_2::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) +{ + Q_UNUSED(buf); + Q_UNUSED(sfactor); + Q_UNUSED(dfactor); + + qWarning() << "glBlendFunci() not supported by OpenGL 3.0 (since OpenGL 4.0)"; +} + +void GraphicsHelperGL3_2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) +{ + Q_UNUSED(buf); + Q_UNUSED(sRGB); + Q_UNUSED(dRGB); + Q_UNUSED(sAlpha); + Q_UNUSED(dAlpha); + + qWarning() << "glBlendFuncSeparatei() not supported by OpenGL 3.0 (since OpenGL 4.0)"; +} + +void GraphicsHelperGL3_2::alphaTest(GLenum, GLenum) +{ + qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; +} + +void GraphicsHelperGL3_2::depthTest(GLenum mode) +{ + m_funcs->glEnable(GL_DEPTH_TEST); + m_funcs->glDepthFunc(mode); +} + +void GraphicsHelperGL3_2::depthMask(GLenum mode) +{ + m_funcs->glDepthMask(mode); +} + +void GraphicsHelperGL3_2::depthRange(GLdouble nearValue, GLdouble farValue) +{ + m_funcs->glDepthRange(nearValue, farValue); +} + +void GraphicsHelperGL3_2::frontFace(GLenum mode) +{ + m_funcs->glFrontFace(mode); + +} + +void GraphicsHelperGL3_2::setMSAAEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_MULTISAMPLE) + : m_funcs->glDisable(GL_MULTISAMPLE); +} + +void GraphicsHelperGL3_2::setAlphaCoverageEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) + : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); +} + +GLuint GraphicsHelperGL3_2::createFrameBufferObject() +{ + GLuint id; + m_funcs->glGenFramebuffers(1, &id); + return id; +} + +void GraphicsHelperGL3_2::releaseFrameBufferObject(GLuint frameBufferId) +{ + m_funcs->glDeleteFramebuffers(1, &frameBufferId); +} + +void GraphicsHelperGL3_2::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) +{ + switch (mode) { + case FBODraw: + m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); + return; + case FBORead: + m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); + return; + case FBOReadAndDraw: + default: + m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); + return; + } +} + +void GraphicsHelperGL3_2::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + Q_UNUSED(imageUnit) + Q_UNUSED(texture) + Q_UNUSED(mipLevel) + Q_UNUSED(layered) + Q_UNUSED(layer) + Q_UNUSED(access) + Q_UNUSED(format) + qWarning() << "Shader Images are not supported by OpenGL 3.2 (since OpenGL 4.2)"; + +} + +GLuint GraphicsHelperGL3_2::boundFrameBufferObject() +{ + GLint id = 0; + m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); + return id; +} + +bool GraphicsHelperGL3_2::checkFrameBufferComplete() +{ + return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); +} + +bool GraphicsHelperGL3_2::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + Q_UNUSED(attachment); + return false; +} + +void GraphicsHelperGL3_2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; + + if (attachment.m_point <= QRenderTargetOutput::Color15) + attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + + texture->bind(); + QOpenGLTexture::Target target = texture->target(); + if (target == QOpenGLTexture::Target1DArray || target == QOpenGLTexture::Target2DArray || + target == QOpenGLTexture::Target2DMultisampleArray || target == QOpenGLTexture::Target3D) + m_funcs->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMapArray) + m_funcs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMap) + m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else + m_funcs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); + texture->release(); +} + +void GraphicsHelperGL3_2::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) +{ + Q_UNUSED(renderBuffer); + Q_UNUSED(attachment); + Q_UNREACHABLE(); +} + +bool GraphicsHelperGL3_2::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case MRT: + case UniformBufferObject: + case PrimitiveRestart: + case RenderBufferDimensionRetrieval: + case TextureDimensionRetrieval: + case BindableFragmentOutputs: + case BlitFramebuffer: + case Fences: + return true; + case Tessellation: + return !m_tessFuncs.isNull(); + default: + return false; + } +} + +void GraphicsHelperGL3_2::drawBuffers(GLsizei n, const int *bufs) +{ + // Use QVarLengthArray here + QVarLengthArray drawBufs(n); + + for (int i = 0; i < n; i++) + drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; + m_funcs->glDrawBuffers(n, drawBufs.constData()); +} + +void GraphicsHelperGL3_2::bindFragDataLocation(GLuint shader, const QHash &outputs) +{ + for (auto it = outputs.begin(), end = outputs.end(); it != end; ++it) + m_funcs->glBindFragDataLocation(shader, it.value(), it.key().toStdString().c_str()); +} + +void GraphicsHelperGL3_2::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + m_funcs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); +} + +void GraphicsHelperGL3_2::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) +{ + Q_UNUSED(programId); + Q_UNUSED(shaderStorageBlockIndex); + Q_UNUSED(shaderStorageBlockBinding); + qWarning() << "SSBO are not supported by OpenGL 3.0 (since OpenGL 4.3)"; +} + +void GraphicsHelperGL3_2::bindBufferBase(GLenum target, GLuint index, GLuint buffer) +{ + m_funcs->glBindBufferBase(target, index, buffer); +} + +void GraphicsHelperGL3_2::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + char *bufferData = buffer.data(); + + switch (description.m_type) { + + case GL_FLOAT: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_FLOAT_VEC2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_FLOAT_VEC3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_FLOAT_VEC4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_FLOAT_MAT2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); + break; + } + + case GL_FLOAT_MAT2x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); + break; + } + + case GL_FLOAT_MAT2x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); + break; + } + + case GL_FLOAT_MAT3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); + break; + } + + case GL_FLOAT_MAT3x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); + break; + } + + case GL_FLOAT_MAT3x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); + break; + } + + case GL_FLOAT_MAT4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); + break; + } + + case GL_FLOAT_MAT4x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); + break; + } + + case GL_FLOAT_MAT4x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); + break; + } + + case GL_INT: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_INT_VEC2: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_INT_VEC3: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_INT_VEC4: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_UNSIGNED_INT: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_UNSIGNED_INT_VEC2: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_UNSIGNED_INT_VEC3: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_UNSIGNED_INT_VEC4: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_BOOL: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_BOOL_VEC2: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_BOOL_VEC3: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_BOOL_VEC4: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_2D_RECT: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_2D_RECT: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_2D_RECT: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_1D_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: { + Q_ASSERT(description.m_size == 1); + int value = v.toInt(); + QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); + break; + } + + default: + qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; + break; + } +} + +uint GraphicsHelperGL3_2::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + int arrayStride = qMax(description.m_arrayStride, 0); + int matrixStride = qMax(description.m_matrixStride, 0); + + switch (description.m_type) { + + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + case GL_UNSIGNED_INT_VEC2: + rawByteSize = 8; + break; + + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + case GL_UNSIGNED_INT_VEC3: + rawByteSize = 12; + break; + + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + case GL_UNSIGNED_INT_VEC4: + rawByteSize = 16; + break; + + case GL_FLOAT_MAT2: + rawByteSize = matrixStride ? 2 * matrixStride : 16; + break; + + case GL_FLOAT_MAT2x4: + rawByteSize = matrixStride ? 2 * matrixStride : 32; + break; + + case GL_FLOAT_MAT4x2: + rawByteSize = matrixStride ? 4 * matrixStride : 32; + break; + + case GL_FLOAT_MAT3: + rawByteSize = matrixStride ? 3 * matrixStride : 36; + break; + + case GL_FLOAT_MAT2x3: + rawByteSize = matrixStride ? 2 * matrixStride : 24; + break; + + case GL_FLOAT_MAT3x2: + rawByteSize = matrixStride ? 3 * matrixStride : 24; + break; + + case GL_FLOAT_MAT4: + rawByteSize = matrixStride ? 4 * matrixStride : 64; + break; + + case GL_FLOAT_MAT4x3: + rawByteSize = matrixStride ? 4 * matrixStride : 48; + break; + + case GL_FLOAT_MAT3x4: + rawByteSize = matrixStride ? 3 * matrixStride : 48; + break; + + case GL_BOOL: + rawByteSize = 1; + break; + + case GL_BOOL_VEC2: + rawByteSize = 2; + break; + + case GL_BOOL_VEC3: + rawByteSize = 3; + break; + + case GL_BOOL_VEC4: + rawByteSize = 4; + break; + + case GL_INT: + case GL_FLOAT: + case GL_UNSIGNED_INT: + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_2D_RECT: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_2D_RECT: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_2D_RECT: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_1D_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + rawByteSize = 4; + break; + } + + return arrayStride ? rawByteSize * arrayStride : rawByteSize; +} + +void GraphicsHelperGL3_2::enableClipPlane(int clipPlane) +{ + m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL3_2::disableClipPlane(int clipPlane) +{ + m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL3_2::setClipPlane(int clipPlane, const QVector3D &normal, float distance) +{ + // deprecated + Q_UNUSED(clipPlane); + Q_UNUSED(normal); + Q_UNUSED(distance); +} + +GLint GraphicsHelperGL3_2::maxClipPlaneCount() +{ + GLint max = 0; + m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); + return max; +} + +void GraphicsHelperGL3_2::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + Q_UNUSED(barriers); + qWarning() << "memory barrier is not supported by OpenGL 3.0 (since 4.3)"; +} + +void GraphicsHelperGL3_2::enablePrimitiveRestart(int primitiveRestartIndex) +{ + m_funcs->glPrimitiveRestartIndex(primitiveRestartIndex); + m_funcs->glEnable(GL_PRIMITIVE_RESTART); +} + +void GraphicsHelperGL3_2::enableVertexAttributeArray(int location) +{ + m_funcs->glEnableVertexAttribArray(location); +} + +void GraphicsHelperGL3_2::disablePrimitiveRestart() +{ + m_funcs->glDisable(GL_PRIMITIVE_RESTART); +} + +void GraphicsHelperGL3_2::clearBufferf(GLint drawbuffer, const QVector4D &values) +{ + GLfloat vec[4] = {values[0], values[1], values[2], values[3]}; + m_funcs->glClearBufferfv(GL_COLOR, drawbuffer, vec); +} + +void GraphicsHelperGL3_2::pointSize(bool programmable, GLfloat value) +{ + if (programmable) { + m_funcs->glEnable(GL_PROGRAM_POINT_SIZE); + } else { + m_funcs->glDisable(GL_PROGRAM_POINT_SIZE); + m_funcs->glPointSize(value); + } +} + +void GraphicsHelperGL3_2::enablei(GLenum cap, GLuint index) +{ + m_funcs->glEnablei(cap, index); +} + +void GraphicsHelperGL3_2::disablei(GLenum cap, GLuint index) +{ + m_funcs->glDisablei(cap, index); +} + +void GraphicsHelperGL3_2::setSeamlessCubemap(bool enable) +{ + if (enable) + m_funcs->glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + else + m_funcs->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); +} + +QSize GraphicsHelperGL3_2::getRenderBufferDimensions(GLuint renderBufferId) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); + + return QSize(width, height); +} + +QSize GraphicsHelperGL3_2::getTextureDimensions(GLuint textureId, GLenum target, uint level) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindTexture(target, textureId); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); + m_funcs->glBindTexture(target, 0); + + return QSize(width, height); +} + +void GraphicsHelperGL3_2::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) +{ + Q_UNUSED(wx); + Q_UNUSED(wy); + Q_UNUSED(wz); + qWarning() << "Compute Shaders are not supported by OpenGL 3.2 (since OpenGL 4.3)"; +} + +char *GraphicsHelperGL3_2::mapBuffer(GLenum target, GLsizeiptr size) +{ + return static_cast(m_funcs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); +} + +GLboolean GraphicsHelperGL3_2::unmapBuffer(GLenum target) +{ + return m_funcs->glUnmapBuffer(target); +} + +void GraphicsHelperGL3_2::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform1fv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform2fv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform3fv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform4fv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform1iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform1iv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform2iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform2iv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform3iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform3iv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform4iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform4iv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform1uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform1uiv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform2uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform2uiv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform3uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform3uiv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniform4uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform4uiv(location, count, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2x3fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3x2fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2x4fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4x2fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3x4fv(location, count, false, values); +} + +void GraphicsHelperGL3_2::glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4x3fv(location, count, false, values); +} + +UniformType GraphicsHelperGL3_2::uniformTypeFromGLType(GLenum type) +{ + switch (type) { + case GL_FLOAT: + return UniformType::Float; + case GL_FLOAT_VEC2: + return UniformType::Vec2; + case GL_FLOAT_VEC3: + return UniformType::Vec3; + case GL_FLOAT_VEC4: + return UniformType::Vec4; + case GL_FLOAT_MAT2: + return UniformType::Mat2; + case GL_FLOAT_MAT3: + return UniformType::Mat3; + case GL_FLOAT_MAT4: + return UniformType::Mat4; + case GL_FLOAT_MAT2x3: + return UniformType::Mat2x3; + case GL_FLOAT_MAT3x2: + return UniformType::Mat3x2; + case GL_FLOAT_MAT2x4: + return UniformType::Mat2x4; + case GL_FLOAT_MAT4x2: + return UniformType::Mat4x2; + case GL_FLOAT_MAT3x4: + return UniformType::Mat3x4; + case GL_FLOAT_MAT4x3: + return UniformType::Mat4x3; + case GL_INT: + return UniformType::Int; + case GL_INT_VEC2: + return UniformType::IVec2; + case GL_INT_VEC3: + return UniformType::IVec3; + case GL_INT_VEC4: + return UniformType::IVec4; + case GL_UNSIGNED_INT: + return UniformType::UInt; + case GL_UNSIGNED_INT_VEC2: + return UniformType::UIVec2; + case GL_UNSIGNED_INT_VEC3: + return UniformType::UIVec3; + case GL_UNSIGNED_INT_VEC4: + return UniformType::UIVec4; + case GL_BOOL: + return UniformType::Bool; + case GL_BOOL_VEC2: + return UniformType::BVec2; + case GL_BOOL_VEC3: + return UniformType::BVec3; + case GL_BOOL_VEC4: + return UniformType::BVec4; + + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_1D: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D: + case GL_SAMPLER_2D_RECT: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_SAMPLER_3D: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + return UniformType::Sampler; + default: + Q_UNREACHABLE(); + return UniformType::Float; + } +} + +void GraphicsHelperGL3_2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) +{ + m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h new file mode 100644 index 000000000..b6b2f7141 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h @@ -0,0 +1,185 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#ifndef QT_OPENGL_ES_2 + +QT_BEGIN_NAMESPACE + +class QOpenGLFunctions_3_2_Core; +class QOpenGLExtension_ARB_tessellation_shader; + +namespace Qt3DRender { +namespace Render { + +class Q_AUTOTEST_EXPORT GraphicsHelperGL3_2 : public GraphicsHelperInterface +{ +public: + GraphicsHelperGL3_2(); + ~GraphicsHelperGL3_2(); + + // QGraphicHelperInterface interface + void alphaTest(GLenum mode1, GLenum mode2) override; + void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; + void bindFragDataLocation(GLuint shader, const QHash &outputs) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; + void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; + void blendEquation(GLenum mode) override; + void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; + void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; + void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; + GLuint boundFrameBufferObject() override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; + bool checkFrameBufferComplete() override; + void clearBufferf(GLint drawbuffer, const QVector4D &values) override; + GLuint createFrameBufferObject() override; + void depthMask(GLenum mode) override; + void depthRange(GLdouble nearValue, GLdouble farValue) override; + void depthTest(GLenum mode) override; + void disableClipPlane(int clipPlane) override; + void disablei(GLenum cap, GLuint index) override; + void disablePrimitiveRestart() override; + void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; + char *mapBuffer(GLenum target, GLsizeiptr size) override; + GLboolean unmapBuffer(GLenum target) override; + void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; + void drawArraysIndirect(GLenum mode,void *indirect) override; + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; + void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; + void drawBuffers(GLsizei n, const int *bufs) override; + void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + void enableClipPlane(int clipPlane) override; + void enablei(GLenum cap, GLuint index) override; + void enablePrimitiveRestart(int primitiveRestartIndex) override; + void enableVertexAttributeArray(int location) override; + void frontFace(GLenum mode) override; + QSize getRenderBufferDimensions(GLuint renderBufferId) override; + QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; + void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; + void pointSize(bool programmable, GLfloat value) override; + GLint maxClipPlaneCount() override; + void memoryBarrier(QMemoryBarrier::Operations barriers) override; + QVector programUniformBlocks(GLuint programId) override; + QVector programAttributesAndLocations(GLuint programId) override; + QVector programUniformsAndLocations(GLuint programId) override; + QVector programShaderStorageBlocks(GLuint programId) override; + void releaseFrameBufferObject(GLuint frameBufferId) override; + void setMSAAEnabled(bool enable) override; + void setAlphaCoverageEnabled(bool enable) override; + void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; + void setSeamlessCubemap(bool enable) override; + void setVerticesPerPatch(GLint verticesPerPatch) override; + bool supportsFeature(Feature feature) const override; + uint uniformByteSize(const ShaderUniform &description) override; + void useProgram(GLuint programId) override; + void vertexAttribDivisor(GLuint index, GLuint divisor) override; + void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; + void readBuffer(GLenum mode) override; + void drawBuffer(GLenum mode) override; + void rasterMode(GLenum faceMode, GLenum rasterMode) override; + + void *fenceSync() override; + void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; + void waitSync(void *sync) override; + bool wasSyncSignaled(void *sync) override; + void deleteSync(void *sync) override; + + void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; + + void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; + + void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; + + void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; + + UniformType uniformTypeFromGLType(GLenum glType) override; + +private: + QOpenGLFunctions_3_2_Core *m_funcs; + QScopedPointer m_tessFuncs; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp new file mode 100644 index 000000000..3d8e2acfc --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp @@ -0,0 +1,1240 @@ +/**************************************************************************** +** +** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelpergl3_3_p.h" + +#ifndef QT_OPENGL_ES_2 +#include +#include +#include +#include +#include + +# ifndef QT_OPENGL_3_2 +# define GL_PATCH_VERTICES 36466 +# define GL_ACTIVE_RESOURCES 0x92F5 +# define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +# define GL_BUFFER_BINDING 0x9302 +# define GL_BUFFER_DATA_SIZE 0x9303 +# define GL_NUM_ACTIVE_VARIABLES 0x9304 +# define GL_SHADER_STORAGE_BLOCK 0x92E6 +# define GL_UNIFORM 0x92E1 +# define GL_UNIFORM_BLOCK 0x92E2 +# define GL_UNIFORM_BLOCK_INDEX 0x8A3A +# define GL_UNIFORM_OFFSET 0x8A3B +# define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +# define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +# define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +# define GL_UNIFORM_BLOCK_BINDING 0x8A3F +# define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +# endif + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +GraphicsHelperGL3_3::GraphicsHelperGL3_3() + : m_funcs(nullptr) + , m_tessFuncs() +{ +} + +GraphicsHelperGL3_3::~GraphicsHelperGL3_3() +{ +} + +void GraphicsHelperGL3_3::initializeHelper(QOpenGLContext *context, + QAbstractOpenGLFunctions *functions) +{ + m_funcs = static_cast(functions); + const bool ok = m_funcs->initializeOpenGLFunctions(); + Q_ASSERT(ok); + Q_UNUSED(ok); + + if (context->hasExtension(QByteArrayLiteral("GL_ARB_tessellation_shader"))) { + m_tessFuncs.reset(new QOpenGLExtension_ARB_tessellation_shader); + m_tessFuncs->initializeOpenGLFunctions(); + } +} + +void GraphicsHelperGL3_3::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL 3"; + + // glDrawElements OpenGL 3.1 or greater + m_funcs->glDrawElementsInstancedBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + instances, + baseVertex); +} + +void GraphicsHelperGL3_3::drawArraysInstanced(GLenum primitiveType, + GLint first, + GLsizei count, + GLsizei instances) +{ + // glDrawArraysInstanced OpenGL 3.1 or greater + m_funcs->glDrawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsHelperGL3_3::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL 3"; + m_funcs->glDrawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsHelperGL3_3::drawElements(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLint baseVertex) +{ + m_funcs->glDrawElementsBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + baseVertex); +} + +void GraphicsHelperGL3_3::drawElementsIndirect(GLenum, GLenum, void *) +{ + qWarning() << "Indirect Drawing is not supported with OpenGL 3"; +} + +void GraphicsHelperGL3_3::drawArrays(GLenum primitiveType, + GLint first, + GLsizei count) +{ + m_funcs->glDrawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperGL3_3::drawArraysIndirect(GLenum , void *) +{ + qWarning() << "Indirect Drawing is not supported with OpenGL 3"; +} + +void GraphicsHelperGL3_3::setVerticesPerPatch(GLint verticesPerPatch) +{ +#if defined(QT_OPENGL_4) + if (!m_tessFuncs) { + qWarning() << "Tessellation not supported with OpenGL 3 without GL_ARB_tessellation_shader"; + return; + } + + m_tessFuncs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); +#else + Q_UNUSED(verticesPerPatch); + qWarning() << "Tessellation not supported"; +#endif +} + +void GraphicsHelperGL3_3::useProgram(GLuint programId) +{ + m_funcs->glUseProgram(programId); +} + +QVector GraphicsHelperGL3_3::programUniformsAndLocations(GLuint programId) +{ + QVector uniforms; + + GLint nbrActiveUniforms = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); + uniforms.reserve(nbrActiveUniforms); + char uniformName[256]; + for (GLint i = 0; i < nbrActiveUniforms; i++) { + ShaderUniform uniform; + GLsizei uniformNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, + &uniform.m_size, &uniform.m_type, uniformName); + uniformName[sizeof(uniformName) - 1] = '\0'; + uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); + uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); + // Work around for uniform array names that aren't returned with [0] by some drivers + if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) + uniform.m_name.append(QLatin1String("[0]")); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); + uniform.m_rawByteSize = uniformByteSize(uniform); + uniforms.append(uniform); + qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; + } + + return uniforms; +} + +QVector GraphicsHelperGL3_3::programAttributesAndLocations(GLuint programId) +{ + QVector attributes; + GLint nbrActiveAttributes = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); + attributes.reserve(nbrActiveAttributes); + char attributeName[256]; + for (GLint i = 0; i < nbrActiveAttributes; i++) { + ShaderAttribute attribute; + GLsizei attributeNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, + &attribute.m_size, &attribute.m_type, attributeName); + attributeName[sizeof(attributeName) - 1] = '\0'; + attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); + attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); + attributes.append(attribute); + } + return attributes; +} + +QVector GraphicsHelperGL3_3::programUniformBlocks(GLuint programId) +{ + QVector blocks; + GLint nbrActiveUniformsBlocks = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORM_BLOCKS, &nbrActiveUniformsBlocks); + blocks.reserve(nbrActiveUniformsBlocks); + for (GLint i = 0; i < nbrActiveUniformsBlocks; i++) { + QByteArray uniformBlockName(256, '\0'); + GLsizei length = 0; + ShaderUniformBlock uniformBlock; + m_funcs->glGetActiveUniformBlockName(programId, i, 256, &length, uniformBlockName.data()); + uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); + uniformBlock.m_index = i; + m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &uniformBlock.m_activeUniformsCount); + m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_BINDING, &uniformBlock.m_binding); + m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.m_size); + blocks.append(uniformBlock); + } + return blocks; +} + +QVector GraphicsHelperGL3_3::programShaderStorageBlocks(GLuint programId) +{ + Q_UNUSED(programId); + QVector blocks; + qWarning() << "SSBO are not supported by OpenGL 3.3 (since OpenGL 4.3)"; + return blocks; +} + +void GraphicsHelperGL3_3::vertexAttribDivisor(GLuint index, GLuint divisor) +{ + m_funcs->glVertexAttribDivisor(index, divisor); +} + +void GraphicsHelperGL3_3::vertexAttributePointer(GLenum shaderDataType, + GLuint index, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + const GLvoid *pointer) +{ + switch (shaderDataType) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + case GL_FLOAT_MAT2: + case GL_FLOAT_MAT2x3: + case GL_FLOAT_MAT2x4: + case GL_FLOAT_MAT3: + case GL_FLOAT_MAT3x2: + case GL_FLOAT_MAT3x4: + case GL_FLOAT_MAT4x2: + case GL_FLOAT_MAT4x3: + case GL_FLOAT_MAT4: + m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); + break; + + case GL_INT: + case GL_INT_VEC2: + case GL_INT_VEC3: + case GL_INT_VEC4: + case GL_UNSIGNED_INT: + case GL_UNSIGNED_INT_VEC2: + case GL_UNSIGNED_INT_VEC3: + case GL_UNSIGNED_INT_VEC4: + m_funcs->glVertexAttribIPointer(index, size, type, stride, pointer); + break; + + default: + qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + } +} + +void GraphicsHelperGL3_3::readBuffer(GLenum mode) +{ + m_funcs->glReadBuffer(mode); +} + +void GraphicsHelperGL3_3::drawBuffer(GLenum mode) +{ + m_funcs->glDrawBuffer(mode); +} + +void *GraphicsHelperGL3_3::fenceSync() +{ + return m_funcs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); +} + +void GraphicsHelperGL3_3::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) +{ + m_funcs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); +} + +void GraphicsHelperGL3_3::waitSync(void *sync) +{ + m_funcs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); +} + +bool GraphicsHelperGL3_3::wasSyncSignaled(void *sync) +{ + GLint v; + m_funcs->glGetSynciv(static_cast(sync), + GL_SYNC_STATUS, + sizeof(v), + nullptr, + &v); + return v == GL_SIGNALED; +} + +void GraphicsHelperGL3_3::deleteSync(void *sync) +{ + m_funcs->glDeleteSync(static_cast(sync)); +} + +void GraphicsHelperGL3_3::rasterMode(GLenum faceMode, GLenum rasterMode) +{ + m_funcs->glPolygonMode(faceMode, rasterMode); +} + +void GraphicsHelperGL3_3::blendEquation(GLenum mode) +{ + m_funcs->glBlendEquation(mode); +} + +void GraphicsHelperGL3_3::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) +{ + Q_UNUSED(buf); + Q_UNUSED(sfactor); + Q_UNUSED(dfactor); + + qWarning() << "glBlendFunci() not supported by OpenGL 3.3 (since OpenGL 4.0)"; +} + +void GraphicsHelperGL3_3::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) +{ + Q_UNUSED(buf); + Q_UNUSED(sRGB); + Q_UNUSED(dRGB); + Q_UNUSED(sAlpha); + Q_UNUSED(dAlpha); + + qWarning() << "glBlendFuncSeparatei() not supported by OpenGL 3.3 (since OpenGL 4.0)"; +} + +void GraphicsHelperGL3_3::alphaTest(GLenum, GLenum) +{ + qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; +} + +void GraphicsHelperGL3_3::depthTest(GLenum mode) +{ + m_funcs->glEnable(GL_DEPTH_TEST); + m_funcs->glDepthFunc(mode); +} + +void GraphicsHelperGL3_3::depthMask(GLenum mode) +{ + m_funcs->glDepthMask(mode); +} + +void GraphicsHelperGL3_3::depthRange(GLdouble nearValue, GLdouble farValue) +{ + m_funcs->glDepthRange(nearValue, farValue); +} + +void GraphicsHelperGL3_3::frontFace(GLenum mode) +{ + m_funcs->glFrontFace(mode); + +} + +void GraphicsHelperGL3_3::setMSAAEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_MULTISAMPLE) + : m_funcs->glDisable(GL_MULTISAMPLE); +} + +void GraphicsHelperGL3_3::setAlphaCoverageEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) + : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); +} + +GLuint GraphicsHelperGL3_3::createFrameBufferObject() +{ + GLuint id; + m_funcs->glGenFramebuffers(1, &id); + return id; +} + +void GraphicsHelperGL3_3::releaseFrameBufferObject(GLuint frameBufferId) +{ + m_funcs->glDeleteFramebuffers(1, &frameBufferId); +} + +void GraphicsHelperGL3_3::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) +{ + switch (mode) { + case FBODraw: + m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); + return; + case FBORead: + m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); + return; + case FBOReadAndDraw: + default: + m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); + return; + } +} + +GLuint GraphicsHelperGL3_3::boundFrameBufferObject() +{ + GLint id = 0; + m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); + return id; +} + +bool GraphicsHelperGL3_3::checkFrameBufferComplete() +{ + return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); +} + +bool GraphicsHelperGL3_3::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + Q_UNUSED(attachment); + return false; +} + +void GraphicsHelperGL3_3::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; + + if (attachment.m_point <= QRenderTargetOutput::Color15) + attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + + texture->bind(); + QOpenGLTexture::Target target = texture->target(); + if (target == QOpenGLTexture::Target1DArray || target == QOpenGLTexture::Target2DArray || + target == QOpenGLTexture::Target2DMultisampleArray || target == QOpenGLTexture::Target3D) + m_funcs->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMapArray) + m_funcs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face != QAbstractTexture::AllFaces) + m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else + m_funcs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); + texture->release(); +} + +void GraphicsHelperGL3_3::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) +{ + Q_UNUSED(renderBuffer); + Q_UNUSED(attachment); + Q_UNREACHABLE(); +} + +bool GraphicsHelperGL3_3::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case MRT: + case UniformBufferObject: + case PrimitiveRestart: + case RenderBufferDimensionRetrieval: + case TextureDimensionRetrieval: + case BindableFragmentOutputs: + case BlitFramebuffer: + case Fences: + return true; + case Tessellation: + return !m_tessFuncs.isNull(); + default: + return false; + } +} + +void GraphicsHelperGL3_3::drawBuffers(GLsizei n, const int *bufs) +{ + // Use QVarLengthArray here + QVarLengthArray drawBufs(n); + + for (int i = 0; i < n; i++) + drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; + m_funcs->glDrawBuffers(n, drawBufs.constData()); +} + +void GraphicsHelperGL3_3::bindFragDataLocation(GLuint shader, const QHash &outputs) +{ + for (auto it = outputs.begin(), end = outputs.end(); it != end; ++it) + m_funcs->glBindFragDataLocation(shader, it.value(), it.key().toStdString().c_str()); +} + +void GraphicsHelperGL3_3::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + m_funcs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); +} + +void GraphicsHelperGL3_3::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) +{ + Q_UNUSED(programId); + Q_UNUSED(shaderStorageBlockIndex); + Q_UNUSED(shaderStorageBlockBinding); + qWarning() << "SSBO are not supported by OpenGL 3.3 (since OpenGL 4.3)"; +} + +void GraphicsHelperGL3_3::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + Q_UNUSED(imageUnit) + Q_UNUSED(texture) + Q_UNUSED(mipLevel) + Q_UNUSED(layered) + Q_UNUSED(layer) + Q_UNUSED(access) + Q_UNUSED(format) + qWarning() << "Shader Images are not supported by OpenGL 3.3 (since OpenGL 4.2)"; +} + +void GraphicsHelperGL3_3::bindBufferBase(GLenum target, GLuint index, GLuint buffer) +{ + m_funcs->glBindBufferBase(target, index, buffer); +} + +void GraphicsHelperGL3_3::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + char *bufferData = buffer.data(); + + switch (description.m_type) { + + case GL_FLOAT: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_FLOAT_VEC2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_FLOAT_VEC3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_FLOAT_VEC4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_FLOAT_MAT2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); + break; + } + + case GL_FLOAT_MAT2x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); + break; + } + + case GL_FLOAT_MAT2x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); + break; + } + + case GL_FLOAT_MAT3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); + break; + } + + case GL_FLOAT_MAT3x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); + break; + } + + case GL_FLOAT_MAT3x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); + break; + } + + case GL_FLOAT_MAT4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); + break; + } + + case GL_FLOAT_MAT4x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); + break; + } + + case GL_FLOAT_MAT4x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); + break; + } + + case GL_INT: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_INT_VEC2: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_INT_VEC3: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_INT_VEC4: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_UNSIGNED_INT: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_UNSIGNED_INT_VEC2: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_UNSIGNED_INT_VEC3: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_UNSIGNED_INT_VEC4: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_BOOL: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_BOOL_VEC2: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_BOOL_VEC3: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_BOOL_VEC4: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_2D_RECT: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_2D_RECT: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_2D_RECT: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_1D_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: { + Q_ASSERT(description.m_size == 1); + int value = v.toInt(); + QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); + break; + } + + default: + qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; + break; + } +} + +uint GraphicsHelperGL3_3::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + int arrayStride = qMax(description.m_arrayStride, 0); + int matrixStride = qMax(description.m_matrixStride, 0); + + switch (description.m_type) { + + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + case GL_UNSIGNED_INT_VEC2: + rawByteSize = 8; + break; + + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + case GL_UNSIGNED_INT_VEC3: + rawByteSize = 12; + break; + + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + case GL_UNSIGNED_INT_VEC4: + rawByteSize = 16; + break; + + case GL_FLOAT_MAT2: + rawByteSize = matrixStride ? 2 * matrixStride : 16; + break; + + case GL_FLOAT_MAT2x4: + rawByteSize = matrixStride ? 2 * matrixStride : 32; + break; + + case GL_FLOAT_MAT4x2: + rawByteSize = matrixStride ? 4 * matrixStride : 32; + break; + + case GL_FLOAT_MAT3: + rawByteSize = matrixStride ? 3 * matrixStride : 36; + break; + + case GL_FLOAT_MAT2x3: + rawByteSize = matrixStride ? 2 * matrixStride : 24; + break; + + case GL_FLOAT_MAT3x2: + rawByteSize = matrixStride ? 3 * matrixStride : 24; + break; + + case GL_FLOAT_MAT4: + rawByteSize = matrixStride ? 4 * matrixStride : 64; + break; + + case GL_FLOAT_MAT4x3: + rawByteSize = matrixStride ? 4 * matrixStride : 48; + break; + + case GL_FLOAT_MAT3x4: + rawByteSize = matrixStride ? 3 * matrixStride : 48; + break; + + case GL_BOOL: + rawByteSize = 1; + break; + + case GL_BOOL_VEC2: + rawByteSize = 2; + break; + + case GL_BOOL_VEC3: + rawByteSize = 3; + break; + + case GL_BOOL_VEC4: + rawByteSize = 4; + break; + + case GL_INT: + case GL_FLOAT: + case GL_UNSIGNED_INT: + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_2D_RECT: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_2D_RECT: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_2D_RECT: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_1D_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + rawByteSize = 4; + break; + } + + return arrayStride ? rawByteSize * arrayStride : rawByteSize; +} + +void GraphicsHelperGL3_3::enableClipPlane(int clipPlane) +{ + m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL3_3::disableClipPlane(int clipPlane) +{ + m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL3_3::setClipPlane(int clipPlane, const QVector3D &normal, float distance) +{ + // deprecated + Q_UNUSED(clipPlane); + Q_UNUSED(normal); + Q_UNUSED(distance); +} + +GLint GraphicsHelperGL3_3::maxClipPlaneCount() +{ + GLint max = 0; + m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); + return max; +} + +void GraphicsHelperGL3_3::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + Q_UNUSED(barriers); + qWarning() << "memory barrier is not supported by OpenGL 3.3 (since 4.3)"; +} + +void GraphicsHelperGL3_3::enablePrimitiveRestart(int primitiveRestartIndex) +{ + m_funcs->glPrimitiveRestartIndex(primitiveRestartIndex); + m_funcs->glEnable(GL_PRIMITIVE_RESTART); +} + +void GraphicsHelperGL3_3::enableVertexAttributeArray(int location) +{ + m_funcs->glEnableVertexAttribArray(location); +} + +void GraphicsHelperGL3_3::disablePrimitiveRestart() +{ + m_funcs->glDisable(GL_PRIMITIVE_RESTART); +} + +void GraphicsHelperGL3_3::clearBufferf(GLint drawbuffer, const QVector4D &values) +{ + GLfloat vec[4] = {values[0], values[1], values[2], values[3]}; + m_funcs->glClearBufferfv(GL_COLOR, drawbuffer, vec); +} + +void GraphicsHelperGL3_3::pointSize(bool programmable, GLfloat value) +{ + if (programmable) { + m_funcs->glEnable(GL_PROGRAM_POINT_SIZE); + } else { + m_funcs->glDisable(GL_PROGRAM_POINT_SIZE); + m_funcs->glPointSize(value); + } +} + +void GraphicsHelperGL3_3::enablei(GLenum cap, GLuint index) +{ + m_funcs->glEnablei(cap, index); +} + +void GraphicsHelperGL3_3::disablei(GLenum cap, GLuint index) +{ + m_funcs->glDisablei(cap, index); +} + +void GraphicsHelperGL3_3::setSeamlessCubemap(bool enable) +{ + if (enable) + m_funcs->glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + else + m_funcs->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); +} + +QSize GraphicsHelperGL3_3::getRenderBufferDimensions(GLuint renderBufferId) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); + + return QSize(width, height); +} + +QSize GraphicsHelperGL3_3::getTextureDimensions(GLuint textureId, GLenum target, uint level) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindTexture(target, textureId); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); + m_funcs->glBindTexture(target, 0); + + return QSize(width, height); +} + +void GraphicsHelperGL3_3::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) +{ + Q_UNUSED(wx); + Q_UNUSED(wy); + Q_UNUSED(wz); + qWarning() << "Compute Shaders are not supported by OpenGL 3.3 (since OpenGL 4.3)"; +} + +char *GraphicsHelperGL3_3::mapBuffer(GLenum target, GLsizeiptr size) +{ + return static_cast(m_funcs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); +} + +GLboolean GraphicsHelperGL3_3::unmapBuffer(GLenum target) +{ + return m_funcs->glUnmapBuffer(target); +} + +void GraphicsHelperGL3_3::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform1fv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform2fv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform3fv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform4fv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform1iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform1iv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform2iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform2iv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform3iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform3iv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform4iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform4iv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform1uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform1uiv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform2uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform2uiv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform3uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform3uiv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniform4uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform4uiv(location, count, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2x3fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3x2fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2x4fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4x2fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3x4fv(location, count, false, values); +} + +void GraphicsHelperGL3_3::glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4x3fv(location, count, false, values); +} + +UniformType GraphicsHelperGL3_3::uniformTypeFromGLType(GLenum type) +{ + switch (type) { + case GL_FLOAT: + return UniformType::Float; + case GL_FLOAT_VEC2: + return UniformType::Vec2; + case GL_FLOAT_VEC3: + return UniformType::Vec3; + case GL_FLOAT_VEC4: + return UniformType::Vec4; + case GL_FLOAT_MAT2: + return UniformType::Mat2; + case GL_FLOAT_MAT3: + return UniformType::Mat3; + case GL_FLOAT_MAT4: + return UniformType::Mat4; + case GL_FLOAT_MAT2x3: + return UniformType::Mat2x3; + case GL_FLOAT_MAT3x2: + return UniformType::Mat3x2; + case GL_FLOAT_MAT2x4: + return UniformType::Mat2x4; + case GL_FLOAT_MAT4x2: + return UniformType::Mat4x2; + case GL_FLOAT_MAT3x4: + return UniformType::Mat3x4; + case GL_FLOAT_MAT4x3: + return UniformType::Mat4x3; + case GL_INT: + return UniformType::Int; + case GL_INT_VEC2: + return UniformType::IVec2; + case GL_INT_VEC3: + return UniformType::IVec3; + case GL_INT_VEC4: + return UniformType::IVec4; + case GL_UNSIGNED_INT: + return UniformType::UInt; + case GL_UNSIGNED_INT_VEC2: + return UniformType::UIVec2; + case GL_UNSIGNED_INT_VEC3: + return UniformType::UIVec3; + case GL_UNSIGNED_INT_VEC4: + return UniformType::UIVec4; + case GL_BOOL: + return UniformType::Bool; + case GL_BOOL_VEC2: + return UniformType::BVec2; + case GL_BOOL_VEC3: + return UniformType::BVec3; + case GL_BOOL_VEC4: + return UniformType::BVec4; + + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_1D: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D: + case GL_SAMPLER_2D_RECT: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_2D_ARRAY: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_SAMPLER_3D: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + return UniformType::Sampler; + default: + Q_UNREACHABLE(); + return UniformType::Float; + } +} + +void GraphicsHelperGL3_3::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) +{ + m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h new file mode 100644 index 000000000..8d8525111 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h @@ -0,0 +1,185 @@ +/**************************************************************************** +** +** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#ifndef QT_OPENGL_ES_2 + +QT_BEGIN_NAMESPACE + +class QOpenGLFunctions_3_3_Core; +class QOpenGLExtension_ARB_tessellation_shader; + +namespace Qt3DRender { +namespace Render { + +class Q_AUTOTEST_EXPORT GraphicsHelperGL3_3 : public GraphicsHelperInterface +{ +public: + GraphicsHelperGL3_3(); + ~GraphicsHelperGL3_3(); + + // QGraphicHelperInterface interface + void alphaTest(GLenum mode1, GLenum mode2) override; + void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; + void bindFragDataLocation(GLuint shader, const QHash &outputs) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; + void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; + void blendEquation(GLenum mode) override; + void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; + void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; + void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; + GLuint boundFrameBufferObject() override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; + bool checkFrameBufferComplete() override; + void clearBufferf(GLint drawbuffer, const QVector4D &values) override; + GLuint createFrameBufferObject() override; + void depthMask(GLenum mode) override; + void depthRange(GLdouble nearValue, GLdouble farValue) override; + void depthTest(GLenum mode) override; + void disableClipPlane(int clipPlane) override; + void disablei(GLenum cap, GLuint index) override; + void disablePrimitiveRestart() override; + void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; + char *mapBuffer(GLenum target, GLsizeiptr size) override; + GLboolean unmapBuffer(GLenum target) override; + void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; + void drawArraysIndirect(GLenum mode,void *indirect) override; + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; + void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; + void drawBuffers(GLsizei n, const int *bufs) override; + void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + void enableClipPlane(int clipPlane) override; + void enablei(GLenum cap, GLuint index) override; + void enablePrimitiveRestart(int primitiveRestartIndex) override; + void enableVertexAttributeArray(int location) override; + void frontFace(GLenum mode) override; + QSize getRenderBufferDimensions(GLuint renderBufferId) override; + QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; + void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; + void pointSize(bool programmable, GLfloat value) override; + GLint maxClipPlaneCount() override; + void memoryBarrier(QMemoryBarrier::Operations barriers) override; + QVector programUniformBlocks(GLuint programId) override; + QVector programAttributesAndLocations(GLuint programId) override; + QVector programUniformsAndLocations(GLuint programId) override; + QVector programShaderStorageBlocks(GLuint programId) override; + void releaseFrameBufferObject(GLuint frameBufferId) override; + void setMSAAEnabled(bool enable) override; + void setAlphaCoverageEnabled(bool enable) override; + void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; + void setSeamlessCubemap(bool enable) override; + void setVerticesPerPatch(GLint verticesPerPatch) override; + bool supportsFeature(Feature feature) const override; + uint uniformByteSize(const ShaderUniform &description) override; + void useProgram(GLuint programId) override; + void vertexAttribDivisor(GLuint index, GLuint divisor) override; + void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; + void readBuffer(GLenum mode) override; + void drawBuffer(GLenum mode) override; + void rasterMode(GLenum faceMode, GLenum rasterMode) override; + + void *fenceSync() override; + void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; + void waitSync(void *sync) override; + bool wasSyncSignaled(void *sync) override; + void deleteSync(void *sync) override; + + void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; + + void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; + + void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; + + void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; + + UniformType uniformTypeFromGLType(GLenum glType) override; + +private: + QOpenGLFunctions_3_3_Core *m_funcs; + QScopedPointer m_tessFuncs; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp new file mode 100644 index 000000000..775dd7935 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp @@ -0,0 +1,1442 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicshelpergl4_p.h" + +#ifndef QT_OPENGL_ES_2 +#include +#include +#include +#include +#include + +# ifndef QT_OPENGL_4_3 +# ifndef GL_PATCH_VERTICES +# define GL_PATCH_VERTICES 36466 +# endif +# define GL_ACTIVE_RESOURCES 0x92F5 +# define GL_BUFFER_BINDING 0x9302 +# define GL_BUFFER_DATA_SIZE 0x9303 +# define GL_NUM_ACTIVE_VARIABLES 0x9304 +# define GL_SHADER_STORAGE_BLOCK 0x92E6 +# define GL_UNIFORM 0x92E1 +# define GL_UNIFORM_BLOCK 0x92E2 +# define GL_UNIFORM_BLOCK_INDEX 0x8A3A +# define GL_UNIFORM_OFFSET 0x8A3B +# define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +# define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +# define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +# define GL_UNIFORM_BLOCK_BINDING 0x8A3F +# define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +# define GL_ALL_BARRIER_BITS 0xFFFFFFFF +# define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 +# define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 +# define GL_UNIFORM_BARRIER_BIT 0x00000004 +# define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 +# define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 +# define GL_COMMAND_BARRIER_BIT 0x00000040 +# define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 +# define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 +# define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 +# define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 +# define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 +# define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 +# define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +# define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 +# define GL_IMAGE_1D 0x904C +# define GL_IMAGE_2D 0x904D +# define GL_IMAGE_3D 0x904E +# define GL_IMAGE_2D_RECT 0x904F +# define GL_IMAGE_CUBE 0x9050 +# define GL_IMAGE_BUFFER 0x9051 +# define GL_IMAGE_1D_ARRAY 0x9052 +# define GL_IMAGE_2D_ARRAY 0x9053 +# define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +# define GL_IMAGE_2D_MULTISAMPLE 0x9055 +# define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 +# define GL_INT_IMAGE_1D 0x9057 +# define GL_INT_IMAGE_2D 0x9058 +# define GL_INT_IMAGE_3D 0x9059 +# define GL_INT_IMAGE_2D_RECT 0x905A +# define GL_INT_IMAGE_CUBE 0x905B +# define GL_INT_IMAGE_BUFFER 0x905C +# define GL_INT_IMAGE_1D_ARRAY 0x905D +# define GL_INT_IMAGE_2D_ARRAY 0x905E +# define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +# define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 +# define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 +# define GL_UNSIGNED_INT_IMAGE_1D 0x9062 +# define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +# define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +# define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 +# define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +# define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +# define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 +# define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +# define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +# define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B +# define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C +# endif + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +namespace { + +GLbitfield memoryBarrierGLBitfield(QMemoryBarrier::Operations barriers) +{ + GLbitfield bits = 0; + + if (barriers.testFlag(QMemoryBarrier::All)) { + bits |= GL_ALL_BARRIER_BITS; + return bits; + } + + if (barriers.testFlag(QMemoryBarrier::VertexAttributeArray)) + bits |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::ElementArray)) + bits |= GL_ELEMENT_ARRAY_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::Uniform)) + bits |= GL_UNIFORM_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::TextureFetch)) + bits |= GL_TEXTURE_FETCH_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::ShaderImageAccess)) + bits |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::Command)) + bits |= GL_COMMAND_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::PixelBuffer)) + bits |= GL_PIXEL_BUFFER_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::TextureUpdate)) + bits |= GL_TEXTURE_UPDATE_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::BufferUpdate)) + bits |= GL_BUFFER_UPDATE_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::FrameBuffer)) + bits |= GL_FRAMEBUFFER_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::TransformFeedback)) + bits |= GL_TRANSFORM_FEEDBACK_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::AtomicCounter)) + bits |= GL_ATOMIC_COUNTER_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::ShaderStorage)) + bits |= GL_SHADER_STORAGE_BARRIER_BIT; + if (barriers.testFlag(QMemoryBarrier::QueryBuffer)) + bits |= GL_QUERY_BUFFER_BARRIER_BIT; + + return bits; +} + +} + +GraphicsHelperGL4::GraphicsHelperGL4() + : m_funcs(nullptr) +{ +} + +void GraphicsHelperGL4::initializeHelper(QOpenGLContext *context, + QAbstractOpenGLFunctions *functions) +{ + Q_UNUSED(context); + m_funcs = static_cast(functions); + const bool ok = m_funcs->initializeOpenGLFunctions(); + Q_ASSERT(ok); + Q_UNUSED(ok); +} + +void GraphicsHelperGL4::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLsizei instances, + GLint baseVertex, + GLint baseInstance) +{ + if (baseInstance != 0) + qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; + + // glDrawElements OpenGL 3.1 or greater + m_funcs->glDrawElementsInstancedBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + instances, + baseVertex); +} + +void GraphicsHelperGL4::drawArraysInstanced(GLenum primitiveType, + GLint first, + GLsizei count, + GLsizei instances) +{ + // glDrawArraysInstanced OpenGL 3.1 or greater + m_funcs->glDrawArraysInstanced(primitiveType, + first, + count, + instances); +} + +void GraphicsHelperGL4::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) +{ + m_funcs->glDrawArraysInstancedBaseInstance(primitiveType, + first, + count, + instances, + baseInstance); +} + +void GraphicsHelperGL4::drawElements(GLenum primitiveType, + GLsizei primitiveCount, + GLint indexType, + void *indices, + GLint baseVertex) +{ + m_funcs->glDrawElementsBaseVertex(primitiveType, + primitiveCount, + indexType, + indices, + baseVertex); +} + +void GraphicsHelperGL4::drawElementsIndirect(GLenum mode, + GLenum type, + void *indirect) +{ + m_funcs->glDrawElementsIndirect(mode, type, indirect); +} + +void GraphicsHelperGL4::drawArrays(GLenum primitiveType, + GLint first, + GLsizei count) +{ + m_funcs->glDrawArrays(primitiveType, + first, + count); +} + +void GraphicsHelperGL4::drawArraysIndirect(GLenum mode, void *indirect) +{ + m_funcs->glDrawArraysIndirect(mode, indirect); +} + +void GraphicsHelperGL4::setVerticesPerPatch(GLint verticesPerPatch) +{ + m_funcs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); +} + +void GraphicsHelperGL4::useProgram(GLuint programId) +{ + m_funcs->glUseProgram(programId); +} + +QVector GraphicsHelperGL4::programUniformsAndLocations(GLuint programId) +{ + QVector uniforms; + + GLint nbrActiveUniforms = 0; + m_funcs->glGetProgramInterfaceiv(programId, GL_UNIFORM, GL_ACTIVE_RESOURCES, &nbrActiveUniforms); + uniforms.reserve(nbrActiveUniforms); + char uniformName[256]; + for (GLint i = 0; i < nbrActiveUniforms; ++i) { + ShaderUniform uniform; + GLsizei uniformNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, + &uniform.m_size, &uniform.m_type, uniformName); + uniformName[sizeof(uniformName) - 1] = '\0'; + uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); + uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); + // Work around for uniform array names that aren't returned with [0] by some drivers + if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) + uniform.m_name.append(QLatin1String("[0]")); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); + m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); + uniform.m_rawByteSize = uniformByteSize(uniform); + uniforms.append(uniform); + qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; + } + + return uniforms; +} + +QVector GraphicsHelperGL4::programAttributesAndLocations(GLuint programId) +{ + QVector attributes; + GLint nbrActiveAttributes = 0; + m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); + attributes.reserve(nbrActiveAttributes); + char attributeName[256]; + for (GLint i = 0; i < nbrActiveAttributes; ++i) { + ShaderAttribute attribute; + GLsizei attributeNameLength = 0; + // Size is 1 for scalar and more for struct or arrays + // Type is the GL Type + m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, + &attribute.m_size, &attribute.m_type, attributeName); + attributeName[sizeof(attributeName) - 1] = '\0'; + attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); + attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); + attributes.append(attribute); + } + return attributes; +} + +QVector GraphicsHelperGL4::programUniformBlocks(GLuint programId) +{ + QVector blocks; + GLint nbrActiveUniformsBlocks = 0; + m_funcs->glGetProgramInterfaceiv(programId, GL_UNIFORM_BLOCK, GL_ACTIVE_RESOURCES, &nbrActiveUniformsBlocks); + blocks.reserve(nbrActiveUniformsBlocks); + for (GLint i = 0; i < nbrActiveUniformsBlocks; ++i) { + QByteArray uniformBlockName(256, '\0'); + GLsizei length = 0; + ShaderUniformBlock uniformBlock; + m_funcs->glGetProgramResourceName(programId, GL_UNIFORM_BLOCK, i, 256, &length, uniformBlockName.data()); + uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); + uniformBlock.m_index = i; + GLenum prop = GL_BUFFER_BINDING; + m_funcs->glGetProgramResourceiv(programId, GL_UNIFORM_BLOCK, i, 1, &prop, 4, NULL, &uniformBlock.m_binding); + prop = GL_BUFFER_DATA_SIZE; + m_funcs->glGetProgramResourceiv(programId, GL_UNIFORM_BLOCK, i, 1, &prop, 4, NULL, &uniformBlock.m_size); + prop = GL_NUM_ACTIVE_VARIABLES; + m_funcs->glGetProgramResourceiv(programId, GL_UNIFORM_BLOCK, i, 1, &prop, 4, NULL, &uniformBlock.m_activeUniformsCount); + blocks.append(uniformBlock); + } + return blocks; +} + +QVector GraphicsHelperGL4::programShaderStorageBlocks(GLuint programId) +{ + QVector blocks; + GLint nbrActiveShaderStorageBlocks = 0; + m_funcs->glGetProgramInterfaceiv(programId, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &nbrActiveShaderStorageBlocks); + blocks.reserve(nbrActiveShaderStorageBlocks); + for (GLint i = 0; i < nbrActiveShaderStorageBlocks; ++i) { + QByteArray storageBlockName(256, '\0'); + GLsizei length = 0; + ShaderStorageBlock storageBlock; + m_funcs->glGetProgramResourceName(programId, GL_SHADER_STORAGE_BLOCK, i, 256, &length, storageBlockName.data()); + storageBlock.m_index = i; + storageBlock.m_name = QString::fromUtf8(storageBlockName.left(length)); + GLenum prop = GL_BUFFER_BINDING; + m_funcs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_binding); + prop = GL_BUFFER_DATA_SIZE; + m_funcs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_size); + prop = GL_NUM_ACTIVE_VARIABLES; + m_funcs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_activeVariablesCount); + blocks.push_back(storageBlock); + } + return blocks; +} + +void GraphicsHelperGL4::vertexAttribDivisor(GLuint index, GLuint divisor) +{ + m_funcs->glVertexAttribDivisor(index, divisor); +} + +void GraphicsHelperGL4::vertexAttributePointer(GLenum shaderDataType, + GLuint index, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + const GLvoid *pointer) +{ + switch (shaderDataType) { + case GL_FLOAT: + case GL_FLOAT_VEC2: + case GL_FLOAT_VEC3: + case GL_FLOAT_VEC4: + case GL_FLOAT_MAT2: + case GL_FLOAT_MAT2x3: + case GL_FLOAT_MAT2x4: + case GL_FLOAT_MAT3: + case GL_FLOAT_MAT3x2: + case GL_FLOAT_MAT3x4: + case GL_FLOAT_MAT4x2: + case GL_FLOAT_MAT4x3: + case GL_FLOAT_MAT4: + m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); + break; + + case GL_INT: + case GL_INT_VEC2: + case GL_INT_VEC3: + case GL_INT_VEC4: + case GL_UNSIGNED_INT: + case GL_UNSIGNED_INT_VEC2: + case GL_UNSIGNED_INT_VEC3: + case GL_UNSIGNED_INT_VEC4: + m_funcs->glVertexAttribIPointer(index, size, type, stride, pointer); + break; + + case GL_DOUBLE: + case GL_DOUBLE_VEC2: + case GL_DOUBLE_VEC3: + case GL_DOUBLE_VEC4: + m_funcs->glVertexAttribLPointer(index, size, type, stride, pointer); + break; + + default: + qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + Q_UNREACHABLE(); + } +} + +void GraphicsHelperGL4::readBuffer(GLenum mode) +{ + m_funcs->glReadBuffer(mode); +} + +void GraphicsHelperGL4::drawBuffer(GLenum mode) +{ + m_funcs->glDrawBuffer(mode); +} + +void *GraphicsHelperGL4::fenceSync() +{ + return m_funcs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); +} + +void GraphicsHelperGL4::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) +{ + qDebug() << Q_FUNC_INFO << sync << static_cast(sync); + GLenum e = m_funcs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); + qDebug() << e; +} + +void GraphicsHelperGL4::waitSync(void *sync) +{ + m_funcs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); +} + +bool GraphicsHelperGL4::wasSyncSignaled(void *sync) +{ + GLint v = 0; + m_funcs->glGetSynciv(static_cast(sync), + GL_SYNC_STATUS, + sizeof(v), + nullptr, + &v); + return v == GL_SIGNALED; +} + +void GraphicsHelperGL4::deleteSync(void *sync) +{ + m_funcs->glDeleteSync(static_cast(sync)); +} + +void GraphicsHelperGL4::rasterMode(GLenum faceMode, GLenum rasterMode) +{ + m_funcs->glPolygonMode(faceMode, rasterMode); +} + +void GraphicsHelperGL4::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform1fv(location, count, values); +} + +void GraphicsHelperGL4::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform2fv(location, count, values); +} + +void GraphicsHelperGL4::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform3fv(location, count, values); +} + +void GraphicsHelperGL4::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniform4fv(location, count, values); +} + +void GraphicsHelperGL4::glUniform1iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform1iv(location, count, values); +} + +void GraphicsHelperGL4::glUniform2iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform2iv(location, count, values); +} + +void GraphicsHelperGL4::glUniform3iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform3iv(location, count, values); +} + +void GraphicsHelperGL4::glUniform4iv(GLint location, GLsizei count, const GLint *values) +{ + m_funcs->glUniform4iv(location, count, values); +} + +void GraphicsHelperGL4::glUniform1uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform1uiv(location, count, values); +} + +void GraphicsHelperGL4::glUniform2uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform2uiv(location, count, values); +} + +void GraphicsHelperGL4::glUniform3uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform3uiv(location, count, values); +} + +void GraphicsHelperGL4::glUniform4uiv(GLint location, GLsizei count, const GLuint *values) +{ + m_funcs->glUniform4uiv(location, count, values); +} + +void GraphicsHelperGL4::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2x3fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3x2fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix2x4fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4x2fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix3x4fv(location, count, false, values); +} + +void GraphicsHelperGL4::glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *values) +{ + m_funcs->glUniformMatrix4x3fv(location, count, false, values); +} + +UniformType GraphicsHelperGL4::uniformTypeFromGLType(GLenum type) +{ + switch (type) { + case GL_FLOAT: + return UniformType::Float; + case GL_FLOAT_VEC2: + return UniformType::Vec2; + case GL_FLOAT_VEC3: + return UniformType::Vec3; + case GL_FLOAT_VEC4: + return UniformType::Vec4; + case GL_FLOAT_MAT2: + return UniformType::Mat2; + case GL_FLOAT_MAT3: + return UniformType::Mat3; + case GL_FLOAT_MAT4: + return UniformType::Mat4; + case GL_FLOAT_MAT2x3: + return UniformType::Mat2x3; + case GL_FLOAT_MAT3x2: + return UniformType::Mat3x2; + case GL_FLOAT_MAT2x4: + return UniformType::Mat2x4; + case GL_FLOAT_MAT4x2: + return UniformType::Mat4x2; + case GL_FLOAT_MAT3x4: + return UniformType::Mat3x4; + case GL_FLOAT_MAT4x3: + return UniformType::Mat4x3; + case GL_INT: + return UniformType::Int; + case GL_INT_VEC2: + return UniformType::IVec2; + case GL_INT_VEC3: + return UniformType::IVec3; + case GL_INT_VEC4: + return UniformType::IVec4; + case GL_UNSIGNED_INT: + return UniformType::UInt; + case GL_UNSIGNED_INT_VEC2: + return UniformType::UIVec2; + case GL_UNSIGNED_INT_VEC3: + return UniformType::UIVec3; + case GL_UNSIGNED_INT_VEC4: + return UniformType::UIVec4; + case GL_BOOL: + return UniformType::Bool; + case GL_BOOL_VEC2: + return UniformType::BVec2; + case GL_BOOL_VEC3: + return UniformType::BVec3; + case GL_BOOL_VEC4: + return UniformType::BVec4; + + case GL_SAMPLER_1D: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D: + case GL_SAMPLER_2D_RECT: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_CUBE_MAP_ARRAY: + case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_SAMPLER_3D: + case GL_SAMPLER_BUFFER: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_CUBE_MAP_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: + return UniformType::Sampler; + + case GL_IMAGE_1D: + case GL_IMAGE_2D: + case GL_IMAGE_3D: + case GL_IMAGE_2D_RECT: + case GL_IMAGE_CUBE: + case GL_IMAGE_BUFFER: + case GL_IMAGE_1D_ARRAY: + case GL_IMAGE_2D_ARRAY: + case GL_IMAGE_CUBE_MAP_ARRAY: + case GL_IMAGE_2D_MULTISAMPLE: + case GL_IMAGE_2D_MULTISAMPLE_ARRAY: + case GL_INT_IMAGE_1D: + case GL_INT_IMAGE_2D: + case GL_INT_IMAGE_3D: + case GL_INT_IMAGE_2D_RECT: + case GL_INT_IMAGE_CUBE: + case GL_INT_IMAGE_BUFFER: + case GL_INT_IMAGE_1D_ARRAY: + case GL_INT_IMAGE_2D_ARRAY: + case GL_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_INT_IMAGE_2D_MULTISAMPLE: + case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_IMAGE_1D: + case GL_UNSIGNED_INT_IMAGE_2D: + case GL_UNSIGNED_INT_IMAGE_3D: + case GL_UNSIGNED_INT_IMAGE_2D_RECT: + case GL_UNSIGNED_INT_IMAGE_CUBE: + case GL_UNSIGNED_INT_IMAGE_BUFFER: + case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: + return UniformType::Image; + + default: + // TO DO: Add support for Doubles and Images + Q_UNREACHABLE(); + return UniformType::Float; + } +} + +void GraphicsHelperGL4::blendEquation(GLenum mode) +{ + m_funcs->glBlendEquation(mode); +} + +void GraphicsHelperGL4::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) +{ + m_funcs->glBlendFunci(buf, sfactor, dfactor); +} + +void GraphicsHelperGL4::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) +{ + m_funcs->glBlendFuncSeparatei(buf, sRGB, dRGB, sAlpha, dAlpha); +} + +void GraphicsHelperGL4::alphaTest(GLenum, GLenum) +{ + qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; +} + +void GraphicsHelperGL4::depthTest(GLenum mode) +{ + m_funcs->glEnable(GL_DEPTH_TEST); + m_funcs->glDepthFunc(mode); +} + +void GraphicsHelperGL4::depthMask(GLenum mode) +{ + m_funcs->glDepthMask(mode); +} + +void GraphicsHelperGL4::depthRange(GLdouble nearValue, GLdouble farValue) +{ + m_funcs->glDepthRange(nearValue, farValue); +} + +void GraphicsHelperGL4::frontFace(GLenum mode) +{ + m_funcs->glFrontFace(mode); + +} + +void GraphicsHelperGL4::setMSAAEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_MULTISAMPLE) + : m_funcs->glDisable(GL_MULTISAMPLE); +} + +void GraphicsHelperGL4::setAlphaCoverageEnabled(bool enabled) +{ + enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) + : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); +} + +GLuint GraphicsHelperGL4::createFrameBufferObject() +{ + GLuint id; + m_funcs->glGenFramebuffers(1, &id); + return id; +} + +void GraphicsHelperGL4::releaseFrameBufferObject(GLuint frameBufferId) +{ + m_funcs->glDeleteFramebuffers(1, &frameBufferId); +} + +void GraphicsHelperGL4::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) +{ + switch (mode) { + case FBODraw: + m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); + return; + case FBORead: + m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); + return; + case FBOReadAndDraw: + default: + m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); + return; + } +} + +void GraphicsHelperGL4::bindImageTexture(GLuint imageUnit, GLuint texture, + GLint mipLevel, GLboolean layered, + GLint layer, GLenum access, GLenum format) +{ + m_funcs->glBindImageTexture(imageUnit, + texture, + mipLevel, + layered, + layer, + access, + format); +} + +GLuint GraphicsHelperGL4::boundFrameBufferObject() +{ + GLint id = 0; + m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); + return id; +} + +bool GraphicsHelperGL4::checkFrameBufferComplete() +{ + return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); +} + +bool GraphicsHelperGL4::frameBufferNeedsRenderBuffer(const Attachment &attachment) +{ + Q_UNUSED(attachment); + return false; +} + +void GraphicsHelperGL4::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) +{ + GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; + + if (attachment.m_point <= QRenderTargetOutput::Color15) + attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; + else if (attachment.m_point == QRenderTargetOutput::Depth) + attr = GL_DEPTH_ATTACHMENT; + else if (attachment.m_point == QRenderTargetOutput::Stencil) + attr = GL_STENCIL_ATTACHMENT; + + texture->bind(); + QOpenGLTexture::Target target = texture->target(); + if (target == QOpenGLTexture::Target1DArray || target == QOpenGLTexture::Target2DArray || + target == QOpenGLTexture::Target2DMultisampleArray || target == QOpenGLTexture::Target3D) + m_funcs->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMapArray) + m_funcs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); + else if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face != QAbstractTexture::AllFaces) + m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); + else + m_funcs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); + texture->release(); +} + +void GraphicsHelperGL4::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) +{ + Q_UNUSED(renderBuffer); + Q_UNUSED(attachment); + Q_UNREACHABLE(); +} + +bool GraphicsHelperGL4::supportsFeature(GraphicsHelperInterface::Feature feature) const +{ + switch (feature) { + case MRT: + case Tessellation: + case UniformBufferObject: + case BindableFragmentOutputs: + case PrimitiveRestart: + case RenderBufferDimensionRetrieval: + case TextureDimensionRetrieval: + case ShaderStorageObject: + case Compute: + case DrawBuffersBlend: + case BlitFramebuffer: + case IndirectDrawing: + case MapBuffer: + case Fences: + case ShaderImage: + return true; + default: + return false; + } +} + +void GraphicsHelperGL4::drawBuffers(GLsizei n, const int *bufs) +{ + // Use QVarLengthArray here + QVarLengthArray drawBufs(n); + + for (int i = 0; i < n; i++) + drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; + m_funcs->glDrawBuffers(n, drawBufs.constData()); +} + +void GraphicsHelperGL4::bindFragDataLocation(GLuint shader, const QHash &outputs) +{ + for (auto it = outputs.begin(), end = outputs.end(); it != end; ++it) + m_funcs->glBindFragDataLocation(shader, it.value(), it.key().toStdString().c_str()); +} + +void GraphicsHelperGL4::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) +{ + m_funcs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); +} + +void GraphicsHelperGL4::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) +{ + m_funcs->glShaderStorageBlockBinding(programId, shaderStorageBlockIndex, shaderStorageBlockBinding); +} + +void GraphicsHelperGL4::bindBufferBase(GLenum target, GLuint index, GLuint buffer) +{ + m_funcs->glBindBufferBase(target, index, buffer); +} + +void GraphicsHelperGL4::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) +{ + char *bufferData = buffer.data(); + + switch (description.m_type) { + + case GL_FLOAT: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_FLOAT_VEC2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_FLOAT_VEC3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_FLOAT_VEC4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_FLOAT_MAT2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); + break; + } + + case GL_FLOAT_MAT2x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); + break; + } + + case GL_FLOAT_MAT2x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); + break; + } + + case GL_FLOAT_MAT3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); + break; + } + + case GL_FLOAT_MAT3x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); + break; + } + + case GL_FLOAT_MAT3x4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); + break; + } + + case GL_FLOAT_MAT4: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); + break; + } + + case GL_FLOAT_MAT4x2: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); + break; + } + + case GL_FLOAT_MAT4x3: { + const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); + QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); + break; + } + + case GL_INT: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_INT_VEC2: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_INT_VEC3: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_INT_VEC4: { + const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_UNSIGNED_INT: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_UNSIGNED_INT_VEC2: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_UNSIGNED_INT_VEC3: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_UNSIGNED_INT_VEC4: { + const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_BOOL: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); + QGraphicsUtils::fillDataArray(bufferData, data, description, 1); + break; + } + + case GL_BOOL_VEC2: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); + QGraphicsUtils::fillDataArray(bufferData, data, description, 2); + break; + } + + case GL_BOOL_VEC3: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); + QGraphicsUtils::fillDataArray(bufferData, data, description, 3); + break; + } + + case GL_BOOL_VEC4: { + const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); + QGraphicsUtils::fillDataArray(bufferData, data, description, 4); + break; + } + + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_2D_RECT: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_2D_RECT: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_2D_RECT: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_1D_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_IMAGE_1D: + case GL_IMAGE_2D: + case GL_IMAGE_3D: + case GL_IMAGE_2D_RECT: + case GL_IMAGE_CUBE: + case GL_IMAGE_BUFFER: + case GL_IMAGE_1D_ARRAY: + case GL_IMAGE_2D_ARRAY: + case GL_IMAGE_CUBE_MAP_ARRAY: + case GL_IMAGE_2D_MULTISAMPLE: + case GL_IMAGE_2D_MULTISAMPLE_ARRAY: + case GL_INT_IMAGE_1D: + case GL_INT_IMAGE_2D: + case GL_INT_IMAGE_3D: + case GL_INT_IMAGE_2D_RECT: + case GL_INT_IMAGE_CUBE: + case GL_INT_IMAGE_BUFFER: + case GL_INT_IMAGE_1D_ARRAY: + case GL_INT_IMAGE_2D_ARRAY: + case GL_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_INT_IMAGE_2D_MULTISAMPLE: + case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_IMAGE_1D: + case GL_UNSIGNED_INT_IMAGE_2D: + case GL_UNSIGNED_INT_IMAGE_3D: + case GL_UNSIGNED_INT_IMAGE_2D_RECT: + case GL_UNSIGNED_INT_IMAGE_CUBE: + case GL_UNSIGNED_INT_IMAGE_BUFFER: + case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: { + Q_ASSERT(description.m_size == 1); + int value = v.toInt(); + QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); + break; + } + + default: + qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; + break; + } +} + +uint GraphicsHelperGL4::uniformByteSize(const ShaderUniform &description) +{ + uint rawByteSize = 0; + int arrayStride = qMax(description.m_arrayStride, 0); + int matrixStride = qMax(description.m_matrixStride, 0); + + switch (description.m_type) { + + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + case GL_UNSIGNED_INT_VEC2: + rawByteSize = 8; + break; + + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + case GL_UNSIGNED_INT_VEC3: + rawByteSize = 12; + break; + + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + case GL_UNSIGNED_INT_VEC4: + rawByteSize = 16; + break; + + case GL_FLOAT_MAT2: + rawByteSize = matrixStride ? 2 * matrixStride : 16; + break; + + case GL_FLOAT_MAT2x4: + rawByteSize = matrixStride ? 2 * matrixStride : 32; + break; + + case GL_FLOAT_MAT4x2: + rawByteSize = matrixStride ? 4 * matrixStride : 32; + break; + + case GL_FLOAT_MAT3: + rawByteSize = matrixStride ? 3 * matrixStride : 36; + break; + + case GL_FLOAT_MAT2x3: + rawByteSize = matrixStride ? 2 * matrixStride : 24; + break; + + case GL_FLOAT_MAT3x2: + rawByteSize = matrixStride ? 3 * matrixStride : 24; + break; + + case GL_FLOAT_MAT4: + rawByteSize = matrixStride ? 4 * matrixStride : 64; + break; + + case GL_FLOAT_MAT4x3: + rawByteSize = matrixStride ? 4 * matrixStride : 48; + break; + + case GL_FLOAT_MAT3x4: + rawByteSize = matrixStride ? 3 * matrixStride : 48; + break; + + case GL_BOOL: + rawByteSize = 1; + break; + + case GL_BOOL_VEC2: + rawByteSize = 2; + break; + + case GL_BOOL_VEC3: + rawByteSize = 3; + break; + + case GL_BOOL_VEC4: + rawByteSize = 4; + break; + + case GL_INT: + case GL_FLOAT: + case GL_UNSIGNED_INT: + case GL_SAMPLER_1D: + case GL_SAMPLER_2D: + case GL_SAMPLER_3D: + case GL_SAMPLER_CUBE: + case GL_SAMPLER_BUFFER: + case GL_SAMPLER_2D_RECT: + case GL_INT_SAMPLER_1D: + case GL_INT_SAMPLER_2D: + case GL_INT_SAMPLER_3D: + case GL_INT_SAMPLER_CUBE: + case GL_INT_SAMPLER_BUFFER: + case GL_INT_SAMPLER_2D_RECT: + case GL_UNSIGNED_INT_SAMPLER_1D: + case GL_UNSIGNED_INT_SAMPLER_2D: + case GL_UNSIGNED_INT_SAMPLER_3D: + case GL_UNSIGNED_INT_SAMPLER_CUBE: + case GL_UNSIGNED_INT_SAMPLER_BUFFER: + case GL_UNSIGNED_INT_SAMPLER_2D_RECT: + case GL_SAMPLER_1D_SHADOW: + case GL_SAMPLER_2D_SHADOW: + case GL_SAMPLER_CUBE_SHADOW: + case GL_SAMPLER_1D_ARRAY: + case GL_SAMPLER_2D_ARRAY: + case GL_INT_SAMPLER_1D_ARRAY: + case GL_INT_SAMPLER_2D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: + case GL_SAMPLER_1D_ARRAY_SHADOW: + case GL_SAMPLER_2D_ARRAY_SHADOW: + case GL_SAMPLER_2D_RECT_SHADOW: + case GL_SAMPLER_2D_MULTISAMPLE: + case GL_INT_SAMPLER_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: + case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: + case GL_IMAGE_1D: + case GL_IMAGE_2D: + case GL_IMAGE_3D: + case GL_IMAGE_2D_RECT: + case GL_IMAGE_CUBE: + case GL_IMAGE_BUFFER: + case GL_IMAGE_1D_ARRAY: + case GL_IMAGE_2D_ARRAY: + case GL_IMAGE_CUBE_MAP_ARRAY: + case GL_IMAGE_2D_MULTISAMPLE: + case GL_IMAGE_2D_MULTISAMPLE_ARRAY: + case GL_INT_IMAGE_1D: + case GL_INT_IMAGE_2D: + case GL_INT_IMAGE_3D: + case GL_INT_IMAGE_2D_RECT: + case GL_INT_IMAGE_CUBE: + case GL_INT_IMAGE_BUFFER: + case GL_INT_IMAGE_1D_ARRAY: + case GL_INT_IMAGE_2D_ARRAY: + case GL_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_INT_IMAGE_2D_MULTISAMPLE: + case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: + case GL_UNSIGNED_INT_IMAGE_1D: + case GL_UNSIGNED_INT_IMAGE_2D: + case GL_UNSIGNED_INT_IMAGE_3D: + case GL_UNSIGNED_INT_IMAGE_2D_RECT: + case GL_UNSIGNED_INT_IMAGE_CUBE: + case GL_UNSIGNED_INT_IMAGE_BUFFER: + case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: + case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: + case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: + case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: + rawByteSize = 4; + break; + + default: { + qWarning() << Q_FUNC_INFO << "unable to deduce rawByteSize for uniform type:" << description.m_type << "for uniform" << description.m_name; + break; + } + + } + + return arrayStride ? rawByteSize * arrayStride : rawByteSize; +} + +void GraphicsHelperGL4::enableClipPlane(int clipPlane) +{ + m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL4::disableClipPlane(int clipPlane) +{ + m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); +} + +void GraphicsHelperGL4::setClipPlane(int, const QVector3D &, float) +{ + // deprecated +} + +GLint GraphicsHelperGL4::maxClipPlaneCount() +{ + GLint max = 0; + m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); + return max; +} + +void GraphicsHelperGL4::memoryBarrier(QMemoryBarrier::Operations barriers) +{ + m_funcs->glMemoryBarrier(memoryBarrierGLBitfield(barriers)); +} + +void GraphicsHelperGL4::enablePrimitiveRestart(int primitiveRestartIndex) +{ + m_funcs->glPrimitiveRestartIndex(primitiveRestartIndex); + m_funcs->glEnable(GL_PRIMITIVE_RESTART); +} + +void GraphicsHelperGL4::enableVertexAttributeArray(int location) +{ + m_funcs->glEnableVertexAttribArray(location); +} + +void GraphicsHelperGL4::disablePrimitiveRestart() +{ + m_funcs->glDisable(GL_PRIMITIVE_RESTART); +} + +void GraphicsHelperGL4::clearBufferf(GLint drawbuffer, const QVector4D &values) +{ + GLfloat vec[4] = {values[0], values[1], values[2], values[3]}; + m_funcs->glClearBufferfv(GL_COLOR, drawbuffer, vec); +} + +void GraphicsHelperGL4::pointSize(bool programmable, GLfloat value) +{ + if (programmable) { + m_funcs->glEnable(GL_PROGRAM_POINT_SIZE); + } else { + m_funcs->glDisable(GL_PROGRAM_POINT_SIZE); + m_funcs->glPointSize(value); + } +} + +void GraphicsHelperGL4::enablei(GLenum cap, GLuint index) +{ + m_funcs->glEnablei(cap, index); +} + +void GraphicsHelperGL4::disablei(GLenum cap, GLuint index) +{ + m_funcs->glDisablei(cap, index); +} + +void GraphicsHelperGL4::setSeamlessCubemap(bool enable) +{ + if (enable) + m_funcs->glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + else + m_funcs->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); +} + +QSize GraphicsHelperGL4::getRenderBufferDimensions(GLuint renderBufferId) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); + m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); + m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); + + return QSize(width, height); +} + +QSize GraphicsHelperGL4::getTextureDimensions(GLuint textureId, GLenum target, uint level) +{ + GLint width = 0; + GLint height = 0; + + m_funcs->glBindTexture(target, textureId); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); + m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); + m_funcs->glBindTexture(target, 0); + + return QSize(width, height); +} + +void GraphicsHelperGL4::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) +{ + m_funcs->glDispatchCompute(wx, wy, wz); +} + +char *GraphicsHelperGL4::mapBuffer(GLenum target, GLsizeiptr size) +{ + return static_cast(m_funcs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); +} + +GLboolean GraphicsHelperGL4::unmapBuffer(GLenum target) +{ + return m_funcs->glUnmapBuffer(target); +} + +void GraphicsHelperGL4::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) +{ + m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h new file mode 100644 index 000000000..02cb7e211 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#ifndef QT_OPENGL_ES_2 + +QT_BEGIN_NAMESPACE + +class QOpenGLFunctions_4_3_Core; + +namespace Qt3DRender { +namespace Render { + +class Q_AUTOTEST_EXPORT GraphicsHelperGL4 : public GraphicsHelperInterface +{ +public: + GraphicsHelperGL4(); + + // QGraphicHelperInterface interface + void alphaTest(GLenum mode1, GLenum mode2) override; + void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; + void bindFragDataLocation(GLuint shader, const QHash &outputs) override; + bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; + void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; + void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; + void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; + void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; + void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; + void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; + void blendEquation(GLenum mode) override; + void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; + void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; + void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; + GLuint boundFrameBufferObject() override; + void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; + bool checkFrameBufferComplete() override; + void clearBufferf(GLint drawbuffer, const QVector4D &values) override; + GLuint createFrameBufferObject() override; + void depthMask(GLenum mode) override; + void depthRange(GLdouble nearValue, GLdouble farValue) override; + void depthTest(GLenum mode) override; + void disableClipPlane(int clipPlane) override; + void disablei(GLenum cap, GLuint index) override; + void disablePrimitiveRestart() override; + void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; + char *mapBuffer(GLenum target, GLsizeiptr size) override; + GLboolean unmapBuffer(GLenum target) override; + void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; + void drawArraysIndirect(GLenum mode,void *indirect) override; + void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; + void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; + void drawBuffers(GLsizei n, const int *bufs) override; + void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; + void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; + void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; + void enableClipPlane(int clipPlane) override; + void enablei(GLenum cap, GLuint index) override; + void enablePrimitiveRestart(int primitiveRestartIndex) override; + void enableVertexAttributeArray(int location) override; + void frontFace(GLenum mode) override; + QSize getRenderBufferDimensions(GLuint renderBufferId) override; + QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; + void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; + void pointSize(bool programmable, GLfloat value) override; + GLint maxClipPlaneCount() override; + void memoryBarrier(QMemoryBarrier::Operations barriers) override; + QVector programUniformBlocks(GLuint programId) override; + QVector programAttributesAndLocations(GLuint programId) override; + QVector programUniformsAndLocations(GLuint programId) override; + QVector programShaderStorageBlocks(GLuint programId) override; + void releaseFrameBufferObject(GLuint frameBufferId) override; + void setMSAAEnabled(bool enable) override; + void setAlphaCoverageEnabled(bool enable) override; + void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; + void setSeamlessCubemap(bool enable) override; + void setVerticesPerPatch(GLint verticesPerPatch) override; + bool supportsFeature(Feature feature) const override; + uint uniformByteSize(const ShaderUniform &description) override; + void useProgram(GLuint programId) override; + void vertexAttribDivisor(GLuint index, GLuint divisor) override; + void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; + void readBuffer(GLenum mode) override; + void drawBuffer(GLenum mode) override; + void rasterMode(GLenum faceMode, GLenum rasterMode) override; + + void *fenceSync() override; + void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; + void waitSync(void *sync) override; + bool wasSyncSignaled(void *sync) override; + void deleteSync(void *sync) override; + + void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; + + void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; + void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; + + void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; + void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; + + void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; + void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; + + UniformType uniformTypeFromGLType(GLenum glType) override; + +private: + QOpenGLFunctions_4_3_Core *m_funcs; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // !QT_OPENGL_ES_2 + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h new file mode 100644 index 000000000..aa2b65c66 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h @@ -0,0 +1,203 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H +#define QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +struct Attachment; +class RenderBuffer; + +class GraphicsHelperInterface +{ +public: + enum Feature { + MRT = 0, + Tessellation, + UniformBufferObject, + BindableFragmentOutputs, + PrimitiveRestart, + RenderBufferDimensionRetrieval, + TextureDimensionRetrieval, + ShaderStorageObject, + Compute, + DrawBuffersBlend, + BlitFramebuffer, + IndirectDrawing, + MapBuffer, + Fences, + ShaderImage + }; + + enum FBOBindMode { + FBODraw, + FBORead, + FBOReadAndDraw + }; + + virtual ~GraphicsHelperInterface() {} + virtual void alphaTest(GLenum mode1, GLenum mode2) = 0; + virtual void bindBufferBase(GLenum target, GLuint index, GLuint buffer) = 0; + virtual void bindFragDataLocation(GLuint shader, const QHash &outputs) = 0; + virtual bool frameBufferNeedsRenderBuffer(const Attachment &attachment) = 0; + virtual void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) = 0; + virtual void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) = 0; + virtual void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) = 0; + virtual void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) = 0; + virtual void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) = 0; + virtual void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) = 0; + virtual void blendEquation(GLenum mode) = 0; + virtual void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) = 0; + virtual void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) = 0; + virtual void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) = 0; + virtual GLuint boundFrameBufferObject() = 0; + virtual void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) = 0; + virtual bool checkFrameBufferComplete() = 0; + virtual void clearBufferf(GLint drawbuffer, const QVector4D &values) = 0; + virtual GLuint createFrameBufferObject() = 0; + virtual void depthRange(GLdouble nearValue, GLdouble farValue) = 0; + virtual void depthMask(GLenum mode) = 0; + virtual void depthTest(GLenum mode) = 0; + virtual void disableClipPlane(int clipPlane) = 0; + virtual void disablei(GLenum cap, GLuint index) = 0; + virtual void disablePrimitiveRestart() = 0; + virtual void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) = 0; + virtual char *mapBuffer(GLenum target, GLsizeiptr size) = 0; + virtual GLboolean unmapBuffer(GLenum target) = 0; + virtual void drawArrays(GLenum primitiveType, GLint first, GLsizei count) = 0; + virtual void drawArraysIndirect(GLenum mode,void *indirect) = 0; + virtual void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) = 0; + virtual void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseinstance) = 0; + virtual void drawBuffers(GLsizei n, const int *bufs) = 0; + virtual void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLint baseVertex) = 0; + virtual void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) = 0; + virtual void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLsizei instances, GLint baseVertex, GLint baseInstance) = 0; + virtual void enableClipPlane(int clipPlane) = 0; + virtual void enablei(GLenum cap, GLuint index) = 0; + virtual void enablePrimitiveRestart(int primitiveRestartIndex) = 0; + virtual void enableVertexAttributeArray(int location) = 0; + virtual void frontFace(GLenum mode) = 0; + virtual QSize getRenderBufferDimensions(GLuint renderBufferId) = 0; + virtual QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) = 0; + virtual void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) = 0; + virtual GLint maxClipPlaneCount() = 0; + virtual void memoryBarrier(QMemoryBarrier::Operations barriers) = 0; + virtual void pointSize(bool programmable, GLfloat value) = 0; + virtual QVector programAttributesAndLocations(GLuint programId) = 0; + virtual QVector programUniformsAndLocations(GLuint programId) = 0; + virtual QVector programUniformBlocks(GLuint programId) = 0; + virtual QVector programShaderStorageBlocks(GLuint programId) = 0; + virtual void releaseFrameBufferObject(GLuint frameBufferId) = 0; + virtual void setAlphaCoverageEnabled(bool enable) = 0; + virtual void setClipPlane(int clipPlane, const QVector3D &normal, float distance) = 0; + virtual void setMSAAEnabled(bool enable) = 0; + virtual void setSeamlessCubemap(bool enable) = 0; + virtual void setVerticesPerPatch(GLint verticesPerPatch) = 0; + virtual bool supportsFeature(Feature feature) const = 0; + virtual uint uniformByteSize(const ShaderUniform &description) = 0; + virtual void useProgram(GLuint programId) = 0; + virtual void vertexAttribDivisor(GLuint index, GLuint divisor) = 0; + virtual void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) = 0; + virtual void readBuffer(GLenum mode) = 0; + virtual void drawBuffer(GLenum mode) = 0; + virtual void rasterMode(GLenum faceMode, GLenum rasterMode) = 0; + + virtual void *fenceSync() = 0; + virtual void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) = 0; + virtual void waitSync(void *sync) = 0; + virtual bool wasSyncSignaled(void *sync) = 0; + virtual void deleteSync(void *sync) = 0; + + virtual void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) = 0; + + virtual void glUniform1iv(GLint location, GLsizei count, const GLint *value) = 0; + virtual void glUniform2iv(GLint location, GLsizei count, const GLint *value) = 0; + virtual void glUniform3iv(GLint location, GLsizei count, const GLint *value) = 0; + virtual void glUniform4iv(GLint location, GLsizei count, const GLint *value) = 0; + + virtual void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) = 0; + virtual void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) = 0; + virtual void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) = 0; + virtual void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) = 0; + + virtual void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) = 0; + virtual void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) = 0; + + virtual UniformType uniformTypeFromGLType(GLenum glType) = 0; +}; + + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri new file mode 100644 index 000000000..3cfa445ce --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri @@ -0,0 +1,33 @@ +#DEFINES += QT3D_RENDER_ASPECT_OPENGL_DEBUG + +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/graphicscontext_p.h \ + $$PWD/graphicshelperinterface_p.h \ + $$PWD/graphicshelperes2_p.h \ + $$PWD/graphicshelperes3_p.h \ + $$PWD/graphicshelperes3_1_p.h \ + $$PWD/graphicshelperes3_2_p.h \ + $$PWD/graphicshelpergl2_p.h \ + $$PWD/graphicshelpergl3_3_p.h \ + $$PWD/graphicshelpergl4_p.h \ + $$PWD/graphicshelpergl3_2_p.h \ + $$PWD/imagesubmissioncontext_p.h \ + $$PWD/submissioncontext_p.h \ + $$PWD/texturesubmissioncontext_p.h \ + $$PWD/qgraphicsutils_p.h + +SOURCES += \ + $$PWD/graphicscontext.cpp \ + $$PWD/graphicshelperes2.cpp \ + $$PWD/graphicshelperes3.cpp \ + $$PWD/graphicshelperes3_1.cpp \ + $$PWD/graphicshelperes3_2.cpp \ + $$PWD/graphicshelpergl2.cpp \ + $$PWD/graphicshelpergl3_3.cpp \ + $$PWD/graphicshelpergl4.cpp \ + $$PWD/graphicshelpergl3_2.cpp \ + $$PWD/imagesubmissioncontext.cpp \ + $$PWD/submissioncontext.cpp \ + $$PWD/texturesubmissioncontext.cpp diff --git a/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp new file mode 100644 index 000000000..cd2b33fb4 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp @@ -0,0 +1,306 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "imagesubmissioncontext_p.h" +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +// ES 3.1+ or GL 4.2+ +#ifndef GL_READ_ONLY +#define GL_READ_ONLY 0x88B8 +#endif +#ifndef GL_WRITE_ONLY +#define GL_WRITE_ONLY 0x88B9 +#endif +#ifndef GL_READ_WRITE +#define GL_READ_WRITE 0x88BA +#endif + +namespace Qt3DRender { +namespace Render { + +class GraphicsContext; +class GLTexture; + +namespace { + +GLenum glAccessEnumForShaderImageAccess(QShaderImage::Access access) +{ + switch (access) { + case QShaderImage::ReadOnly: + return GL_READ_ONLY; + case QShaderImage::WriteOnly: + return GL_WRITE_ONLY; + case QShaderImage::ReadWrite: + default: + break; + } + return GL_READ_WRITE; +} + +GLenum glImageFormatToGL(QShaderImage::ImageFormat format) +{ + // Right now we can abuse from the fact that the ImageFormat enum values + // have been assigned the same value as the GL enum + return GLenum(format); +} + +GLenum glImageFormatForShaderImageFormat(QShaderImage::ImageFormat format, + QAbstractTexture::TextureFormat textureFormat) +{ + Q_ASSERT_X(format != QShaderImage::NoFormat, Q_FUNC_INFO, "Valid image format or Automatic expected"); + + if (format != QShaderImage::Automatic) + return glImageFormatToGL(format); + + // Otherwise try to mind to best texture format + switch (textureFormat) { + case QAbstractTexture::R8_UNorm: + return glImageFormatToGL(QShaderImage::R8_UNorm); + case QAbstractTexture::RG8_UNorm: + return glImageFormatToGL(QShaderImage::RG8_UNorm); + case QAbstractTexture::RGBA8_UNorm: + return glImageFormatToGL(QShaderImage::RGBA8_UNorm); + + case QAbstractTexture::R16_UNorm: + return glImageFormatToGL(QShaderImage::R16_UNorm); + case QAbstractTexture::RG16_UNorm: + return glImageFormatToGL(QShaderImage::RG16_UNorm); + case QAbstractTexture::RGBA16_UNorm: + return glImageFormatToGL(QShaderImage::RGBA16_UNorm); + + case QAbstractTexture::R8_SNorm: + return glImageFormatToGL(QShaderImage::R8_SNorm); + case QAbstractTexture::RG8_SNorm: + return glImageFormatToGL(QShaderImage::RG8_SNorm); + case QAbstractTexture::RGBA8_SNorm: + return glImageFormatToGL(QShaderImage::RGBA8_SNorm); + + case QAbstractTexture::R16_SNorm: + return glImageFormatToGL(QShaderImage::R16_SNorm); + case QAbstractTexture::RG16_SNorm: + return glImageFormatToGL(QShaderImage::RG16_SNorm); + case QAbstractTexture::RGBA16_SNorm: + return glImageFormatToGL(QShaderImage::RGBA16_SNorm); + + case QAbstractTexture::R8U: + return glImageFormatToGL(QShaderImage::R8U); + case QAbstractTexture::RG8U: + return glImageFormatToGL(QShaderImage::RG8U); + case QAbstractTexture::RGBA8U: + return glImageFormatToGL(QShaderImage::RGBA8U); + + case QAbstractTexture::R16U: + return glImageFormatToGL(QShaderImage::R16U); + case QAbstractTexture::RG16U: + return glImageFormatToGL(QShaderImage::RG16U); + case QAbstractTexture::RGBA16U: + return glImageFormatToGL(QShaderImage::RGBA16U); + + case QAbstractTexture::R32U: + return glImageFormatToGL(QShaderImage::R32U); + case QAbstractTexture::RG32U: + return glImageFormatToGL(QShaderImage::RG32U); + case QAbstractTexture::RGBA32U: + return glImageFormatToGL(QShaderImage::RGBA32U); + + case QAbstractTexture::R8I: + return glImageFormatToGL(QShaderImage::R8I); + case QAbstractTexture::RG8I: + return glImageFormatToGL(QShaderImage::RG8I); + case QAbstractTexture::RGBA8I: + return glImageFormatToGL(QShaderImage::RGBA8I); + + case QAbstractTexture::R16I: + return glImageFormatToGL(QShaderImage::R16I); + case QAbstractTexture::RG16I: + return glImageFormatToGL(QShaderImage::RG16I); + case QAbstractTexture::RGBA16I: + return glImageFormatToGL(QShaderImage::RGBA16I); + + case QAbstractTexture::R32I: + return glImageFormatToGL(QShaderImage::R32I); + case QAbstractTexture::RG32I: + return glImageFormatToGL(QShaderImage::RG32I); + case QAbstractTexture::RGBA32I: + return glImageFormatToGL(QShaderImage::RGBA32I); + + case QAbstractTexture::R16F: + return glImageFormatToGL(QShaderImage::R16F); + case QAbstractTexture::RG16F: + return glImageFormatToGL(QShaderImage::RG16F); + case QAbstractTexture::RGBA16F: + return glImageFormatToGL(QShaderImage::RGBA16F); + + case QAbstractTexture::R32F: + return glImageFormatToGL(QShaderImage::R32F); + case QAbstractTexture::RG32F: + return glImageFormatToGL(QShaderImage::RG32F); + case QAbstractTexture::RGBA32F: + return glImageFormatToGL(QShaderImage::RGBA32F); + + case QAbstractTexture::RG11B10F: + return glImageFormatToGL(QShaderImage::RG11B10F); + case QAbstractTexture::RGB10A2: + return glImageFormatToGL(QShaderImage::RGB10A2); + case QAbstractTexture::RGB10A2U: + return glImageFormatToGL(QShaderImage::RGB10A2U); + + default: + qWarning() << "Cannot map Texture format" << textureFormat << "to a valid Image Format"; + Q_UNREACHABLE(); + return GL_NONE; + } +} + +} // anonymous + +ImageSubmissionContext::ImageSubmissionContext() + : m_ctx(nullptr) +{ +} + +void ImageSubmissionContext::initialize(GraphicsContext *context) +{ + m_ctx = context; + m_activeImages.resize(m_ctx->maxImageUnitsCount()); +} + +void ImageSubmissionContext::endDrawing() +{ + // Reduce score of all active Images + decayImageScores(); +} + +// Return Image Unit for Image +// If Image was used previously and recently, it will return the last used unit +// for that image. Otherwise it will try to return the image unit the least used. +int ImageSubmissionContext::activateImage(ShaderImage *image, GLTexture *tex) +{ + const int onUnit = assignUnitForImage(image->peerId()); + + if (onUnit < 0) { + qWarning() << "Unable to find available image unit"; + return -1; + } + + QOpenGLTexture *glTex = tex->getGLTexture(); + if (glTex == nullptr) { + qWarning() << "Unable to retrieve valid texture for Image"; + return -1; + } + + // Bind Image against Texture and resolve Image Format + m_ctx->bindImageTexture(onUnit, + glTex->textureId(), + image->mipLevel(), + image->layered(), + image->layer(), + glAccessEnumForShaderImageAccess(image->access()), + glImageFormatForShaderImageFormat(image->format(), + tex->properties().format)); + + // Store information about the Texture/Image on ActiveImage for given + // image unit + m_activeImages[onUnit].shaderImageId = image->peerId(); + m_activeImages[onUnit].texture = tex; + m_activeImages[onUnit].score = 200; + m_activeImages[onUnit].pinned = true; + + return onUnit; +} + +// Unset pinned Active Image and reduce their score +void ImageSubmissionContext::deactivateImages() +{ + for (int u = 0, m = m_activeImages.size(); u < m; ++u) { + if (m_activeImages[u].pinned) { + m_activeImages[u].pinned = false; + m_activeImages[u].score = qMax(m_activeImages[u].score - 1, 0); + return; + } + } +} + +// Reduce score of all active images (pinned or not) +void ImageSubmissionContext::decayImageScores() +{ + for (int u = 0, m = m_activeImages.size(); u < m; ++u) + m_activeImages[u].score = qMax(m_activeImages[u].score - 1, 0); +} + +int ImageSubmissionContext::assignUnitForImage(Qt3DCore::QNodeId shaderImageId) +{ + int lowestScoredUnit = -1; + int lowestScore = 0xfffffff; + + const int m = m_activeImages.size(); + for (int u = 0; u < m; ++u) { + if (m_activeImages[u].shaderImageId == shaderImageId) + return u; + } + + for (int u = 0; u < m; ++u) { + // No image is currently active on the image unit + // we save the image unit with the texture that has been on there + // the longest time while not being used + if (!m_activeImages[u].pinned) { + const int score = m_activeImages[u].score; + if (score < lowestScore) { + lowestScore = score; + lowestScoredUnit = u; + } + } + } + + if (lowestScoredUnit == -1) + qCWarning(Backend) << Q_FUNC_INFO << "No free image units!"; + + return lowestScoredUnit; +} + + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h new file mode 100644 index 000000000..6d39f469b --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H +#define QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class GraphicsContext; +class GLTexture; +class ShaderImage; + +class Q_AUTOTEST_EXPORT ImageSubmissionContext +{ +public: + ImageSubmissionContext(); + + void initialize(GraphicsContext *context); + void endDrawing(); + int activateImage(ShaderImage *image, GLTexture *tex); + void deactivateImages(); + +private: + void decayImageScores(); + int assignUnitForImage(Qt3DCore::QNodeId shaderImageId); + + struct ActiveImage + { + Qt3DCore::QNodeId shaderImageId; + GLTexture *texture = nullptr; + int score = 0; + bool pinned = false; + }; + QVector m_activeImages; + GraphicsContext *m_ctx; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h b/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h new file mode 100644 index 000000000..efc952ea5 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h @@ -0,0 +1,410 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H +#define QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { + +const int QMatrix2x2Type = qMetaTypeId(); +const int QMatrix2x3Type = qMetaTypeId(); +const int QMatrix2x4Type = qMetaTypeId(); +const int QMatrix3x2Type = qMetaTypeId(); +const int QMatrix3x3Type = qMetaTypeId(); +const int QMatrix3x4Type = qMetaTypeId(); +const int QMatrix4x2Type = qMetaTypeId(); +const int QMatrix4x3Type = qMetaTypeId(); + +} + +class QGraphicsUtils +{ + +public: + + template + static const char *bytesFromVariant(const QVariant &v) + { + uint byteSize = sizeof(T); + // Max 16 float that we may want as doubles + // 64 should be best for most cases + static QVarLengthArray array(16 * byteSize); + memset(array.data(), 0, array.size()); + + switch (static_cast(v.type())) { + + // 1 byte + case QMetaType::Bool: { + T data = v.value(); + memcpy(array.data(), &data, byteSize); + break; + } + case QMetaType::Char: { + T data = v.value(); + memcpy(array.data(), &data, byteSize); + break; + } + + // 4 bytes + case QMetaType::Float: { + T data = v.value(); + memcpy(array.data(), &data, byteSize); + break; + } + case QMetaType::Int: { + T data = v.value(); + memcpy(array.data(), &data, byteSize); + break; + + } + case QMetaType::UInt: { + qDebug() << "UINT"; + T data = v.value(); + memcpy(array.data(), &data, byteSize); + break; + } + + // 8 bytes + case QMetaType::Double: { + T data = v.value(); + memcpy(array.data(), &data, byteSize); + break; + } + + // 2 floats + case QMetaType::QPointF: { + QPointF vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + break; + } + case QMetaType::QSizeF: { + QSizeF vv = v.value(); + T data = vv.width(); + memcpy(array.data(), &data, byteSize); + data = vv.height(); + memcpy(array.data() + byteSize, &data, byteSize); + break; + } + + case QMetaType::QVector2D: { + QVector2D vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + break; + } + + // 2 ints + case QMetaType::QPoint: { + QPointF vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + break; + } + + case QMetaType::QSize: { + QSize vv = v.value(); + T data = vv.width(); + memcpy(array.data(), &data, byteSize); + data = vv.height(); + memcpy(array.data() + byteSize, &data, byteSize); + break; + } + + // 3 floats + case QMetaType::QVector3D: { + QVector3D vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + data = vv.z(); + memcpy(array.data() + 2 * byteSize, &data, byteSize); + break; + } + + // 4 floats + case QMetaType::QVector4D: { + QVector4D vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + data = vv.z(); + memcpy(array.data() + 2 * byteSize, &data, byteSize); + data = vv.w(); + memcpy(array.data() + 3 * byteSize, &data, byteSize); + break; + } + + case QMetaType::QQuaternion: { + + break; + } + + case QMetaType::QRectF: { + QRectF vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + data = vv.width(); + memcpy(array.data() + 2 * byteSize, &data, byteSize); + data = vv.height(); + memcpy(array.data() + 3 * byteSize, &data, byteSize); + break; + } + + case QMetaType::QColor: { + QColor vv = v.value(); + T data = vv.redF(); + memcpy(array.data(), &data, byteSize); + data = vv.greenF(); + memcpy(array.data() + byteSize, &data, byteSize); + data = vv.blueF(); + memcpy(array.data() + 2 * byteSize, &data, byteSize); + data = vv.alphaF(); + memcpy(array.data() + 3 * byteSize, &data, byteSize); + break; + } + + // 4 ints + case QMetaType::QRect: { + QRectF vv = v.value(); + T data = vv.x(); + memcpy(array.data(), &data, byteSize); + data = vv.y(); + memcpy(array.data() + byteSize, &data, byteSize); + data = vv.width(); + memcpy(array.data() + 2 * byteSize, &data, byteSize); + data = vv.height(); + memcpy(array.data() + 3 * byteSize, &data, byteSize); + break; + } + + // 16 floats + case QMetaType::QMatrix4x4: { + QMatrix4x4 mat = v.value(); + float *data = mat.data(); + for (int i = 0; i < 16; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + break; + } + + default: { + + float *data = nullptr; + if (v.userType() == QMatrix3x3Type) { + QMatrix3x3 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 9; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix2x2Type) { + QMatrix2x2 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 4; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix2x3Type) { + QMatrix2x3 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 6; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix3x2Type) { + QMatrix3x2 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 6; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix2x4Type) { + QMatrix2x4 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 8; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix4x2Type) { + QMatrix4x2 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 8; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix3x4Type) { + QMatrix3x4 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 12; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else if (v.userType() == QMatrix4x3Type) { + QMatrix4x3 mat = v.value(); + data = mat.data(); + for (int i = 0; i < 12; i++) { + T d = data[i]; + memcpy(array.data() + i * byteSize, &d, byteSize); + } + } + else + qWarning() << Q_FUNC_INFO << "QVariant type conversion not handled for " << v.type(); + break; + } + + } + return array.constData(); + } + + + template + static const T *valueArrayFromVariant(const QVariant &v, int count, int tupleSize) + { + uint byteSize = sizeof(T); + uint offset = byteSize * tupleSize; + static QVarLengthArray uniformValuesArray(1024); + uniformValuesArray.resize(count * offset); + char *data = uniformValuesArray.data(); + memset(data, 0, uniformValuesArray.size()); + + QVariantList vList = v.toList(); + // Handles list of QVariant: usually arrays of float + if (!vList.isEmpty()) { + for (int i = 0; i < vList.length() && uint(i) * offset < uint(uniformValuesArray.size()); i++) { + const char *subBuffer = QGraphicsUtils::bytesFromVariant(vList.at(i)); + memcpy(data + i * offset, subBuffer, offset); + } + } + else { + memcpy(data, QGraphicsUtils::bytesFromVariant(v), offset); + } + return reinterpret_cast(uniformValuesArray.constData()); + } + + template + static void fillDataArray(void *buffer, const T *data, const ShaderUniform &description, int tupleSize) + { + uint offset = description.m_offset / sizeof(T); + uint stride = description.m_arrayStride / sizeof(T); + T *bufferData = (T*)buffer; + + for (int i = 0; i < description.m_size; ++i) { + for (int j = 0; j < tupleSize; j++) { + int idx = i * tupleSize + j; + bufferData[offset + j] = data[idx]; + } + offset += stride; + } + } + + template + static void fillDataMatrixArray(void *buffer, const T *data, const ShaderUniform &description, int cols, int rows) + { + uint offset = description.m_offset / sizeof(T); + uint arrayStride = description.m_arrayStride / sizeof(T); + uint matrixStride = description.m_matrixStride / sizeof(T); + T *bufferData = (T*)buffer; + + for (int i = 0; i < description.m_size; ++i) { + for (int col = 0; col < cols; ++col) { + for (int row = 0; row < rows; ++row) { + int idx = i * cols * rows + rows * col + row; + bufferData[offset + row] = data[idx]; + } + offset += matrixStride; + } + offset += arrayStride; + } + } + +}; + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp new file mode 100644 index 000000000..9501b0b52 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp @@ -0,0 +1,1574 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "submissioncontext_p.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(QT_OPENGL_ES_2) +#include +#include +#include +#include +#include +#include +#include +#include +#endif +#include +#include + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +#ifndef GL_READ_FRAMEBUFFER +#define GL_READ_FRAMEBUFFER 0x8CA8 +#endif + +#ifndef GL_DRAW_FRAMEBUFFER +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#endif + +namespace Qt3DRender { +namespace Render { + + +static QHash static_contexts; + +unsigned int nextFreeContextId() +{ + for (unsigned int i=0; i < 0xffff; ++i) { + if (!static_contexts.contains(i)) + return i; + } + + qFatal("Couldn't find free context ID"); + return 0; +} + +namespace { + +GLBuffer::Type attributeTypeToGLBufferType(QAttribute::AttributeType type) +{ + switch (type) { + case QAttribute::VertexAttribute: + return GLBuffer::ArrayBuffer; + case QAttribute::IndexAttribute: + return GLBuffer::IndexBuffer; + case QAttribute::DrawIndirectAttribute: + return GLBuffer::DrawIndirectBuffer; + default: + Q_UNREACHABLE(); + } +} + +void copyGLFramebufferDataToImage(QImage &img, const uchar *srcData, uint stride, uint width, uint height, QAbstractTexture::TextureFormat format) +{ + switch (format) { + case QAbstractTexture::RGBA32F: + { + uchar *srcScanline = (uchar *)srcData + stride * (height - 1); + for (uint i = 0; i < height; ++i) { + uchar *dstScanline = img.scanLine(i); + float *pSrc = (float*)srcScanline; + for (uint j = 0; j < width; j++) { + *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+2], 1.0f)); + *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+1], 1.0f)); + *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+0], 1.0f)); + *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+3], 1.0f)); + } + srcScanline -= stride; + } + } break; + default: + { + uchar* srcScanline = (uchar *)srcData + stride * (height - 1); + for (uint i = 0; i < height; ++i) { + memcpy(img.scanLine(i), srcScanline, stride); + srcScanline -= stride; + } + } break; + } +} + +// Render States Helpers +template +void applyStateHelper(const GenericState *state, SubmissionContext *gc) +{ + Q_UNUSED(state); + Q_UNUSED(gc); +} + +template<> +void applyStateHelper(const AlphaFunc *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->alphaTest(std::get<0>(values), std::get<1>(values)); +} + +template<> +void applyStateHelper(const BlendEquationArguments *state, SubmissionContext *gc) +{ + const auto values = state->values(); + // Un-indexed BlendEquationArguments -> Use normal GL1.0 functions + if (std::get<5>(values) < 0) { + if (std::get<4>(values)) { + gc->openGLContext()->functions()->glEnable(GL_BLEND); + gc->openGLContext()->functions()->glBlendFuncSeparate(std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); + } else { + gc->openGLContext()->functions()->glDisable(GL_BLEND); + } + } + // BlendEquationArguments for a particular Draw Buffer. Different behaviours for + // (1) 3.0-3.3: only enablei/disablei supported. + // (2) 4.0+: all operations supported. + // We just ignore blend func parameter for (1), so no warnings get + // printed. + else { + if (std::get<4>(values)) { + gc->enablei(GL_BLEND, std::get<5>(values)); + if (gc->supportsDrawBuffersBlend()) { + gc->blendFuncSeparatei(std::get<5>(values), std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); + } + } else { + gc->disablei(GL_BLEND, std::get<5>(values)); + } + } +} + +template<> +void applyStateHelper(const BlendEquation *state, SubmissionContext *gc) +{ + gc->blendEquation(std::get<0>(state->values())); +} + +template<> +void applyStateHelper(const MSAAEnabled *state, SubmissionContext *gc) +{ + gc->setMSAAEnabled(std::get<0>(state->values())); +} + +template<> +void applyStateHelper(const DepthRange *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->depthRange(std::get<0>(values), std::get<1>(values)); +} + +template<> +void applyStateHelper(const DepthTest *state, SubmissionContext *gc) +{ + gc->depthTest(std::get<0>(state->values())); +} + +template<> +void applyStateHelper(const RasterMode *state, SubmissionContext *gc) +{ + gc->rasterMode(std::get<0>(state->values()), std::get<1>(state->values())); +} + +template<> +void applyStateHelper(const NoDepthMask *state, SubmissionContext *gc) +{ + gc->depthMask(std::get<0>(state->values())); +} + +template<> +void applyStateHelper(const CullFace *state, SubmissionContext *gc) +{ + const auto values = state->values(); + if (std::get<0>(values) == QCullFace::NoCulling) { + gc->openGLContext()->functions()->glDisable(GL_CULL_FACE); + } else { + gc->openGLContext()->functions()->glEnable(GL_CULL_FACE); + gc->openGLContext()->functions()->glCullFace(std::get<0>(values)); + } +} + +template<> +void applyStateHelper(const FrontFace *state, SubmissionContext *gc) +{ + gc->frontFace(std::get<0>(state->values())); +} + +template<> +void applyStateHelper(const ScissorTest *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->openGLContext()->functions()->glEnable(GL_SCISSOR_TEST); + gc->openGLContext()->functions()->glScissor(std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); +} + +template<> +void applyStateHelper(const StencilTest *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->openGLContext()->functions()->glEnable(GL_STENCIL_TEST); + gc->openGLContext()->functions()->glStencilFuncSeparate(GL_FRONT, std::get<0>(values), std::get<1>(values), std::get<2>(values)); + gc->openGLContext()->functions()->glStencilFuncSeparate(GL_BACK, std::get<3>(values), std::get<4>(values), std::get<5>(values)); +} + +template<> +void applyStateHelper(const AlphaCoverage *, SubmissionContext *gc) +{ + gc->setAlphaCoverageEnabled(true); +} + +template<> +void applyStateHelper(const PointSize *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->pointSize(std::get<0>(values), std::get<1>(values)); +} + + +template<> +void applyStateHelper(const PolygonOffset *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->openGLContext()->functions()->glEnable(GL_POLYGON_OFFSET_FILL); + gc->openGLContext()->functions()->glPolygonOffset(std::get<0>(values), std::get<1>(values)); +} + +template<> +void applyStateHelper(const ColorMask *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->openGLContext()->functions()->glColorMask(std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); +} + +template<> +void applyStateHelper(const ClipPlane *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->enableClipPlane(std::get<0>(values)); + gc->setClipPlane(std::get<0>(values), std::get<1>(values), std::get<2>(values)); +} + +template<> +void applyStateHelper(const SeamlessCubemap *, SubmissionContext *gc) +{ + gc->setSeamlessCubemap(true); +} + +template<> +void applyStateHelper(const StencilOp *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->openGLContext()->functions()->glStencilOpSeparate(GL_FRONT, std::get<0>(values), std::get<1>(values), std::get<2>(values)); + gc->openGLContext()->functions()->glStencilOpSeparate(GL_BACK, std::get<3>(values), std::get<4>(values), std::get<5>(values)); +} + +template<> +void applyStateHelper(const StencilMask *state, SubmissionContext *gc) +{ + const auto values = state->values(); + gc->openGLContext()->functions()->glStencilMaskSeparate(GL_FRONT, std::get<0>(values)); + gc->openGLContext()->functions()->glStencilMaskSeparate(GL_BACK, std::get<1>(values)); +} + +template<> +void applyStateHelper(const Dithering *, SubmissionContext *gc) +{ + gc->openGLContext()->functions()->glEnable(GL_DITHER); +} + +#ifndef GL_LINE_SMOOTH +#define GL_LINE_SMOOTH 0x0B20 +#endif + +template<> +void applyStateHelper(const LineWidth *state, SubmissionContext *gc) +{ + const auto values = state->values(); + if (std::get<1>(values)) + gc->openGLContext()->functions()->glEnable(GL_LINE_SMOOTH); + else + gc->openGLContext()->functions()->glDisable(GL_LINE_SMOOTH); + + gc->openGLContext()->functions()->glLineWidth(std::get<0>(values)); +} + +} // anonymous + + +SubmissionContext::SubmissionContext() + : GraphicsContext() + , m_ownCurrent(true) + , m_id(nextFreeContextId()) + , m_surface(nullptr) + , m_activeShader(nullptr) + , m_renderTargetFormat(QAbstractTexture::NoFormat) + , m_currClearStencilValue(0) + , m_currClearDepthValue(1.f) + , m_currClearColorValue(0,0,0,0) + , m_material(nullptr) + , m_activeFBO(0) + , m_boundArrayBuffer(nullptr) + , m_stateSet(nullptr) + , m_renderer(nullptr) + , m_uboTempArray(QByteArray(1024, 0)) +{ + static_contexts[m_id] = this; +} + +SubmissionContext::~SubmissionContext() +{ + releaseOpenGL(); + + Q_ASSERT(static_contexts[m_id] == this); + static_contexts.remove(m_id); +} + +void SubmissionContext::initialize() +{ + GraphicsContext::initialize(); + m_textureContext.initialize(this); + m_imageContext.initialize(this); +} + +void SubmissionContext::resolveRenderTargetFormat() +{ + const QSurfaceFormat format = m_gl->format(); + const uint a = (format.alphaBufferSize() == -1) ? 0 : format.alphaBufferSize(); + const uint r = format.redBufferSize(); + const uint g = format.greenBufferSize(); + const uint b = format.blueBufferSize(); + +#define RGBA_BITS(r,g,b,a) (r | (g << 6) | (b << 12) | (a << 18)) + + const uint bits = RGBA_BITS(r,g,b,a); + switch (bits) { + case RGBA_BITS(8,8,8,8): + m_renderTargetFormat = QAbstractTexture::RGBA8_UNorm; + break; + case RGBA_BITS(8,8,8,0): + m_renderTargetFormat = QAbstractTexture::RGB8_UNorm; + break; + case RGBA_BITS(5,6,5,0): + m_renderTargetFormat = QAbstractTexture::R5G6B5; + break; + } +#undef RGBA_BITS +} + +bool SubmissionContext::beginDrawing(QSurface *surface) +{ + Q_ASSERT(surface); + Q_ASSERT(m_gl); + + m_surface = surface; + + // TO DO: Find a way to make to pause work if the window is not exposed + // if (m_surface && m_surface->surfaceClass() == QSurface::Window) { + // qDebug() << Q_FUNC_INFO << 1; + // if (!static_cast(m_surface)->isExposed()) + // return false; + // qDebug() << Q_FUNC_INFO << 2; + // } + + // Makes the surface current on the OpenGLContext + // and sets the right glHelper + m_ownCurrent = !(m_gl->surface() == m_surface); + if (m_ownCurrent && !makeCurrent(m_surface)) + return false; + + // TODO: cache surface format somewhere rather than doing this every time render surface changes + resolveRenderTargetFormat(); + +#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) + GLint err = m_gl->functions()->glGetError(); + if (err != 0) { + qCWarning(Backend) << Q_FUNC_INFO << "glGetError:" << err; + } +#endif + + if (!isInitialized()) + initialize(); + initializeHelpers(m_surface); + + // need to reset these values every frame, may get overwritten elsewhere + m_gl->functions()->glClearColor(m_currClearColorValue.redF(), m_currClearColorValue.greenF(), m_currClearColorValue.blueF(), m_currClearColorValue.alphaF()); + m_gl->functions()->glClearDepthf(m_currClearDepthValue); + m_gl->functions()->glClearStencil(m_currClearStencilValue); + + if (m_activeShader) { + m_activeShader = nullptr; + } + + m_boundArrayBuffer = nullptr; + return true; +} + +void SubmissionContext::endDrawing(bool swapBuffers) +{ + if (swapBuffers) + m_gl->swapBuffers(m_surface); + if (m_ownCurrent) + m_gl->doneCurrent(); + m_textureContext.endDrawing(); + m_imageContext.endDrawing(); +} + +void SubmissionContext::activateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, GLuint defaultFboId) +{ + GLuint fboId = defaultFboId; // Default FBO + if (renderTargetNodeId) { + // New RenderTarget + if (!m_renderTargets.contains(renderTargetNodeId)) { + if (m_defaultFBO && fboId == m_defaultFBO) { + // this is the default fbo that some platforms create (iOS), we just register it + // Insert FBO into hash + m_renderTargets.insert(renderTargetNodeId, fboId); + } else { + fboId = createRenderTarget(renderTargetNodeId, attachments); + } + } else { + fboId = updateRenderTarget(renderTargetNodeId, attachments, true); + } + } + m_activeFBO = fboId; + m_glHelper->bindFrameBufferObject(m_activeFBO, GraphicsHelperInterface::FBODraw); + // Set active drawBuffers + activateDrawBuffers(attachments); +} + +GLuint SubmissionContext::createRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments) +{ + const GLuint fboId = m_glHelper->createFrameBufferObject(); + if (fboId) { + // The FBO is created and its attachments are set once + // Insert FBO into hash + m_renderTargets.insert(renderTargetNodeId, fboId); + // Bind FBO + m_glHelper->bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); + bindFrameBufferAttachmentHelper(fboId, attachments); + } else { + qCritical("Failed to create FBO"); + } + return fboId; +} + +GLuint SubmissionContext::updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, bool isActiveRenderTarget) +{ + const GLuint fboId = m_renderTargets.value(renderTargetNodeId); + + // We need to check if one of the attachment was resized + bool needsResize = !m_renderTargetsSize.contains(fboId); // not even initialized yet? + if (!needsResize) { + // render target exists, has attachment been resized? + GLTextureManager *glTextureManager = m_renderer->glResourceManagers()->glTextureManager(); + const QSize s = m_renderTargetsSize[fboId]; + const auto attachments_ = attachments.attachments(); + for (const Attachment &attachment : attachments_) { + GLTexture *rTex = glTextureManager->lookupResource(attachment.m_textureUuid); + // ### TODO QTBUG-64757 this check is insufficient since the + // texture may have changed to another one with the same size. That + // case is not handled atm. + if (rTex) { + needsResize |= rTex->size() != s; + if (isActiveRenderTarget && attachment.m_point == QRenderTargetOutput::Color0) + m_renderTargetFormat = rTex->properties().format; + } + } + } + + if (needsResize) { + m_glHelper->bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); + bindFrameBufferAttachmentHelper(fboId, attachments); + } + + return fboId; +} + +QSize SubmissionContext::renderTargetSize(const QSize &surfaceSize) const +{ + QSize renderTargetSize; + if (m_activeFBO != m_defaultFBO) { + // For external FBOs we may not have a m_renderTargets entry. + if (m_renderTargetsSize.contains(m_activeFBO)) { + renderTargetSize = m_renderTargetsSize[m_activeFBO]; + } else if (surfaceSize.isValid()) { + renderTargetSize = surfaceSize; + } else { + // External FBO (when used with QtQuick2 Scene3D) + + // Query FBO color attachment 0 size + GLint attachmentObjectType = GL_NONE; + GLint attachment0Name = 0; + m_gl->functions()->glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, + &attachmentObjectType); + m_gl->functions()->glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, + &attachment0Name); + + if (attachmentObjectType == GL_RENDERBUFFER && m_glHelper->supportsFeature(GraphicsHelperInterface::RenderBufferDimensionRetrieval)) + renderTargetSize = m_glHelper->getRenderBufferDimensions(attachment0Name); + else if (attachmentObjectType == GL_TEXTURE && m_glHelper->supportsFeature(GraphicsHelperInterface::TextureDimensionRetrieval)) + // Assumes texture level 0 and GL_TEXTURE_2D target + renderTargetSize = m_glHelper->getTextureDimensions(attachment0Name, GL_TEXTURE_2D); + else + return renderTargetSize; + } + } else { + renderTargetSize = m_surface->size(); + if (m_surface->surfaceClass() == QSurface::Window) { + const float dpr = static_cast(m_surface)->devicePixelRatio(); + renderTargetSize *= dpr; + } + } + return renderTargetSize; +} + +QImage SubmissionContext::readFramebuffer(const QRect &rect) +{ + QImage img; + const unsigned int area = rect.width() * rect.height(); + unsigned int bytes; + GLenum format, type; + QImage::Format imageFormat; + uint stride; + + /* format value should match GL internalFormat */ + GLenum internalFormat = m_renderTargetFormat; + + switch (m_renderTargetFormat) { + case QAbstractTexture::RGBAFormat: + case QAbstractTexture::RGBA8_SNorm: + case QAbstractTexture::RGBA8_UNorm: + case QAbstractTexture::RGBA8U: + case QAbstractTexture::SRGB8_Alpha8: +#ifdef QT_OPENGL_ES_2 + format = GL_RGBA; + imageFormat = QImage::Format_RGBA8888_Premultiplied; +#else + format = GL_BGRA; + imageFormat = QImage::Format_ARGB32_Premultiplied; + internalFormat = GL_RGBA8; +#endif + type = GL_UNSIGNED_BYTE; + bytes = area * 4; + stride = rect.width() * 4; + break; + case QAbstractTexture::SRGB8: + case QAbstractTexture::RGBFormat: + case QAbstractTexture::RGB8U: + case QAbstractTexture::RGB8_UNorm: +#ifdef QT_OPENGL_ES_2 + format = GL_RGBA; + imageFormat = QImage::Format_RGBX8888; +#else + format = GL_BGRA; + imageFormat = QImage::Format_RGB32; + internalFormat = GL_RGB8; +#endif + type = GL_UNSIGNED_BYTE; + bytes = area * 4; + stride = rect.width() * 4; + break; +#ifndef QT_OPENGL_ES_2 + case QAbstractTexture::RG11B10F: + bytes = area * 4; + format = GL_RGB; + type = GL_UNSIGNED_INT_10F_11F_11F_REV; + imageFormat = QImage::Format_RGB30; + stride = rect.width() * 4; + break; + case QAbstractTexture::RGB10A2: + bytes = area * 4; + format = GL_RGBA; + type = GL_UNSIGNED_INT_2_10_10_10_REV; + imageFormat = QImage::Format_A2BGR30_Premultiplied; + stride = rect.width() * 4; + break; + case QAbstractTexture::R5G6B5: + bytes = area * 2; + format = GL_RGB; + type = GL_UNSIGNED_SHORT; + internalFormat = GL_UNSIGNED_SHORT_5_6_5_REV; + imageFormat = QImage::Format_RGB16; + stride = rect.width() * 2; + break; + case QAbstractTexture::RGBA16F: + case QAbstractTexture::RGBA16U: + case QAbstractTexture::RGBA32F: + case QAbstractTexture::RGBA32U: + bytes = area * 16; + format = GL_RGBA; + type = GL_FLOAT; + imageFormat = QImage::Format_ARGB32_Premultiplied; + stride = rect.width() * 16; + break; +#endif + default: + auto warning = qWarning(); + warning << "Unable to convert"; + QtDebugUtils::formatQEnum(warning, m_renderTargetFormat); + warning << "render target texture format to QImage."; + return img; + } + + GLint samples = 0; + m_gl->functions()->glGetIntegerv(GL_SAMPLES, &samples); + if (samples > 0 && !m_glHelper->supportsFeature(GraphicsHelperInterface::BlitFramebuffer)) { + qCWarning(Backend) << Q_FUNC_INFO << "Unable to capture multisampled framebuffer; " + "Required feature BlitFramebuffer is missing."; + return img; + } + + img = QImage(rect.width(), rect.height(), imageFormat); + + QScopedArrayPointer data(new uchar [bytes]); + + if (samples > 0) { + // resolve multisample-framebuffer to renderbuffer and read pixels from it + GLuint fbo, rb; + QOpenGLFunctions *gl = m_gl->functions(); + gl->glGenFramebuffers(1, &fbo); + gl->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); + gl->glGenRenderbuffers(1, &rb); + gl->glBindRenderbuffer(GL_RENDERBUFFER, rb); + gl->glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, rect.width(), rect.height()); + gl->glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb); + + const GLenum status = gl->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + gl->glDeleteRenderbuffers(1, &rb); + gl->glDeleteFramebuffers(1, &fbo); + qCWarning(Backend) << Q_FUNC_INFO << "Copy-framebuffer not complete: " << status; + return img; + } + + m_glHelper->blitFramebuffer(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height(), + 0, 0, rect.width(), rect.height(), + GL_COLOR_BUFFER_BIT, GL_NEAREST); + gl->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); + gl->glReadPixels(0,0,rect.width(), rect.height(), format, type, data.data()); + + copyGLFramebufferDataToImage(img, data.data(), stride, rect.width(), rect.height(), m_renderTargetFormat); + + gl->glBindRenderbuffer(GL_RENDERBUFFER, rb); + gl->glDeleteRenderbuffers(1, &rb); + gl->glBindFramebuffer(GL_FRAMEBUFFER, m_activeFBO); + gl->glDeleteFramebuffers(1, &fbo); + } else { + // read pixels directly from framebuffer + m_gl->functions()->glReadPixels(rect.x(), rect.y(), rect.width(), rect.height(), format, type, data.data()); + copyGLFramebufferDataToImage(img, data.data(), stride, rect.width(), rect.height(), m_renderTargetFormat); + } + + return img; +} + +void SubmissionContext::setViewport(const QRectF &viewport, const QSize &surfaceSize) +{ + // // save for later use; this has nothing to do with the viewport but it is + // // here that we get to know the surfaceSize from the RenderView. + m_surfaceSize = surfaceSize; + + m_viewport = viewport; + QSize size = renderTargetSize(surfaceSize); + + // Check that the returned size is before calling glViewport + if (size.isEmpty()) + return; + + // Qt3D 0------------------> 1 OpenGL 1^ + // | | + // | | + // | | + // V | + // 1 0---------------------> 1 + // The Viewport is defined between 0 and 1 which allows us to automatically + // scale to the size of the provided window surface + m_gl->functions()->glViewport(m_viewport.x() * size.width(), + (1.0 - m_viewport.y() - m_viewport.height()) * size.height(), + m_viewport.width() * size.width(), + m_viewport.height() * size.height()); +} + +void SubmissionContext::releaseOpenGL() +{ + m_renderBufferHash.clear(); + + // Stop and destroy the OpenGL logger + if (m_debugLogger) { + m_debugLogger->stopLogging(); + m_debugLogger.reset(nullptr); + } +} + +// The OpenGLContext is not current on any surface at this point +void SubmissionContext::setOpenGLContext(QOpenGLContext* ctx) +{ + Q_ASSERT(ctx); + + releaseOpenGL(); + m_gl = ctx; +} + +// Called only from RenderThread +bool SubmissionContext::activateShader(GLShader *shader) +{ + if (shader->shaderProgram() != m_activeShader) { + // Ensure material uniforms are re-applied + m_material = nullptr; + + m_activeShader = shader->shaderProgram(); + if (Q_LIKELY(m_activeShader != nullptr)) { + m_activeShader->bind(); + } else { + m_glHelper->useProgram(0); + qWarning() << "No shader program found"; + return false; + } + } + return true; +} + +void SubmissionContext::bindFrameBufferAttachmentHelper(GLuint fboId, const AttachmentPack &attachments) +{ + // Set FBO attachments. These are normally textures, except that on Open GL + // ES <= 3.1 we must use a renderbuffer if a combined depth+stencil is + // desired since this cannot be achieved neither with a single texture (not + // before GLES 3.2) nor with separate textures (no suitable format for + // stencil before 3.1 with the appropriate extension). + + QSize fboSize; + GLTextureManager *glTextureManager = m_renderer->glResourceManagers()->glTextureManager(); + const auto attachments_ = attachments.attachments(); + for (const Attachment &attachment : attachments_) { + GLTexture *rTex = glTextureManager->lookupResource(attachment.m_textureUuid); + if (!m_glHelper->frameBufferNeedsRenderBuffer(attachment)) { + QOpenGLTexture *glTex = rTex ? rTex->getGLTexture() : nullptr; + if (glTex != nullptr) { + // The texture can not be rendered simultaniously by another renderer + Q_ASSERT(!rTex->isExternalRenderingEnabled()); + if (fboSize.isEmpty()) + fboSize = QSize(glTex->width(), glTex->height()); + else + fboSize = QSize(qMin(fboSize.width(), glTex->width()), qMin(fboSize.height(), glTex->height())); + m_glHelper->bindFrameBufferAttachment(glTex, attachment); + } + } else { + RenderBuffer *renderBuffer = rTex ? rTex->getOrCreateRenderBuffer() : nullptr; + if (renderBuffer) { + if (fboSize.isEmpty()) + fboSize = QSize(renderBuffer->width(), renderBuffer->height()); + else + fboSize = QSize(qMin(fboSize.width(), renderBuffer->width()), qMin(fboSize.height(), renderBuffer->height())); + m_glHelper->bindFrameBufferAttachment(renderBuffer, attachment); + } + } + } + m_renderTargetsSize.insert(fboId, fboSize); +} + +void SubmissionContext::activateDrawBuffers(const AttachmentPack &attachments) +{ + const QVector activeDrawBuffers = attachments.getGlDrawBuffers(); + + if (m_glHelper->checkFrameBufferComplete()) { + if (activeDrawBuffers.size() > 1) {// We need MRT + if (m_glHelper->supportsFeature(GraphicsHelperInterface::MRT)) { + // Set up MRT, glDrawBuffers... + m_glHelper->drawBuffers(activeDrawBuffers.size(), activeDrawBuffers.data()); + } + } + } else { + qCWarning(Backend) << "FBO incomplete"; + } +} + + +void SubmissionContext::setActiveMaterial(Material *rmat) +{ + if (m_material == rmat) + return; + + m_textureContext.deactivateTexturesWithScope(TextureSubmissionContext::TextureScopeMaterial); + m_imageContext.deactivateImages(); + m_material = rmat; +} + +void SubmissionContext::setCurrentStateSet(RenderStateSet *ss) +{ + if (ss == m_stateSet) + return; + if (ss) + applyStateSet(ss); + m_stateSet = ss; +} + +RenderStateSet *SubmissionContext::currentStateSet() const +{ + return m_stateSet; +} + +void SubmissionContext::applyState(const StateVariant &stateVariant) +{ + switch (stateVariant.type) { + + case AlphaCoverageStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + case AlphaTestMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + case BlendStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + case BlendEquationArgumentsMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + case MSAAEnabledStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case CullFaceStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case DepthWriteStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case DepthTestStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case DepthRangeMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case RasterModeMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case FrontFaceStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case ScissorStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case StencilTestStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case PointSizeMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case PolygonOffsetStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case ColorStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case ClipPlaneMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case SeamlessCubemapMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case StencilOpMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case StencilWriteStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case DitheringStateMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + + case LineWidthMask: { + applyStateHelper(static_cast(stateVariant.constState()), this); + break; + } + default: + Q_UNREACHABLE(); + } +} + +void SubmissionContext::resetMasked(qint64 maskOfStatesToReset) +{ + // TO DO -> Call gcHelper methods instead of raw GL + // QOpenGLFunctions shouldn't be used here directly + QOpenGLFunctions *funcs = m_gl->functions(); + + if (maskOfStatesToReset & ScissorStateMask) + funcs->glDisable(GL_SCISSOR_TEST); + + if (maskOfStatesToReset & BlendStateMask) + funcs->glDisable(GL_BLEND); + + if (maskOfStatesToReset & StencilWriteStateMask) + funcs->glStencilMask(0); + + if (maskOfStatesToReset & StencilTestStateMask) + funcs->glDisable(GL_STENCIL_TEST); + + if (maskOfStatesToReset & DepthRangeMask) + depthRange(0.0f, 1.0f); + + if (maskOfStatesToReset & DepthTestStateMask) + funcs->glDisable(GL_DEPTH_TEST); + + if (maskOfStatesToReset & DepthWriteStateMask) + funcs->glDepthMask(GL_TRUE); // reset to default + + if (maskOfStatesToReset & FrontFaceStateMask) + funcs->glFrontFace(GL_CCW); // reset to default + + if (maskOfStatesToReset & CullFaceStateMask) + funcs->glDisable(GL_CULL_FACE); + + if (maskOfStatesToReset & DitheringStateMask) + funcs->glDisable(GL_DITHER); + + if (maskOfStatesToReset & AlphaCoverageStateMask) + setAlphaCoverageEnabled(false); + + if (maskOfStatesToReset & PointSizeMask) + pointSize(false, 1.0f); // reset to default + + if (maskOfStatesToReset & PolygonOffsetStateMask) + funcs->glDisable(GL_POLYGON_OFFSET_FILL); + + if (maskOfStatesToReset & ColorStateMask) + funcs->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + + if (maskOfStatesToReset & ClipPlaneMask) { + GLint max = maxClipPlaneCount(); + for (GLint i = 0; i < max; ++i) + disableClipPlane(i); + } + + if (maskOfStatesToReset & SeamlessCubemapMask) + setSeamlessCubemap(false); + + if (maskOfStatesToReset & StencilOpMask) + funcs->glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); + + if (maskOfStatesToReset & LineWidthMask) + funcs->glLineWidth(1.0f); + +#ifndef QT_OPENGL_ES_2 + if (maskOfStatesToReset & RasterModeMask) + m_glHelper->rasterMode(GL_FRONT_AND_BACK, GL_FILL); +#endif +} + +void SubmissionContext::applyStateSet(RenderStateSet *ss) +{ + RenderStateSet* previousStates = currentStateSet(); + + const StateMaskSet invOurState = ~ss->stateMask(); + // generate a mask for each set bit in previous, where we do not have + // the corresponding bit set. + + StateMaskSet stateToReset = 0; + if (previousStates) { + stateToReset = previousStates->stateMask() & invOurState; + qCDebug(RenderStates) << "previous states " << QString::number(previousStates->stateMask(), 2); + } + qCDebug(RenderStates) << " current states " << QString::number(ss->stateMask(), 2) << "inverse " << QString::number(invOurState, 2) << " -> states to change: " << QString::number(stateToReset, 2); + + // Reset states that aren't active in the current state set + resetMasked(stateToReset); + + // Apply states that weren't in the previous state or that have + // different values + const QVector statesToSet = ss->states(); + for (const StateVariant &ds : statesToSet) { + if (previousStates && previousStates->contains(ds)) + continue; + applyState(ds); + } +} + +void SubmissionContext::clearColor(const QColor &color) +{ + if (m_currClearColorValue != color) { + m_currClearColorValue = color; + m_gl->functions()->glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); + } +} + +void SubmissionContext::clearDepthValue(float depth) +{ + if (m_currClearDepthValue != depth) { + m_currClearDepthValue = depth; + m_gl->functions()->glClearDepthf(depth); + } +} + +void SubmissionContext::clearStencilValue(int stencil) +{ + if (m_currClearStencilValue != stencil) { + m_currClearStencilValue = stencil; + m_gl->functions()->glClearStencil(stencil); + } +} + +GLFence SubmissionContext::fenceSync() +{ + return m_glHelper->fenceSync(); +} + +void SubmissionContext::clientWaitSync(GLFence sync, GLuint64 nanoSecTimeout) +{ + qDebug() << Q_FUNC_INFO << sync; + m_glHelper->clientWaitSync(sync, nanoSecTimeout); +} + +void SubmissionContext::waitSync(GLFence sync) +{ + qDebug() << Q_FUNC_INFO << sync; + m_glHelper->waitSync(sync); +} + +bool SubmissionContext::wasSyncSignaled(GLFence sync) +{ + return m_glHelper->wasSyncSignaled(sync); +} + +void SubmissionContext::deleteSync(GLFence sync) +{ + m_glHelper->deleteSync(sync); +} + +// It will be easier if the QGraphicContext applies the QUniformPack +// than the other way around +bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) +{ + static const int irradianceId = StringToInt::lookupId(QLatin1String("envLight.irradiance")); + static const int specularId = StringToInt::lookupId(QLatin1String("envLight.specular")); + // Activate textures and update TextureUniform in the pack + // with the correct textureUnit + + // Set the pinned texture of the previous material texture + // to pinable so that we should easily find an available texture unit + m_textureContext.deactivateTexturesWithScope(TextureSubmissionContext::TextureScopeMaterial); + // Update the uniforms with the correct texture unit id's + PackUniformHash &uniformValues = parameterPack.uniforms(); + + // Fill Texture Uniform Value with proper texture units + // so that they can be applied as regular uniforms in a second step + for (int i = 0; i < parameterPack.textures().size(); ++i) { + const ShaderParameterPack::NamedResource &namedTex = parameterPack.textures().at(i); + // Given a Texture QNodeId, we retrieve the associated shared GLTexture + if (uniformValues.contains(namedTex.glslNameId)) { + GLTexture *t = m_renderer->glResourceManagers()->glTextureManager()->lookupResource(namedTex.nodeId); + if (t != nullptr) { + UniformValue &texUniform = uniformValues.value(namedTex.glslNameId); + if (texUniform.valueType() == UniformValue::TextureValue) { + const int texUnit = m_textureContext.activateTexture(TextureSubmissionContext::TextureScopeMaterial, m_gl, t); + texUniform.data()[namedTex.uniformArrayIndex] = texUnit; + if (texUnit == -1) { + if (namedTex.glslNameId != irradianceId && + namedTex.glslNameId != specularId) { + // Only return false if we are not dealing with env light textures + qCWarning(Backend) << "Unable to find suitable Texture Unit"; + return false; + } + } + } + } + } + } + + // Fill Image Uniform Value with proper image units + // so that they can be applied as regular uniforms in a second step + for (int i = 0; i < parameterPack.images().size(); ++i) { + const ShaderParameterPack::NamedResource &namedTex = parameterPack.images().at(i); + // Given a Texture QNodeId, we retrieve the associated shared GLTexture + if (uniformValues.contains(namedTex.glslNameId)) { + ShaderImage *img = m_renderer->nodeManagers()->shaderImageManager()->lookupResource(namedTex.nodeId); + if (img != nullptr) { + GLTexture *t = m_renderer->glResourceManagers()->glTextureManager()->lookupResource(img->textureId()); + if (t == nullptr) { + qCWarning(Backend) << "Shader Image referencing invalid texture"; + continue; + } else { + UniformValue &imgUniform = uniformValues.value(namedTex.glslNameId); + if (imgUniform.valueType() == UniformValue::ShaderImageValue) { + const int imgUnit = m_imageContext.activateImage(img, t); + imgUniform.data()[namedTex.uniformArrayIndex] = imgUnit; + if (imgUnit == -1) { + qCWarning(Backend) << "Unable to bind Image to Texture"; + return false; + } + } + } + } + } + } + + QOpenGLShaderProgram *shader = activeShader(); + + // TO DO: We could cache the binding points somehow and only do the binding when necessary + // for SSBO and UBO + + // Bind Shader Storage block to SSBO and update SSBO + const QVector blockToSSBOs = parameterPack.shaderStorageBuffers(); + for (const BlockToSSBO b : blockToSSBOs) { + Buffer *cpuBuffer = m_renderer->nodeManagers()->bufferManager()->lookupResource(b.m_bufferID); + GLBuffer *ssbo = glBufferForRenderBuffer(cpuBuffer); + // bindShaderStorageBlock + // This is currently not required as we are introspecting the bindingIndex + // value from the shaders and not replacing them, making such a call useless + // bindShaderStorageBlock(shader->programId(), b.m_blockIndex, b.m_bindingIndex); + bindShaderStorageBlock(shader->programId(), b.m_blockIndex, b.m_bindingIndex); + // Needed to avoid conflict where the buffer would already + // be bound as a VertexArray + bindGLBuffer(ssbo, GLBuffer::ShaderStorageBuffer); + ssbo->bindBufferBase(this, b.m_bindingIndex, GLBuffer::ShaderStorageBuffer); + // TO DO: Make sure that there's enough binding points + } + + // Bind UniformBlocks to UBO and update UBO from Buffer + // TO DO: Convert ShaderData to Buffer so that we can use that generic process + const QVector blockToUBOs = parameterPack.uniformBuffers(); + int uboIndex = 0; + for (const BlockToUBO &b : blockToUBOs) { + Buffer *cpuBuffer = m_renderer->nodeManagers()->bufferManager()->lookupResource(b.m_bufferID); + GLBuffer *ubo = glBufferForRenderBuffer(cpuBuffer); + bindUniformBlock(shader->programId(), b.m_blockIndex, uboIndex); + // Needed to avoid conflict where the buffer would already + // be bound as a VertexArray + bindGLBuffer(ubo, GLBuffer::UniformBuffer); + ubo->bindBufferBase(this, uboIndex++, GLBuffer::UniformBuffer); + // TO DO: Make sure that there's enough binding points + } + + // Update uniforms in the Default Uniform Block + const PackUniformHash values = parameterPack.uniforms(); + const QVector activeUniforms = parameterPack.submissionUniforms(); + + for (const ShaderUniform &uniform : activeUniforms) { + // We can use [] as we are sure the the uniform wouldn't + // be un activeUniforms if there wasn't a matching value + const UniformValue &v = values.value(uniform.m_nameId); + + // skip invalid textures/images + if ((v.valueType() == UniformValue::TextureValue || + v.valueType() == UniformValue::ShaderImageValue) && + *v.constData() == -1) + continue; + + applyUniform(uniform, v); + } + // if not all data is valid, the next frame will be rendered immediately + return true; +} + +void SubmissionContext::enableAttribute(const VAOVertexAttribute &attr) +{ + // Bind buffer within the current VAO + GLBuffer *buf = m_renderer->glResourceManagers()->glBufferManager()->data(attr.bufferHandle); + Q_ASSERT(buf); + bindGLBuffer(buf, attr.attributeType); + + // Don't use QOpenGLShaderProgram::setAttributeBuffer() because of QTBUG-43199. + // Use the introspection data and set the attribute explicitly + m_glHelper->enableVertexAttributeArray(attr.location); + m_glHelper->vertexAttributePointer(attr.shaderDataType, + attr.location, + attr.vertexSize, + attr.dataType, + GL_TRUE, // TODO: Support normalization property on QAttribute + attr.byteStride, + reinterpret_cast(qintptr(attr.byteOffset))); + + + // Done by the helper if it supports it + if (attr.divisor != 0) + m_glHelper->vertexAttribDivisor(attr.location, attr.divisor); +} + +void SubmissionContext::disableAttribute(const SubmissionContext::VAOVertexAttribute &attr) +{ + QOpenGLShaderProgram *prog = activeShader(); + prog->disableAttributeArray(attr.location); +} + +// Note: needs to be called while VAO is bound +void SubmissionContext::specifyAttribute(const Attribute *attribute, + Buffer *buffer, + const ShaderAttribute *attributeDescription) +{ + const int location = attributeDescription->m_location; + if (location < 0) { + qCWarning(Backend) << "failed to resolve location for attribute:" << attribute->name(); + return; + } + + const GLint attributeDataType = glDataTypeFromAttributeDataType(attribute->vertexBaseType()); + const HGLBuffer glBufferHandle = m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); + Q_ASSERT(!glBufferHandle.isNull()); + const GLBuffer::Type attributeType = attributeTypeToGLBufferType(attribute->attributeType()); + + int typeSize = 0; + int attrCount = 0; + + if (attribute->vertexSize() >= 1 && attribute->vertexSize() <= 4) { + attrCount = 1; + } else if (attribute->vertexSize() == 9) { + typeSize = byteSizeFromType(attributeDataType); + attrCount = 3; + } else if (attribute->vertexSize() == 16) { + typeSize = byteSizeFromType(attributeDataType); + attrCount = 4; + } else { + Q_UNREACHABLE(); + } + + Q_ASSERT(!glBufferHandle.isNull()); + VAOVertexAttribute attr; + attr.bufferHandle = glBufferHandle; + attr.attributeType = attributeType; + attr.dataType = attributeDataType; + attr.divisor = attribute->divisor(); + attr.vertexSize = attribute->vertexSize() / attrCount; + attr.byteStride = (attribute->byteStride() != 0) ? attribute->byteStride() : (attrCount * attrCount * typeSize); + attr.shaderDataType = attributeDescription->m_type; + + for (int i = 0; i < attrCount; i++) { + attr.location = location + i; + attr.byteOffset = attribute->byteOffset() + (i * attrCount * typeSize); + + enableAttribute(attr); + + // Save this in the current emulated VAO + if (m_currentVAO) + m_currentVAO->saveVertexAttribute(attr); + } +} + +void SubmissionContext::specifyIndices(Buffer *buffer) +{ + GLBuffer *buf = glBufferForRenderBuffer(buffer); + if (!bindGLBuffer(buf, GLBuffer::IndexBuffer)) + qCWarning(Backend) << Q_FUNC_INFO << "binding index buffer failed"; + + // bound within the current VAO + // Save this in the current emulated VAO + if (m_currentVAO) + m_currentVAO->saveIndexAttribute(m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId())); +} + +void SubmissionContext::updateBuffer(Buffer *buffer) +{ + const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); + if (it != m_renderBufferHash.end()) + uploadDataToGLBuffer(buffer, m_renderer->glResourceManagers()->glBufferManager()->data(it.value())); +} + +QByteArray SubmissionContext::downloadBufferContent(Buffer *buffer) +{ + const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); + if (it != m_renderBufferHash.end()) + return downloadDataFromGLBuffer(buffer, m_renderer->glResourceManagers()->glBufferManager()->data(it.value())); + return QByteArray(); +} + +void SubmissionContext::releaseBuffer(Qt3DCore::QNodeId bufferId) +{ + auto it = m_renderBufferHash.find(bufferId); + if (it != m_renderBufferHash.end()) { + HGLBuffer glBuffHandle = it.value(); + GLBuffer *glBuff = m_renderer->glResourceManagers()->glBufferManager()->data(glBuffHandle); + + Q_ASSERT(glBuff); + // Destroy the GPU resource + glBuff->destroy(this); + // Destroy the GLBuffer instance + m_renderer->glResourceManagers()->glBufferManager()->releaseResource(bufferId); + // Remove Id - HGLBuffer entry + m_renderBufferHash.erase(it); + } +} + +bool SubmissionContext::hasGLBufferForBuffer(Buffer *buffer) +{ + const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); + return (it != m_renderBufferHash.end()); +} + +GLBuffer *SubmissionContext::glBufferForRenderBuffer(Buffer *buf) +{ + if (!m_renderBufferHash.contains(buf->peerId())) + m_renderBufferHash.insert(buf->peerId(), createGLBufferFor(buf)); + return m_renderer->glResourceManagers()->glBufferManager()->data(m_renderBufferHash.value(buf->peerId())); +} + +HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer) +{ + GLBuffer *b = m_renderer->glResourceManagers()->glBufferManager()->getOrCreateResource(buffer->peerId()); + // b.setUsagePattern(static_cast(buffer->usage())); + Q_ASSERT(b); + if (!b->create(this)) + qCWarning(Render::Io) << Q_FUNC_INFO << "buffer creation failed"; + + return m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); +} + +bool SubmissionContext::bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type) +{ + if (type == GLBuffer::ArrayBuffer && buffer == m_boundArrayBuffer) + return true; + + if (buffer->bind(this, type)) { + if (type == GLBuffer::ArrayBuffer) + m_boundArrayBuffer = buffer; + return true; + } + return false; +} + +void SubmissionContext::uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool releaseBuffer) +{ + if (!bindGLBuffer(b, GLBuffer::ArrayBuffer)) // We're uploading, the type doesn't matter here + qCWarning(Render::Io) << Q_FUNC_INFO << "buffer bind failed"; + // If the buffer is dirty (hence being called here) + // there are two possible cases + // * setData was called changing the whole data or functor (or the usage pattern) + // * partial buffer updates where received + + // TO DO: Handle usage pattern + QVector updates = std::move(buffer->pendingBufferUpdates()); + for (auto it = updates.begin(); it != updates.end(); ++it) { + auto update = it; + // We have a partial update + if (update->offset >= 0) { + //accumulate sequential updates as single one + int bufferSize = update->data.size(); + auto it2 = it + 1; + while ((it2 != updates.end()) + && (it2->offset - update->offset == bufferSize)) { + bufferSize += it2->data.size(); + ++it2; + } + update->data.resize(bufferSize); + while (it + 1 != it2) { + ++it; + update->data.replace(it->offset - update->offset, it->data.size(), it->data); + it->data.clear(); + } + // TO DO: based on the number of updates .., it might make sense to + // sometime use glMapBuffer rather than glBufferSubData + b->update(this, update->data.constData(), update->data.size(), update->offset); + } else { + // We have an update that was done by calling QBuffer::setData + // which is used to resize or entirely clear the buffer + // Note: we use the buffer data directly in that case + const int bufferSize = buffer->data().size(); + b->allocate(this, bufferSize, false); // orphan the buffer + b->allocate(this, buffer->data().constData(), bufferSize, false); + } + } + + if (releaseBuffer) { + b->release(this); + m_boundArrayBuffer = nullptr; + } + qCDebug(Render::Io) << "uploaded buffer size=" << buffer->data().size(); +} + +QByteArray SubmissionContext::downloadDataFromGLBuffer(Buffer *buffer, GLBuffer *b) +{ + if (!bindGLBuffer(b, GLBuffer::ArrayBuffer)) // We're downloading, the type doesn't matter here + qCWarning(Render::Io) << Q_FUNC_INFO << "buffer bind failed"; + + QByteArray data = b->download(this, buffer->data().size()); + return data; +} + +void SubmissionContext::blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId, + Qt3DCore::QNodeId outputRenderTargetId, + QRect inputRect, QRect outputRect, + uint defaultFboId, + QRenderTargetOutput::AttachmentPoint inputAttachmentPoint, + QRenderTargetOutput::AttachmentPoint outputAttachmentPoint, + QBlitFramebuffer::InterpolationMethod interpolationMethod) +{ + GLuint inputFboId = defaultFboId; + bool inputBufferIsDefault = true; + if (!inputRenderTargetId.isNull()) { + RenderTarget *renderTarget = m_renderer->nodeManagers()->renderTargetManager()->lookupResource(inputRenderTargetId); + if (renderTarget) { + AttachmentPack attachments(renderTarget, m_renderer->nodeManagers()->attachmentManager()); + if (m_renderTargets.contains(inputRenderTargetId)) + inputFboId = updateRenderTarget(inputRenderTargetId, attachments, false); + else + inputFboId = createRenderTarget(inputRenderTargetId, attachments); + } + inputBufferIsDefault = false; + } + + GLuint outputFboId = defaultFboId; + bool outputBufferIsDefault = true; + if (!outputRenderTargetId.isNull()) { + RenderTarget *renderTarget = m_renderer->nodeManagers()->renderTargetManager()->lookupResource(outputRenderTargetId); + if (renderTarget) { + AttachmentPack attachments(renderTarget, m_renderer->nodeManagers()->attachmentManager()); + if (m_renderTargets.contains(outputRenderTargetId)) + outputFboId = updateRenderTarget(outputRenderTargetId, attachments, false); + else + outputFboId = createRenderTarget(outputRenderTargetId, attachments); + } + outputBufferIsDefault = false; + } + + // Up until this point the input and output rects are normal Qt rectangles. + // Convert them to GL rectangles (Y at bottom). + const int inputFboHeight = inputFboId == defaultFboId ? m_surfaceSize.height() : m_renderTargetsSize[inputFboId].height(); + const GLint srcX0 = inputRect.left(); + const GLint srcY0 = inputFboHeight - (inputRect.top() + inputRect.height()); + const GLint srcX1 = srcX0 + inputRect.width(); + const GLint srcY1 = srcY0 + inputRect.height(); + + const int outputFboHeight = outputFboId == defaultFboId ? m_surfaceSize.height() : m_renderTargetsSize[outputFboId].height(); + const GLint dstX0 = outputRect.left(); + const GLint dstY0 = outputFboHeight - (outputRect.top() + outputRect.height()); + const GLint dstX1 = dstX0 + outputRect.width(); + const GLint dstY1 = dstY0 + outputRect.height(); + + //Get the last bounded framebuffers + const GLuint lastDrawFboId = boundFrameBufferObject(); + + // Activate input framebuffer for reading + bindFramebuffer(inputFboId, GraphicsHelperInterface::FBORead); + + // Activate output framebuffer for writing + bindFramebuffer(outputFboId, GraphicsHelperInterface::FBODraw); + + //Bind texture + if (!inputBufferIsDefault) + readBuffer(GL_COLOR_ATTACHMENT0 + inputAttachmentPoint); + + if (!outputBufferIsDefault) { + // Note that we use glDrawBuffers, not glDrawBuffer. The + // latter is not available with GLES. + const int buf = outputAttachmentPoint; + drawBuffers(1, &buf); + } + + // Blit framebuffer + const GLenum mode = interpolationMethod ? GL_NEAREST : GL_LINEAR; + m_glHelper->blitFramebuffer(srcX0, srcY0, srcX1, srcY1, + dstX0, dstY0, dstX1, dstY1, + GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT, + mode); + + // Reset draw buffer + bindFramebuffer(lastDrawFboId, GraphicsHelperInterface::FBOReadAndDraw); + if (outputAttachmentPoint != QRenderTargetOutput::Color0) { + const int buf = QRenderTargetOutput::Color0; + drawBuffers(1, &buf); + } +} + +} // namespace Render +} // namespace Qt3DRender of namespace + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h new file mode 100644 index 000000000..16eca07ea --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h @@ -0,0 +1,234 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H +#define QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + + +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QAbstractOpenGLFunctions; + +namespace Qt3DRender { + +namespace Render { + +class Renderer; +class GraphicsHelperInterface; +class RenderStateSet; +class Material; +class GLTexture; +class RenderCommand; +class RenderTarget; +class AttachmentPack; +class Attribute; +class Buffer; +class ShaderManager; +struct StateVariant; + +typedef QPair NamedUniformLocation; + +class Q_AUTOTEST_EXPORT SubmissionContext : public GraphicsContext +{ +public: + SubmissionContext(); + ~SubmissionContext(); + + int id() const; // unique, small integer ID of this context + void setRenderer(Renderer *renderer) { m_renderer = renderer; } + + bool beginDrawing(QSurface *surface); + void endDrawing(bool swapBuffers); + void releaseOpenGL(); + void setOpenGLContext(QOpenGLContext* ctx); + + // Viewport + void setViewport(const QRectF &viewport, const QSize &surfaceSize); + QRectF viewport() const { return m_viewport; } + + // Shaders + bool activateShader(GLShader *shader); + QOpenGLShaderProgram *activeShader() const { return m_activeShader; } + + // FBO + GLuint activeFBO() const { return m_activeFBO; } + void activateRenderTarget(const Qt3DCore::QNodeId id, const AttachmentPack &attachments, GLuint defaultFboId); + QSize renderTargetSize(const QSize &surfaceSize) const; + QImage readFramebuffer(const QRect &rect); + void blitFramebuffer(Qt3DCore::QNodeId outputRenderTargetId, Qt3DCore::QNodeId inputRenderTargetId, + QRect inputRect, + QRect outputRect, uint defaultFboId, + QRenderTargetOutput::AttachmentPoint inputAttachmentPoint, + QRenderTargetOutput::AttachmentPoint outputAttachmentPoint, + QBlitFramebuffer::InterpolationMethod interpolationMethod); + + // Attributes + void specifyAttribute(const Attribute *attribute, + Buffer *buffer, + const ShaderAttribute *attributeDescription); + void specifyIndices(Buffer *buffer); + + // Buffer + void updateBuffer(Buffer *buffer); + QByteArray downloadBufferContent(Buffer *buffer); + void releaseBuffer(Qt3DCore::QNodeId bufferId); + bool hasGLBufferForBuffer(Buffer *buffer); + GLBuffer *glBufferForRenderBuffer(Buffer *buf); + + // Parameters + bool setParameters(ShaderParameterPack ¶meterPack); + + // RenderState + void setCurrentStateSet(RenderStateSet* ss); + RenderStateSet *currentStateSet() const; + void applyState(const StateVariant &state); + + void resetMasked(qint64 maskOfStatesToReset); + void applyStateSet(RenderStateSet *ss); + + // Wrappers + void clearColor(const QColor &color); + void clearDepthValue(float depth); + void clearStencilValue(int stencil); + + + // Fences + GLFence fenceSync(); + void clientWaitSync(GLFence sync, GLuint64 nanoSecTimeout); + void waitSync(GLFence sync); + bool wasSyncSignaled(GLFence sync); + void deleteSync(GLFence sync); + +private: + void initialize(); + + // Material + Material* activeMaterial() const { return m_material; } + void setActiveMaterial(Material* rmat); + + // FBO + void bindFrameBufferAttachmentHelper(GLuint fboId, const AttachmentPack &attachments); + void activateDrawBuffers(const AttachmentPack &attachments); + void resolveRenderTargetFormat(); + GLuint createRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments); + GLuint updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, bool isActiveRenderTarget); + + // Buffers + HGLBuffer createGLBufferFor(Buffer *buffer); + void uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool releaseBuffer = false); + QByteArray downloadDataFromGLBuffer(Buffer *buffer, GLBuffer *b); + bool bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type); + + bool m_ownCurrent; + const unsigned int m_id; + QSurface *m_surface; + QSize m_surfaceSize; + + QOpenGLShaderProgram *m_activeShader; + + QHash m_renderBufferHash; + QHash m_renderTargets; + QHash m_renderTargetsSize; + QAbstractTexture::TextureFormat m_renderTargetFormat; + + // cache some current state, to make sure we don't issue unnecessary GL calls + int m_currClearStencilValue; + float m_currClearDepthValue; + QColor m_currClearColorValue; + + Material* m_material; + QRectF m_viewport; + GLuint m_activeFBO; + + GLBuffer *m_boundArrayBuffer; + RenderStateSet* m_stateSet; + Renderer *m_renderer; + QByteArray m_uboTempArray; + + TextureSubmissionContext m_textureContext; + ImageSubmissionContext m_imageContext; + + // Attributes + friend class OpenGLVertexArrayObject; + + struct VAOVertexAttribute + { + HGLBuffer bufferHandle; + GLBuffer::Type attributeType; + int location; + GLint dataType; + uint byteOffset; + uint vertexSize; + uint byteStride; + uint divisor; + GLenum shaderDataType; + }; + + using VAOIndexAttribute = HGLBuffer; + void enableAttribute(const VAOVertexAttribute &attr); + void disableAttribute(const VAOVertexAttribute &attr); +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp new file mode 100644 index 000000000..4f2ff80f5 --- /dev/null +++ b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp @@ -0,0 +1,225 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "texturesubmissioncontext_p.h" + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class TextureExtRendererLocker +{ +public: + static void lock(GLTexture *tex) + { + if (!tex->isExternalRenderingEnabled()) + return; + if (s_lockHash.keys().contains(tex)) { + ++s_lockHash[tex]; + } else { + tex->externalRenderingLock()->lock(); + s_lockHash[tex] = 1; + } + } + static void unlock(GLTexture *tex) + { + if (!tex->isExternalRenderingEnabled()) + return; + if (!s_lockHash.keys().contains(tex)) + return; + + --s_lockHash[tex]; + if (s_lockHash[tex] == 0) { + s_lockHash.remove(tex); + tex->externalRenderingLock()->unlock(); + } + } +private: + static QHash s_lockHash; +}; + +QHash TextureExtRendererLocker::s_lockHash = QHash(); + + +TextureSubmissionContext::TextureSubmissionContext() +{ + +} + +TextureSubmissionContext::~TextureSubmissionContext() +{ + +} + +void TextureSubmissionContext::initialize(GraphicsContext *context) +{ + m_activeTextures.resize(context->maxTextureUnitsCount()); +} + +void TextureSubmissionContext::endDrawing() +{ + decayTextureScores(); + for (int i = 0; i < m_activeTextures.size(); ++i) + if (m_activeTextures[i].texture) + TextureExtRendererLocker::unlock(m_activeTextures[i].texture); +} + +int TextureSubmissionContext::activateTexture(TextureSubmissionContext::TextureScope scope, + QOpenGLContext *m_gl, + GLTexture *tex) +{ + // Returns the texture unit to use for the texture + // This always return a valid unit, unless there are more textures than + // texture unit available for the current material + const int onUnit = assignUnitForTexture(tex); + + // check we didn't overflow the available units + if (onUnit == -1) + return -1; + + const int sharedTextureId = tex->sharedTextureId(); + // We have a valid texture id provided by a shared context + if (sharedTextureId > 0) { + m_gl->functions()->glActiveTexture(GL_TEXTURE0 + onUnit); + const QAbstractTexture::Target target = tex->properties().target; + // For now we know that target values correspond to the GL values + m_gl->functions()->glBindTexture(target, tex->sharedTextureId()); + } else { + // Texture must have been created and updated at this point + QOpenGLTexture *glTex = tex->getGLTexture(); + if (glTex == nullptr) + return -1; + glTex->bind(uint(onUnit)); + } + if (m_activeTextures[onUnit].texture != tex) { + if (m_activeTextures[onUnit].texture) + TextureExtRendererLocker::unlock(m_activeTextures[onUnit].texture); + m_activeTextures[onUnit].texture = tex; + TextureExtRendererLocker::lock(tex); + } + +#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) + int err = m_gl->functions()->glGetError(); + if (err) + qCWarning(Backend) << "GL error after activating texture" << QString::number(err, 16) + << tex->getGLTexture()->textureId() << "on unit" << onUnit; +#endif + + m_activeTextures[onUnit].score = 200; + m_activeTextures[onUnit].pinned = true; + m_activeTextures[onUnit].scope = scope; + + return onUnit; +} + +void TextureSubmissionContext::deactivateTexturesWithScope(TextureSubmissionContext::TextureScope ts) +{ + for (int u=0; u +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLContext; + +namespace Qt3DRender { +namespace Render { + +class GraphicsContext; +class GLTexture; + +class Q_AUTOTEST_EXPORT TextureSubmissionContext +{ +public: + enum TextureScope + { + TextureScopeMaterial = 0, + TextureScopeTechnique + // per-pass for deferred rendering? + }; + + TextureSubmissionContext(); + ~TextureSubmissionContext(); + + void initialize(GraphicsContext *context); + void endDrawing(); + int activateTexture(TextureScope scope, QOpenGLContext *gl, GLTexture* tex); + void deactivateTexture(GLTexture *tex); + void deactivateTexturesWithScope(TextureScope ts); + +private: + void decayTextureScores(); + int assignUnitForTexture(GLTexture* tex); + + // active textures, indexed by texture unit + struct ActiveTexture { + GLTexture *texture = nullptr; + int score = 0; + TextureScope scope = TextureScopeMaterial; + bool pinned = false; + }; + QVector m_activeTextures; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_TEXTURESUBMISSIONCONTEXT_H diff --git a/src/plugins/renderers/opengl/io/glbuffer.cpp b/src/plugins/renderers/opengl/io/glbuffer.cpp new file mode 100644 index 000000000..53fc50cb9 --- /dev/null +++ b/src/plugins/renderers/opengl/io/glbuffer.cpp @@ -0,0 +1,169 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glbuffer_p.h" +#include + +#if !defined(GL_UNIFORM_BUFFER) +#define GL_UNIFORM_BUFFER 0x8A11 +#endif +#if !defined(GL_ARRAY_BUFFER) +#define GL_ARRAY_BUFFER 0x8892 +#endif +#if !defined(GL_ELEMENT_ARRAY_BUFFER) +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#endif +#if !defined(GL_SHADER_STORAGE_BUFFER) +#define GL_SHADER_STORAGE_BUFFER 0x90D2 +#endif +#if !defined(GL_PIXEL_PACK_BUFFER) +#define GL_PIXEL_PACK_BUFFER 0x88EB +#endif +#if !defined(GL_PIXEL_UNPACK_BUFFER) +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#endif +#if !defined(GL_DRAW_INDIRECT_BUFFER) +#define GL_DRAW_INDIRECT_BUFFER 0x8F3F +#endif + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +// A UBO is created for each ShaderData Shader Pair +// That means a UBO is unique to a shader/shaderdata + +namespace { + +GLenum glBufferTypes[] = { + GL_ARRAY_BUFFER, + GL_UNIFORM_BUFFER, + GL_ELEMENT_ARRAY_BUFFER, + GL_SHADER_STORAGE_BUFFER, + GL_PIXEL_PACK_BUFFER, + GL_PIXEL_UNPACK_BUFFER, + GL_DRAW_INDIRECT_BUFFER +}; + +} // anonymous + +GLBuffer::GLBuffer() + : m_bufferId(0) + , m_isCreated(false) + , m_bound(false) + , m_lastTarget(GL_ARRAY_BUFFER) +{ +} + +bool GLBuffer::bind(GraphicsContext *ctx, Type t) +{ + if (m_bufferId == 0) + return false; + m_lastTarget = glBufferTypes[t]; + ctx->openGLContext()->functions()->glBindBuffer(m_lastTarget, m_bufferId); + m_bound = true; + return true; +} + +bool GLBuffer::release(GraphicsContext *ctx) +{ + m_bound = false; + ctx->openGLContext()->functions()->glBindBuffer(m_lastTarget, 0); + return true; +} + +bool GLBuffer::create(GraphicsContext *ctx) +{ + ctx->openGLContext()->functions()->glGenBuffers(1, &m_bufferId); + m_isCreated = true; + return m_bufferId != 0; +} + +void GLBuffer::destroy(GraphicsContext *ctx) +{ + ctx->openGLContext()->functions()->glDeleteBuffers(1, &m_bufferId); + m_isCreated = false; +} + +void GLBuffer::allocate(GraphicsContext *ctx, uint size, bool dynamic) +{ + // Either GL_STATIC_DRAW OR GL_DYNAMIC_DRAW depending on the use case + // TO DO: find a way to know how a buffer/QShaderData will be used to use the right usage + ctx->openGLContext()->functions()->glBufferData(m_lastTarget, size, NULL, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); +} + +void GLBuffer::allocate(GraphicsContext *ctx, const void *data, uint size, bool dynamic) +{ + ctx->openGLContext()->functions()->glBufferData(m_lastTarget, size, data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); +} + +void GLBuffer::update(GraphicsContext *ctx, const void *data, uint size, int offset) +{ + ctx->openGLContext()->functions()->glBufferSubData(m_lastTarget, offset, size, data); +} + +QByteArray GLBuffer::download(GraphicsContext *ctx, uint size) +{ + char *gpu_ptr = ctx->mapBuffer(m_lastTarget, size); + QByteArray data; + if (gpu_ptr != nullptr) { + data.resize(size); + std::copy(gpu_ptr, gpu_ptr+size, data.data()); + } + ctx->unmapBuffer(m_lastTarget); + return data; +} + +void GLBuffer::bindBufferBase(GraphicsContext *ctx, int bindingPoint, GLBuffer::Type t) +{ + ctx->bindBufferBase(glBufferTypes[t], bindingPoint, m_bufferId); +} + +void GLBuffer::bindBufferBase(GraphicsContext *ctx, int bindingPoint) +{ + ctx->bindBufferBase(m_lastTarget, bindingPoint, m_bufferId); +} + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/io/glbuffer_p.h b/src/plugins/renderers/opengl/io/glbuffer_p.h new file mode 100644 index 000000000..731634b6b --- /dev/null +++ b/src/plugins/renderers/opengl/io/glbuffer_p.h @@ -0,0 +1,110 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GLBUFFER_P_H +#define QT3DRENDER_RENDER_GLBUFFER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class GraphicsContext; + +class GLBuffer +{ +public: + GLBuffer(); + + enum Type + { + ArrayBuffer = 0, + UniformBuffer, + IndexBuffer, + ShaderStorageBuffer, + PixelPackBuffer, + PixelUnpackBuffer, + DrawIndirectBuffer + }; + + bool bind(GraphicsContext *ctx, Type t); + bool release(GraphicsContext *ctx); + bool create(GraphicsContext *ctx); + void destroy(GraphicsContext *ctx); + void allocate(GraphicsContext *ctx, uint size, bool dynamic = true); + void allocate(GraphicsContext *ctx, const void *data, uint size, bool dynamic = true); + void update(GraphicsContext *ctx, const void *data, uint size, int offset = 0); + QByteArray download(GraphicsContext *ctx, uint size); + void bindBufferBase(GraphicsContext *ctx, int bindingPoint, Type t); + void bindBufferBase(GraphicsContext *ctx, int bindingPoint); + + inline GLuint bufferId() const { return m_bufferId; } + inline bool isCreated() const { return m_isCreated; } + inline bool isBound() const { return m_bound; } + +private: + GLuint m_bufferId; + bool m_isCreated; + bool m_bound; + GLenum m_lastTarget; +}; + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GLBUFFER_P_H diff --git a/src/plugins/renderers/opengl/io/io.pri b/src/plugins/renderers/opengl/io/io.pri new file mode 100644 index 000000000..462978c4d --- /dev/null +++ b/src/plugins/renderers/opengl/io/io.pri @@ -0,0 +1,8 @@ +INCLUDEPATH += $$PWD + +SOURCES += \ + $$PWD/glbuffer.cpp + +HEADERS += \ + $$PWD/glbuffer_p.h + diff --git a/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp new file mode 100644 index 000000000..95e8862ef --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "filtercompatibletechniquejob_p.h" +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +FilterCompatibleTechniqueJob::FilterCompatibleTechniqueJob() + : m_manager(nullptr) + , m_renderer(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::FilterCompatibleTechniques, 0) +} + +void FilterCompatibleTechniqueJob::setManager(TechniqueManager *manager) +{ + m_manager = manager; +} + +TechniqueManager *FilterCompatibleTechniqueJob::manager() const +{ + return m_manager; +} + +void FilterCompatibleTechniqueJob::setRenderer(Renderer *renderer) +{ + m_renderer = renderer; +} + +Renderer *FilterCompatibleTechniqueJob::renderer() const +{ + return m_renderer; +} + +void FilterCompatibleTechniqueJob::run() +{ + Q_ASSERT(m_manager != nullptr && m_renderer != nullptr); + Q_ASSERT(m_renderer->isRunning() && m_renderer->submissionContext()->isInitialized()); + + const QVector dirtyTechniqueIds = m_manager->takeDirtyTechniques(); + for (const Qt3DCore::QNodeId techniqueId : dirtyTechniqueIds) { + Technique *technique = m_manager->lookupResource(techniqueId); + if (Q_LIKELY(technique != nullptr)) + technique->setCompatibleWithRenderer((*m_renderer->contextInfo() == *technique->graphicsApiFilter())); + } +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h new file mode 100644 index 000000000..9037baa46 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H +#define QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class TechniqueManager; +class Renderer; + +class Q_AUTOTEST_EXPORT FilterCompatibleTechniqueJob : public Qt3DCore::QAspectJob +{ +public: + FilterCompatibleTechniqueJob(); + + void setManager(TechniqueManager *managers); + TechniqueManager *manager() const; + + void setRenderer(Renderer *renderer); + Renderer *renderer() const; + + void run() override; + +private: + TechniqueManager *m_manager; + Renderer *m_renderer; +}; + +typedef QSharedPointer FilterCompatibleTechniqueJobPtr; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H diff --git a/src/plugins/renderers/opengl/jobs/jobs.pri b/src/plugins/renderers/opengl/jobs/jobs.pri new file mode 100644 index 000000000..d80b8bfd9 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/jobs.pri @@ -0,0 +1,17 @@ +INCLUDEPATH += $$PWD + +SOURCES += \ + $$PWD/filtercompatibletechniquejob.cpp \ + $$PWD/materialparametergathererjob.cpp \ + $$PWD/renderviewcommandbuilderjob.cpp \ + $$PWD/renderviewcommandupdaterjob.cpp \ + $$PWD/renderviewinitializerjob.cpp \ + $$PWD/renderviewjobutils.cpp + +HEADERS += \ + $$PWD/filtercompatibletechniquejob_p.h \ + $$PWD/materialparametergathererjob_p.h \ + $$PWD/renderviewcommandbuilderjob_p.h \ + $$PWD/renderviewcommandupdaterjob_p.h \ + $$PWD/renderviewinitializerjob_p.h \ + $$PWD/renderviewjobutils_p.h diff --git a/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp b/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp new file mode 100644 index 000000000..e1f8aa403 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp @@ -0,0 +1,131 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "materialparametergathererjob_p.h" +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { + +int materialParameterGathererCounter = 0; +const int likelyNumberOfParameters = 24; + +} // anonymous + +MaterialParameterGathererJob::MaterialParameterGathererJob() + : Qt3DCore::QAspectJob() + , m_manager(nullptr) + , m_techniqueFilter(nullptr) + , m_renderPassFilter(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::MaterialParameterGathering, materialParameterGathererCounter++) +} + +// TechniqueFilter / RenderPassFilter + +// Parameters from Material/Effect/Technique + +// Note: we could maybe improve that by having a smart update when we detect +// that a parameter value has changed. That might require way more book keeping +// which might make this solution a bit too complex + +// The fact that this can now be performed in parallel should already provide a big +// improvement +void MaterialParameterGathererJob::run() +{ + for (const HMaterial &materialHandle : qAsConst(m_handles)) { + Material *material = m_manager->materialManager()->data(materialHandle); + + if (Q_UNLIKELY(!material->isEnabled())) + continue; + + Effect *effect = m_manager->effectManager()->lookupResource(material->effect()); + Technique *technique = findTechniqueForEffect(m_manager, m_techniqueFilter, effect); + + if (Q_LIKELY(technique != nullptr)) { + RenderPassList passes = findRenderPassesForTechnique(m_manager, m_renderPassFilter, technique); + if (Q_LIKELY(passes.size() > 0)) { + // Order set: + // 1 Pass Filter + // 2 Technique Filter + // 3 Material + // 4 Effect + // 5 Technique + // 6 RenderPass + + // Add Parameters define in techniqueFilter and passFilter + // passFilter have priority over techniqueFilter + + ParameterInfoList parameters; + // Doing the reserve allows a gain of 0.5ms on some of the demo examples + parameters.reserve(likelyNumberOfParameters); + + if (m_renderPassFilter) + parametersFromParametersProvider(¶meters, m_manager->parameterManager(), + m_renderPassFilter); + if (m_techniqueFilter) + parametersFromParametersProvider(¶meters, m_manager->parameterManager(), + m_techniqueFilter); + // Get the parameters for our selected rendering setup (override what was defined in the technique/pass filter) + parametersFromMaterialEffectTechnique(¶meters, m_manager->parameterManager(), material, effect, technique); + + for (RenderPass *renderPass : passes) { + ParameterInfoList globalParameters = parameters; + parametersFromParametersProvider(&globalParameters, m_manager->parameterManager(), renderPass); + m_parameters[material->peerId()].push_back({renderPass, globalParameters}); + } + } + } + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h b/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h new file mode 100644 index 000000000..5975261af --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H +#define QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class NodeManagers; +class TechniqueFilter; +class RenderPassFilter; +class Renderer; + +// TO be executed for each FrameGraph branch with a given RenderPassFilter/TechniqueFilter + +class Q_AUTOTEST_EXPORT MaterialParameterGathererJob : public Qt3DCore::QAspectJob +{ +public: + MaterialParameterGathererJob(); + + inline void setNodeManagers(NodeManagers *manager) Q_DECL_NOTHROW { m_manager = manager; } + inline void setTechniqueFilter(TechniqueFilter *techniqueFilter) Q_DECL_NOTHROW { m_techniqueFilter = techniqueFilter; } + inline void setRenderPassFilter(RenderPassFilter *renderPassFilter) Q_DECL_NOTHROW { m_renderPassFilter = renderPassFilter; } + inline const QHash> &materialToPassAndParameter() Q_DECL_NOTHROW { return m_parameters; } + inline void setHandles(const QVector &handles) Q_DECL_NOTHROW { m_handles = handles; } + + inline TechniqueFilter *techniqueFilter() const Q_DECL_NOTHROW { return m_techniqueFilter; } + inline RenderPassFilter *renderPassFilter() const Q_DECL_NOTHROW { return m_renderPassFilter; } + + void run() final; + +private: + NodeManagers *m_manager; + TechniqueFilter *m_techniqueFilter; + RenderPassFilter *m_renderPassFilter; + + // Material id to array of RenderPasse with parameters + MaterialParameterGathererData m_parameters; + QVector m_handles; +}; + +typedef QSharedPointer MaterialParameterGathererJobPtr; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp new file mode 100644 index 000000000..5bfa9ed6f --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewcommandupdaterjob_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { +int renderViewInstanceCounter = 0; +} // anonymous + +RenderViewCommandUpdaterJob::RenderViewCommandUpdaterJob() + : Qt3DCore::QAspectJob() + , m_offset(0) + , m_count(0) + , m_renderView(nullptr) + , m_renderer(nullptr) + , m_renderables(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderCommandUpdater, renderViewInstanceCounter++); +} + +void RenderViewCommandUpdaterJob::run() +{ + // Build RenderCommand should perform the culling as we have no way to determine + // if a child has a mesh in the view frustum while its parent isn't contained in it. + if (!m_renderView->noDraw()) { + if (m_count == 0) + return; + // Update Render Commands (Uniform Change, Depth Change) + m_renderView->updateRenderCommand(m_renderables, m_offset, m_count); + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h new file mode 100644 index 000000000..6a171d281 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob +{ +public: + RenderViewCommandBuilderJob(); + + inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } + inline void setEntities(const QVector &entities, int offset, int count) + { + m_offset = offset; + m_count = count; + m_entities = entities; + } + inline EntityRenderCommandData &commandData() { return m_commandData; } + + void run() final; + +private: + int m_offset; + int m_count; + RenderView *m_renderView; + QVector m_entities; + EntityRenderCommandData m_commandData; +}; + +typedef QSharedPointer RenderViewCommandBuilderJobPtr; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp new file mode 100644 index 000000000..00cfba558 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewcommandbuilderjob_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { +int renderViewInstanceCounter = 0; +} // anonymous + +RenderViewCommandBuilderJob::RenderViewCommandBuilderJob() + : Qt3DCore::QAspectJob() + , m_offset(0) + , m_count(0) + , m_renderView(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderViewCommandBuilder, renderViewInstanceCounter++) +} + +void RenderViewCommandBuilderJob::run() +{ + if (!m_renderView->noDraw()) { + if (m_count == 0) + return; + + const bool isDraw = !m_renderView->isCompute(); + if (isDraw) + m_commandData = m_renderView->buildDrawRenderCommands(m_entities, m_offset, m_count); + else + m_commandData = m_renderView->buildComputeRenderCommands(m_entities, m_offset, m_count); + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h new file mode 100644 index 000000000..6a171d281 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob +{ +public: + RenderViewCommandBuilderJob(); + + inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } + inline void setEntities(const QVector &entities, int offset, int count) + { + m_offset = offset; + m_count = count; + m_entities = entities; + } + inline EntityRenderCommandData &commandData() { return m_commandData; } + + void run() final; + +private: + int m_offset; + int m_count; + RenderView *m_renderView; + QVector m_entities; + EntityRenderCommandData m_commandData; +}; + +typedef QSharedPointer RenderViewCommandBuilderJobPtr; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp new file mode 100644 index 000000000..1b7cae229 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewcommandupdaterjob_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { +int renderViewInstanceCounter = 0; +} // anonymous + +RenderViewCommandUpdaterJob::RenderViewCommandUpdaterJob() + : Qt3DCore::QAspectJob() + , m_offset(0) + , m_count(0) + , m_renderView(nullptr) + , m_renderer(nullptr) + , m_renderables() +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderCommandUpdater, renderViewInstanceCounter++) +} + +void RenderViewCommandUpdaterJob::run() +{ + // Build RenderCommand should perform the culling as we have no way to determine + // if a child has a mesh in the view frustum while its parent isn't contained in it. + if (!m_renderView->noDraw()) { + if (m_count == 0) + return; + // Update Render Commands (Uniform Change, Depth Change) + m_renderView->updateRenderCommand(m_renderables.data(), m_offset, m_count); + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h new file mode 100644 index 000000000..88961d848 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h @@ -0,0 +1,103 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H +#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class RenderView; +class Renderer; + +class Q_AUTOTEST_EXPORT RenderViewCommandUpdaterJob : public Qt3DCore::QAspectJob +{ +public: + RenderViewCommandUpdaterJob(); + + inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } + inline void setRenderer(Renderer *renderer) Q_DECL_NOTHROW { m_renderer = renderer; } + inline void setRenderables(const EntityRenderCommandDataPtr &renderables, int offset, int count) Q_DECL_NOTHROW + { + m_offset = offset; + m_count = count; + m_renderables = renderables; + } + EntityRenderCommandDataPtr renderables() const { return m_renderables; } + + QVector &commands() Q_DECL_NOTHROW { return m_commands; } + + void run() final; + +private: + int m_offset; + int m_count; + RenderView *m_renderView; + Renderer *m_renderer; + EntityRenderCommandDataPtr m_renderables; + QVector m_commands; +}; + +typedef QSharedPointer RenderViewCommandUpdaterJobPtr; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp new file mode 100644 index 000000000..c1b97959f --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewinitializerjob_p.h" + +#include +#include +#include +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +namespace { +// only accessed in ctor and dtor of RenderViewJob +// which are always being called in a non concurrent manner +int renderViewInstanceCounter = 0; +} // anonymous + +RenderViewInitializerJob::RenderViewInitializerJob() + : m_renderer(nullptr) + , m_fgLeaf(nullptr) + , m_index(0) + , m_renderView(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderView, renderViewInstanceCounter++) +} + +RenderViewInitializerJob::~RenderViewInitializerJob() +{ + renderViewInstanceCounter--; +} + +void RenderViewInitializerJob::run() +{ + qCDebug(Jobs) << Q_FUNC_INFO << m_index; +#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) + QElapsedTimer timer; + timer.start(); + qint64 gatherLightsTime; + qint64 buildCommandsTime; +#endif + + // Create a RenderView object + // The RenderView are created from a QFrameAllocator stored in the current Thread local storage + m_renderView = new RenderView; + + // RenderView should allocate heap resources using only the currentFrameAllocator + m_renderView->setRenderer(m_renderer); + + // Populate the renderview's configuration from the framegraph + setRenderViewConfigFromFrameGraphLeafNode(m_renderView, m_fgLeaf); +#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) + qint64 gatherStateTime = timer.nsecsElapsed(); + timer.restart(); +#endif +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h new file mode 100644 index 000000000..fb4e2c67c --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H +#define QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Renderer; +class FrameGraphNode; +class RenderView; + +class Q_AUTOTEST_EXPORT RenderViewInitializerJob : public Qt3DCore::QAspectJob +{ +public: + RenderViewInitializerJob(); + ~RenderViewInitializerJob(); + + inline void setRenderer(Renderer *renderer) { m_renderer = renderer; } + inline RenderView *renderView() const Q_DECL_NOTHROW { return m_renderView; } + + inline void setFrameGraphLeafNode(FrameGraphNode *fgLeaf) + { + m_fgLeaf = fgLeaf; + } + + // Sets the position in the queue of RenderViews that the + // RenderView generated by this job should be inserted. This is + // used to ensure that for example a RenderView for creating + // a shadow map texture is submitted before the RenderView that + // contains commands making use of the shadow map + inline void setSubmitOrderIndex(int index) { m_index = index; } + inline int submitOrderIndex() const { return m_index; } + + void run() override; + +private: + Renderer *m_renderer; + FrameGraphNode *m_fgLeaf; + int m_index; + RenderView *m_renderView; +}; + +typedef QSharedPointer RenderViewInitializerJobPtr; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp b/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp new file mode 100644 index 000000000..f869c5532 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp @@ -0,0 +1,574 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewjobutils_p.h" +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +using namespace Qt3DCore; + +namespace Qt3DRender { +namespace Render { + +/*! + \internal + Walks up the framegraph tree from \a fgLeaf and builds up as much state + as possible and populates \a rv. For cases where we can't get the specific state + (e.g. because it depends upon more than just the framegraph) we store the data from + the framegraph that will be needed to later when the rest of the data becomes available +*/ +void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, const FrameGraphNode *fgLeaf) +{ + // The specific RenderPass to be used is also dependent upon the Effect and TechniqueFilter + // which is referenced by the Material which is referenced by the RenderMesh. So we can + // only store the filter info in the RenderView structure and use it to do the resolving + // when we build the RenderCommand list. + const NodeManagers *manager = rv->nodeManagers(); + const FrameGraphNode *node = fgLeaf; + + while (node) { + FrameGraphNode::FrameGraphNodeType type = node->nodeType(); + if (node->isEnabled()) + switch (type) { + case FrameGraphNode::InvalidNodeType: + // A base FrameGraphNode, can be used for grouping purposes + break; + case FrameGraphNode::CameraSelector: + // Can be set only once and we take camera nearest to the leaf node + if (!rv->renderCameraLens()) { + const CameraSelector *cameraSelector = static_cast(node); + Entity *camNode = manager->renderNodesManager()->lookupResource(cameraSelector->cameraUuid()); + if (camNode) { + CameraLens *lens = camNode->renderComponent(); + rv->setRenderCameraEntity(camNode); + if (lens && lens->isEnabled()) { + rv->setRenderCameraLens(lens); + // ViewMatrix and ProjectionMatrix are computed + // later in updateMatrices() + // since at this point the transformation matrices + // may not yet have been updated + } + } + } + break; + + case FrameGraphNode::LayerFilter: // Can be set multiple times in the tree + rv->appendLayerFilter(static_cast(node)->peerId()); + break; + + case FrameGraphNode::ProximityFilter: // Can be set multiple times in the tree + rv->appendProximityFilterId(node->peerId()); + break; + + case FrameGraphNode::RenderPassFilter: + // Can be set once + // TODO: Amalgamate all render pass filters from leaf to root + if (!rv->renderPassFilter()) + rv->setRenderPassFilter(static_cast(node)); + break; + + case FrameGraphNode::RenderTarget: { + // Can be set once and we take render target nearest to the leaf node + const RenderTargetSelector *targetSelector = static_cast(node); + QNodeId renderTargetUid = targetSelector->renderTargetUuid(); + HTarget renderTargetHandle = manager->renderTargetManager()->lookupHandle(renderTargetUid); + + // Add renderTarget Handle and build renderCommand AttachmentPack + if (!rv->renderTargetId()) { + rv->setRenderTargetId(renderTargetUid); + + RenderTarget *renderTarget = manager->renderTargetManager()->data(renderTargetHandle); + if (renderTarget) + rv->setAttachmentPack(AttachmentPack(renderTarget, manager->attachmentManager(), targetSelector->outputs())); + } + break; + } + + case FrameGraphNode::ClearBuffers: { + const ClearBuffers *cbNode = static_cast(node); + rv->addClearBuffers(cbNode); + break; + } + + case FrameGraphNode::TechniqueFilter: + // Can be set once + // TODO Amalgamate all technique filters from leaf to root + if (!rv->techniqueFilter()) + rv->setTechniqueFilter(static_cast(node)); + break; + + case FrameGraphNode::Viewport: { + // If the Viewport has already been set in a lower node + // Make it so that the new viewport is actually + // a subregion relative to that of the parent viewport + const ViewportNode *vpNode = static_cast(node); + rv->setViewport(ViewportNode::computeViewport(rv->viewport(), vpNode)); + rv->setGamma(vpNode->gamma()); + break; + } + + case FrameGraphNode::SortMethod: { + const Render::SortPolicy *sortPolicy = static_cast(node); + rv->addSortType(sortPolicy->sortTypes()); + break; + } + + case FrameGraphNode::SubtreeEnabler: + // Has no meaning here. SubtreeEnabler was used + // in a prior step to filter the list of RenderViewJobs + break; + + case FrameGraphNode::StateSet: { + const Render::StateSetNode *rStateSet = static_cast(node); + // Create global RenderStateSet for renderView if no stateSet was set before + RenderStateSet *stateSet = rv->stateSet(); + if (stateSet == nullptr && rStateSet->hasRenderStates()) { + stateSet = new RenderStateSet(); + rv->setStateSet(stateSet); + } + + // Add states from new stateSet we might be missing + // but don' t override existing states (lower StateSetNode always has priority) + if (rStateSet->hasRenderStates()) + addStatesToRenderStateSet(stateSet, rStateSet->renderStates(), manager->renderStateManager()); + break; + } + + case FrameGraphNode::NoDraw: { + rv->setNoDraw(true); + break; + } + + case FrameGraphNode::FrustumCulling: { + rv->setFrustumCulling(true); + break; + } + + case FrameGraphNode::ComputeDispatch: { + const Render::DispatchCompute *dispatchCompute = static_cast(node); + rv->setCompute(true); + rv->setComputeWorkgroups(dispatchCompute->x(), + dispatchCompute->y(), + dispatchCompute->z()); + break; + } + + case FrameGraphNode::Lighting: { + // TODO + break; + } + + case FrameGraphNode::Surface: { + // Use the surface closest to leaf node + if (rv->surface() == nullptr) { + const Render::RenderSurfaceSelector *surfaceSelector + = static_cast(node); + rv->setSurface(surfaceSelector->surface()); + rv->setSurfaceSize(surfaceSelector->renderTargetSize() * surfaceSelector->devicePixelRatio()); + rv->setDevicePixelRatio(surfaceSelector->devicePixelRatio()); + } + break; + } + + case FrameGraphNode::DebugOverlay: + rv->setShowDebugOverlay(true); + break; + + case FrameGraphNode::RenderCapture: { + auto *renderCapture = const_cast( + static_cast(node)); + if (rv->renderCaptureNodeId().isNull() && renderCapture->wasCaptureRequested()) { + rv->setRenderCaptureNodeId(renderCapture->peerId()); + rv->setRenderCaptureRequest(renderCapture->takeCaptureRequest()); + } + break; + } + + case FrameGraphNode::MemoryBarrier: { + const Render::MemoryBarrier *barrier = static_cast(node); + rv->setMemoryBarrier(barrier->waitOperations()|rv->memoryBarrier()); + break; + } + + case FrameGraphNode::BufferCapture: { + auto *bufferCapture = const_cast( + static_cast(node)); + if (bufferCapture != nullptr) + rv->setIsDownloadBuffersEnable(bufferCapture->isEnabled()); + break; + } + + case FrameGraphNode::BlitFramebuffer: { + const Render::BlitFramebuffer *blitFramebufferNode = + static_cast(node); + rv->setHasBlitFramebufferInfo(true); + BlitFramebufferInfo bfbInfo; + bfbInfo.sourceRenderTargetId = blitFramebufferNode->sourceRenderTargetId(); + bfbInfo.destinationRenderTargetId = blitFramebufferNode->destinationRenderTargetId(); + bfbInfo.sourceRect = blitFramebufferNode->sourceRect(); + bfbInfo.destinationRect = blitFramebufferNode->destinationRect(); + bfbInfo.sourceAttachmentPoint = blitFramebufferNode->sourceAttachmentPoint(); + bfbInfo.destinationAttachmentPoint = blitFramebufferNode->destinationAttachmentPoint(); + bfbInfo.interpolationMethod = blitFramebufferNode->interpolationMethod(); + rv->setBlitFrameBufferInfo(bfbInfo); + break; + } + + case FrameGraphNode::WaitFence: { + const Render::WaitFence *waitFence = static_cast(node); + rv->appendWaitFence(waitFence->data()); + break; + } + + case FrameGraphNode::SetFence: { + rv->appendInsertFenceId(node->peerId()); + break; + } + + case FrameGraphNode::NoPicking: + // Nothing to do RenderView wise for NoPicking + break; + + default: + // Should never get here + qCWarning(Backend) << "Unhandled FrameGraphNode type"; + } + + node = node->parent(); + } +} + +/*! + \internal + Searches the best matching Technique from \a effect specified. +*/ +Technique *findTechniqueForEffect(NodeManagers *manager, + const TechniqueFilter *techniqueFilter, + Effect *effect) +{ + if (!effect) + return nullptr; + + QVector matchingTechniques; + const bool hasInvalidTechniqueFilter = (techniqueFilter == nullptr || techniqueFilter->filters().isEmpty()); + + // Iterate through the techniques in the effect + const auto techniqueIds = effect->techniques(); + for (const QNodeId techniqueId : techniqueIds) { + Technique *technique = manager->techniqueManager()->lookupResource(techniqueId); + + // Should be valid, if not there likely a problem with node addition/destruction changes + Q_ASSERT(technique); + + // Check if the technique is compatible with the rendering API + // If no techniqueFilter is present, we return the technique as it satisfies OpenGL version + if (technique->isCompatibleWithRenderer() && (hasInvalidTechniqueFilter || technique->isCompatibleWithFilters(techniqueFilter->filters()))) + matchingTechniques.append(technique); + } + + if (matchingTechniques.size() == 0) // We failed to find a suitable technique to use :( + return nullptr; + + if (matchingTechniques.size() == 1) + return matchingTechniques.first(); + + // Several compatible techniques, return technique with highest major and minor version + Technique* highest = matchingTechniques.first(); + GraphicsApiFilterData filter = *highest->graphicsApiFilter(); + for (auto it = matchingTechniques.cbegin() + 1; it < matchingTechniques.cend(); ++it) { + if (filter < *(*it)->graphicsApiFilter()) { + filter = *(*it)->graphicsApiFilter(); + highest = *it; + } + } + return highest; +} + + +RenderPassList findRenderPassesForTechnique(NodeManagers *manager, + const RenderPassFilter *passFilter, + Technique *technique) +{ + Q_ASSERT(manager); + Q_ASSERT(technique); + + RenderPassList passes; + const auto passIds = technique->renderPasses(); + for (const QNodeId passId : passIds) { + RenderPass *renderPass = manager->renderPassManager()->lookupResource(passId); + + if (renderPass && renderPass->isEnabled()) { + bool foundMatch = (!passFilter || passFilter->filters().size() == 0); + + // A pass filter is present so we need to check for matching criteria + if (!foundMatch && renderPass->filterKeys().size() >= passFilter->filters().size()) { + + // Iterate through the filter criteria and look for render passes with criteria that satisfy them + const auto filterKeyIds = passFilter->filters(); + for (const QNodeId filterKeyId : filterKeyIds) { + foundMatch = false; + FilterKey *filterFilterKey = manager->filterKeyManager()->lookupResource(filterKeyId); + + const auto passFilterKeyIds = renderPass->filterKeys(); + for (const QNodeId passFilterKeyId : passFilterKeyIds) { + FilterKey *passFilterKey = manager->filterKeyManager()->lookupResource(passFilterKeyId); + if ((foundMatch = (*passFilterKey == *filterFilterKey))) + break; + } + + if (!foundMatch) { + // No match for criterion in any of the render pass' criteria + break; + } + } + } + + if (foundMatch) { + // Found a renderpass that satisfies our needs. Add it in order + passes << renderPass; + } + } + } + + return passes; +} + + +ParameterInfoList::const_iterator findParamInfo(ParameterInfoList *params, const int nameId) +{ + const ParameterInfoList::const_iterator end = params->cend(); + ParameterInfoList::const_iterator it = std::lower_bound(params->cbegin(), end, nameId); + if (it != end && it->nameId != nameId) + return end; + return it; +} + +void addParametersForIds(ParameterInfoList *params, ParameterManager *manager, + const Qt3DCore::QNodeIdVector ¶meterIds) +{ + for (const QNodeId paramId : parameterIds) { + const HParameter parameterHandle = manager->lookupHandle(paramId); + const Parameter *param = manager->data(parameterHandle); + ParameterInfoList::iterator it = std::lower_bound(params->begin(), params->end(), param->nameId()); + if (it == params->end() || it->nameId != param->nameId()) + params->insert(it, ParameterInfo(param->nameId(), parameterHandle)); + } +} + +void parametersFromMaterialEffectTechnique(ParameterInfoList *infoList, + ParameterManager *manager, + Material *material, + Effect *effect, + Technique *technique) +{ + // The parameters are taken in the following priority order: + // + // 1) Material + // 2) Effect + // 3) Technique + // + // That way a user can override defaults in Effect's and Techniques on a + // object manner and a Technique can override global defaults from the Effect. + parametersFromParametersProvider(infoList, manager, material); + parametersFromParametersProvider(infoList, manager, effect); + parametersFromParametersProvider(infoList, manager, technique); +} + +// Only add states with types we don't already have +void addStatesToRenderStateSet(RenderStateSet *stateSet, + const QVector stateIds, + RenderStateManager *manager) +{ + for (const Qt3DCore::QNodeId &stateId : stateIds) { + RenderStateNode *node = manager->lookupResource(stateId); + if (node->isEnabled() && stateSet->canAddStateOfType(node->type())) { + stateSet->addState(node->impl()); + } + } +} + +namespace { + +const QString blockArray = QStringLiteral("[%1]"); +const int qNodeIdTypeId = qMetaTypeId(); + +} + +UniformBlockValueBuilder::UniformBlockValueBuilder() + : updatedPropertiesOnly(false) + , shaderDataManager(nullptr) + , textureManager(nullptr) +{ +} + +UniformBlockValueBuilder::~UniformBlockValueBuilder() +{ +} + +void UniformBlockValueBuilder::buildActiveUniformNameValueMapHelper(ShaderData *currentShaderData, const QString &blockName, const QString &qmlPropertyName, const QVariant &value) +{ + // In the end, values are either scalar or a scalar array + // Composed elements (structs, structs array) are simplified into simple scalars + if (value.userType() == QMetaType::QVariantList) { // Array + QVariantList list = value.value(); + if (list.at(0).userType() == qNodeIdTypeId) { // Array of struct qmlPropertyName[i].structMember + for (int i = 0; i < list.size(); ++i) { + const QVariant variantElement = list.at(i); + if (list.at(i).userType() == qNodeIdTypeId) { + const auto nodeId = variantElement.value(); + ShaderData *subShaderData = shaderDataManager->lookupResource(nodeId); + if (subShaderData) { + buildActiveUniformNameValueMapStructHelper(subShaderData, + blockName + QLatin1Char('.') + qmlPropertyName + blockArray.arg(i), + QLatin1String("")); + } + // Note: we only handle ShaderData as nested container nodes here + } + } + } else { // Array of scalar/vec qmlPropertyName[0] + QString varName; + varName.reserve(blockName.length() + 1 + qmlPropertyName.length() + 3); + varName.append(blockName); + varName.append(QLatin1String(".")); + varName.append(qmlPropertyName); + varName.append(QLatin1String("[0]")); + if (uniforms.contains(varName)) { + qCDebug(Shaders) << "UBO array member " << varName << " set for update"; + activeUniformNamesToValue.insert(StringToInt::lookupId(varName), value); + } + } + } else if (value.userType() == qNodeIdTypeId) { // Struct qmlPropertyName.structMember + const auto nodeId = value.value(); + ShaderData *rSubShaderData = shaderDataManager->lookupResource(nodeId); + if (rSubShaderData) { + buildActiveUniformNameValueMapStructHelper(rSubShaderData, + blockName, + qmlPropertyName); + } else if (textureManager->contains(nodeId)) { + const auto varId = StringToInt::lookupId(blockName + QLatin1Char('.') + qmlPropertyName); + activeUniformNamesToValue.insert(varId, value); + } + } else { // Scalar / Vec + QString varName; + varName.reserve(blockName.length() + 1 + qmlPropertyName.length()); + varName.append(blockName); + varName.append(QLatin1String(".")); + varName.append(qmlPropertyName); + if (uniforms.contains(varName)) { + qCDebug(Shaders) << "UBO scalar member " << varName << " set for update"; + + // If the property needs to be transformed, we transform it here as + // the shaderdata cannot hold transformed properties for multiple + // thread contexts at once + activeUniformNamesToValue.insert(StringToInt::lookupId(varName), + currentShaderData->getTransformedProperty(qmlPropertyName, viewMatrix)); + } + } +} + +void UniformBlockValueBuilder::buildActiveUniformNameValueMapStructHelper(ShaderData *rShaderData, const QString &blockName, const QString &qmlPropertyName) +{ + const QHash &properties = rShaderData->properties(); + auto it = properties.begin(); + const auto end = properties.end(); + + while (it != end) { + QString fullBlockName; + fullBlockName.reserve(blockName.length() + 1 + qmlPropertyName.length()); + fullBlockName.append(blockName); + if (!qmlPropertyName.isEmpty()) { + fullBlockName.append(QLatin1String(".")); + fullBlockName.append(qmlPropertyName); + } + buildActiveUniformNameValueMapHelper(rShaderData, fullBlockName, + it.key(), it.value().value); + ++it; + } +} + +ParameterInfo::ParameterInfo(const int nameId, const HParameter &handle) + : nameId(nameId) + , handle(handle) +{} + +bool ParameterInfo::operator<(const ParameterInfo &other) const Q_DECL_NOEXCEPT +{ + return nameId < other.nameId; +} + +bool ParameterInfo::operator<(const int otherNameId) const Q_DECL_NOEXCEPT +{ + return nameId < otherNameId; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h b/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h new file mode 100644 index 000000000..a8bbd01b4 --- /dev/null +++ b/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h @@ -0,0 +1,188 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDERVIEWJOBUTILS_P_H +#define QT3DRENDER_RENDERVIEWJOBUTILS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DCore { +class QFrameAllocator; +} + +namespace Qt3DRender { +namespace Render { + +class FrameGraphNode; +class ParameterManager; +class Effect; +class Entity; +class Material; +class RenderPass; +class RenderStateSet; +class Technique; +class RenderView; +class TechniqueFilter; +class RenderPassFilter; +class Renderer; +class NodeManagers; +class ShaderDataManager; +struct ShaderUniform; +class ShaderData; +class TextureManager; +class RenderStateManager; +class RenderStateCollection; + +Q_AUTOTEST_EXPORT void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, + const FrameGraphNode *fgLeaf); + +Q_AUTOTEST_EXPORT Technique *findTechniqueForEffect(NodeManagers *manager, + const TechniqueFilter *techniqueFilter, + Effect *effect); + +typedef QVarLengthArray RenderPassList; +Q_AUTOTEST_EXPORT RenderPassList findRenderPassesForTechnique(NodeManagers *manager, + const RenderPassFilter *passFilter, + Technique *technique); + +// Extracts the type T from a QVariant v without using QVariant::value which is slow +// Note: Assumes you are 100% sure about the type you requested +template +inline T variant_value(const QVariant &v) +{ + return *reinterpret_cast(v.data()); +} + +struct ParameterInfo +{ + explicit ParameterInfo(const int nameId = -1, const HParameter &handle = HParameter()); + + int nameId; + HParameter handle; + + bool operator<(const int otherNameId) const Q_DECL_NOEXCEPT; + bool operator<(const ParameterInfo &other) const Q_DECL_NOEXCEPT; +}; +typedef QVector ParameterInfoList; + +struct RenderPassParameterData +{ + RenderPass *pass; + ParameterInfoList parameterInfo; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, RenderPassParameterData, Q_MOVABLE_TYPE) + +using MaterialParameterGathererData = QHash>; + +Q_AUTOTEST_EXPORT void parametersFromMaterialEffectTechnique(ParameterInfoList *infoList, + ParameterManager *manager, + Material *material, + Effect *effect, + Technique *technique); + +Q_AUTOTEST_EXPORT void addParametersForIds(ParameterInfoList *params, ParameterManager *manager, + const QVector ¶meterIds); + +template +void parametersFromParametersProvider(ParameterInfoList *infoList, + ParameterManager *manager, + T *provider) +{ + addParametersForIds(infoList, manager, provider->parameters()); +} + +Q_AUTOTEST_EXPORT ParameterInfoList::const_iterator findParamInfo(ParameterInfoList *infoList, + const int nameId); + +Q_AUTOTEST_EXPORT void addStatesToRenderStateSet(RenderStateSet *stateSet, + const QVector stateIds, + RenderStateManager *manager); + +typedef QHash UniformBlockValueBuilderHash; + +struct Q_AUTOTEST_EXPORT UniformBlockValueBuilder +{ + UniformBlockValueBuilder(); + ~UniformBlockValueBuilder(); + + QT3D_ALIGNED_MALLOC_AND_FREE() + + void buildActiveUniformNameValueMapHelper(ShaderData *currentShaderData, + const QString &blockName, + const QString &qmlPropertyName, + const QVariant &value); + void buildActiveUniformNameValueMapStructHelper(ShaderData *rShaderData, + const QString &blockName, + const QString &qmlPropertyName = QString()); + + bool updatedPropertiesOnly; + QHash uniforms; + UniformBlockValueBuilderHash activeUniformNamesToValue; + ShaderDataManager *shaderDataManager; + TextureManager *textureManager; + Matrix4x4 viewMatrix; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDERVIEWJOBUTILS_P_H diff --git a/src/plugins/renderers/opengl/main.cpp b/src/plugins/renderers/opengl/main.cpp new file mode 100644 index 000000000..61e796788 --- /dev/null +++ b/src/plugins/renderers/opengl/main.cpp @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +QT_BEGIN_NAMESPACE + +class OpenGLRendererPlugin : public Qt3DRender::Render::QRendererPlugin +{ + Q_OBJECT + Q_PLUGIN_METADATA(IID QRendererPluginFactoryInterface_iid FILE "openglrenderer.json") + + Qt3DRender::Render::AbstractRenderer *create(const QString &key, Qt3DRender::QRenderAspect::RenderType renderMode) override + { + Q_UNUSED(key) + return new Qt3DRender::Render::Renderer(renderMode); + } +}; + +QT_END_NAMESPACE + +#include "main.moc" diff --git a/src/plugins/renderers/opengl/managers/gl_handle_types_p.h b/src/plugins/renderers/opengl/managers/gl_handle_types_p.h new file mode 100644 index 000000000..eb25bab7f --- /dev/null +++ b/src/plugins/renderers/opengl/managers/gl_handle_types_p.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H +#define QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class GLBuffer; +class GLTexture; +class OpenGLVertexArrayObject; + +typedef Qt3DCore::QHandle HGLBuffer; +typedef Qt3DCore::QHandle HVao; +typedef Qt3DCore::QHandle HGLTexture; + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H diff --git a/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp b/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp new file mode 100644 index 000000000..67a7422aa --- /dev/null +++ b/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glresourcemanagers_p.h" + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + + +GLResourceManagers::GLResourceManagers() + : m_glBufferManager(new GLBufferManager()) + , m_glShaderManager(new GLShaderManager()) + , m_glTextureManager(new GLTextureManager()) + , m_glFenceManager(new GLFenceManager()) + , m_vaoManager(new VAOManager()) +{ +} + +GLResourceManagers::~GLResourceManagers() +{ + delete m_vaoManager; + delete m_glFenceManager; + delete m_glTextureManager; + delete m_glShaderManager; + delete m_glBufferManager; +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h b/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h new file mode 100644 index 000000000..3597e6965 --- /dev/null +++ b/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h @@ -0,0 +1,135 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H +#define QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT GLFenceManager : public QHash +{ +}; + +class Q_AUTOTEST_EXPORT VAOManager : public Qt3DCore::QResourceManager< + OpenGLVertexArrayObject, + VAOIdentifier, + Qt3DCore::NonLockingPolicy> +{ +public: + VAOManager() {} +}; + +class Q_AUTOTEST_EXPORT GLBufferManager : public Qt3DCore::QResourceManager< + GLBuffer, + Qt3DCore::QNodeId, + Qt3DCore::NonLockingPolicy> +{ +}; + +class Q_AUTOTEST_EXPORT GLTextureManager : public Qt3DCore::QResourceManager< + GLTexture, + Qt3DCore::QNodeId, + Qt3DCore::NonLockingPolicy> +{ +public: + QHash texNodeIdForGLTexture; +}; + +class Q_AUTOTEST_EXPORT GLShaderManager : public APIShaderManager +{ +public: + explicit GLShaderManager() + : APIShaderManager() + {} +}; + + +class Q_AUTOTEST_EXPORT GLResourceManagers +{ +public: + GLResourceManagers(); + ~GLResourceManagers(); + + inline VAOManager *vaoManager() const noexcept { return m_vaoManager; } + inline GLShaderManager *glShaderManager() const noexcept { return m_glShaderManager; } + inline GLTextureManager *glTextureManager() const noexcept { return m_glTextureManager; } + inline GLBufferManager *glBufferManager() const noexcept { return m_glBufferManager; } + inline GLFenceManager *glFenceManager() const noexcept { return m_glFenceManager; } + +private: + GLBufferManager *m_glBufferManager; + GLShaderManager *m_glShaderManager; + GLTextureManager *m_glTextureManager; + GLFenceManager *m_glFenceManager; + VAOManager *m_vaoManager; +}; + +} // Render + +} // Qt3DRender + +Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP) + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H diff --git a/src/plugins/renderers/opengl/managers/managers.pri b/src/plugins/renderers/opengl/managers/managers.pri new file mode 100644 index 000000000..97a4c2c45 --- /dev/null +++ b/src/plugins/renderers/opengl/managers/managers.pri @@ -0,0 +1,8 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/gl_handle_types_p.h \ + $$PWD/glresourcemanagers_p.h + +SOURCES += \ + $$PWD/glresourcemanagers.cpp diff --git a/src/plugins/renderers/opengl/opengl.pri b/src/plugins/renderers/opengl/opengl.pri new file mode 100644 index 000000000..1682ab7b3 --- /dev/null +++ b/src/plugins/renderers/opengl/opengl.pri @@ -0,0 +1,41 @@ +QT += core-private gui-private 3dcore 3dcore-private 3drender 3drender-private +QT_PRIVATE = openglextensions + +# Qt3D is free of Q_FOREACH - make sure it stays that way: +DEFINES += QT_NO_FOREACH +DEFINES += BUILD_QT3D_MODULE + +# For Q_AUTOTEST_EXPORT to work +DEFINES += QT_BUILDING_QT + +DISTFILES += \ + openglrenderer.json + +include (renderer/renderer.pri) +include (jobs/jobs.pri) +include (io/io.pri) +include (textures/textures.pri) +include (graphicshelpers/graphicshelpers.pri) +include (managers/managers.pri) + +!integrity: include (debug/debug.pri) + +INCLUDEPATH += $$PWD + +# Qt3D is free of Q_FOREACH - make sure it stays that way: +DEFINES += QT_NO_FOREACH + +gcov { + QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage + QMAKE_LFLAGS += -fprofile-arcs -ftest-coverage +} + +qtConfig(qt3d-simd-avx2) { + CONFIG += simd + QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_AVX2 +} + +qtConfig(qt3d-simd-sse2):!qtConfig(qt3d-simd-avx2) { + CONFIG += simd + QMAKE_CXXFLAGS += $$QMAKE_CFLAGS_SSE2 +} diff --git a/src/plugins/renderers/opengl/opengl.pro b/src/plugins/renderers/opengl/opengl.pro new file mode 100644 index 000000000..ebd4ff5d1 --- /dev/null +++ b/src/plugins/renderers/opengl/opengl.pro @@ -0,0 +1,10 @@ +TARGET = openglrenderer + +include(opengl.pri) + +SOURCES += \ + main.cpp + +PLUGIN_TYPE = renderers +PLUGIN_CLASS_NAME = OpenGLRendererPlugin +load(qt_plugin) diff --git a/src/plugins/renderers/opengl/openglrenderer.json b/src/plugins/renderers/opengl/openglrenderer.json new file mode 100644 index 000000000..6cafa2ffa --- /dev/null +++ b/src/plugins/renderers/opengl/openglrenderer.json @@ -0,0 +1,3 @@ +{ + "Keys": ["opengl"] +} diff --git a/src/plugins/renderers/opengl/renderer/commandexecuter.cpp b/src/plugins/renderers/opengl/renderer/commandexecuter.cpp new file mode 100644 index 000000000..6498b44b8 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/commandexecuter.cpp @@ -0,0 +1,391 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "commandexecuter_p.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Debug { + +namespace { + +template +QJsonObject typeToJsonObj(const Type &) +{ + return QJsonObject(); +} + +template +QJsonValue typeToJsonValue(const Type &t) +{ + Q_UNUSED(t); + return QJsonValue(); +} + +template<> +QJsonObject typeToJsonObj(const QRectF &rect) +{ + QJsonObject obj; + + obj.insert(QLatin1String("x"), rect.x()); + obj.insert(QLatin1String("y"), rect.y()); + obj.insert(QLatin1String("width"), rect.width()); + obj.insert(QLatin1String("height"), rect.height()); + + return obj; +} + +template<> +QJsonValue typeToJsonValue(const QRectF &rect) +{ + QJsonArray value; + + value.push_back(rect.x()); + value.push_back(rect.y()); + value.push_back(rect.width()); + value.push_back(rect.height()); + + return value; +} + +template<> +QJsonObject typeToJsonObj(const QSize &s) +{ + QJsonObject obj; + + obj.insert(QLatin1String("width"), s.width()); + obj.insert(QLatin1String("height"), s.height()); + + return obj; +} + +template<> +QJsonValue typeToJsonValue(const QSize &s) +{ + QJsonArray value; + + value.push_back(s.width()); + value.push_back(s.height()); + + return value; +} + +template<> +QJsonObject typeToJsonObj(const QVector3D &v) +{ + QJsonObject obj; + + obj.insert(QLatin1String("x"), v.x()); + obj.insert(QLatin1String("y"), v.y()); + obj.insert(QLatin1String("z"), v.z()); + + return obj; +} + +template<> +QJsonValue typeToJsonValue(const QVector3D &v) +{ + QJsonArray value; + + value.push_back(v.x()); + value.push_back(v.y()); + value.push_back(v.z()); + + return value; +} + +template<> +QJsonObject typeToJsonObj(const Qt3DCore::QNodeId &v) +{ + QJsonObject obj; + obj.insert(QLatin1String("id"), qint64(v.id())); + return obj; +} + +template<> +QJsonValue typeToJsonValue(const Qt3DCore::QNodeId &v) +{ + QJsonValue value(qint64(v.id())); + return value; +} + +template<> +QJsonObject typeToJsonObj(const QVector4D &v) +{ + QJsonObject obj; + + obj.insert(QLatin1String("x"), v.x()); + obj.insert(QLatin1String("y"), v.y()); + obj.insert(QLatin1String("z"), v.z()); + obj.insert(QLatin1String("w"), v.w()); + + return obj; +} + +template<> +QJsonValue typeToJsonValue(const QVector4D &v) +{ + QJsonArray value; + + value.push_back(v.x()); + value.push_back(v.y()); + value.push_back(v.z()); + value.push_back(v.w()); + + return value; +} + +template<> +QJsonObject typeToJsonObj(const QMatrix4x4 &v) +{ + QJsonObject obj; + + obj.insert(QLatin1String("row 0"), typeToJsonObj(v.row(0))); + obj.insert(QLatin1String("row 1"), typeToJsonObj(v.row(0))); + obj.insert(QLatin1String("row 2"), typeToJsonObj(v.row(0))); + obj.insert(QLatin1String("row 3"), typeToJsonObj(v.row(0))); + + return obj; +} + +template<> +QJsonValue typeToJsonValue(const QMatrix4x4 &v) +{ + QJsonArray value; + + value.push_back(typeToJsonValue(v.row(0))); + value.push_back(typeToJsonValue(v.row(1))); + value.push_back(typeToJsonValue(v.row(2))); + value.push_back(typeToJsonValue(v.row(3))); + + return value; +} + +template<> +QJsonValue typeToJsonValue(const QVariant &v) +{ + const int nodeTypeId = qMetaTypeId(); + + if (v.userType() == nodeTypeId) + return typeToJsonValue(v.value()); + + switch (v.userType()) { + case QMetaType::QVector3D: + return typeToJsonValue(v.value()); + case QMetaType::QVector4D: + return typeToJsonValue(v.value()); + case QMetaType::QMatrix4x4: + return typeToJsonValue(v.value()); + default: + return QJsonValue::fromVariant(v); + } +} + +template +QJsonObject backendNodeToJSon(Handle handle, Manager *manager) +{ + Qt3DCore::QBackendNode *node = manager->data(handle); + QJsonObject obj; + Qt3DCore::QNodeId id; + if (node != nullptr) + id = node->peerId(); + obj.insert(QLatin1String("id"), qint64(id.id())); + return obj; +} + +QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) +{ + QJsonObject obj; + + const Render::PackUniformHash &uniforms = pack.uniforms(); + QJsonArray uniformsArray; + for (int i = 0, m = uniforms.keys.size(); i < m; ++i) { + QJsonObject uniformObj; + uniformObj.insert(QLatin1String("name"), Render::StringToInt::lookupString(uniforms.keys.at(i))); + const Render::UniformValue::ValueType type = uniforms.values.at(i).valueType(); + uniformObj.insert(QLatin1String("type"), + type == Render::UniformValue::ScalarValue + ? QLatin1String("value") + : QLatin1String("texture")); + uniformsArray.push_back(uniformObj); + } + obj.insert(QLatin1String("uniforms"), uniformsArray); + + QJsonArray texturesArray; + const QVector &textures = pack.textures(); + for (const auto & texture : textures) { + QJsonObject textureObj; + textureObj.insert(QLatin1String("name"), Render::StringToInt::lookupString(texture.glslNameId)); + textureObj.insert(QLatin1String("id"), qint64(texture.nodeId.id())); + texturesArray.push_back(textureObj); + } + obj.insert(QLatin1String("textures"), texturesArray); + + const QVector &ubos = pack.uniformBuffers(); + QJsonArray ubosArray; + for (const auto &ubo : ubos) { + QJsonObject uboObj; + uboObj.insert(QLatin1String("index"), ubo.m_blockIndex); + uboObj.insert(QLatin1String("bufferId"), qint64(ubo.m_bufferID.id())); + ubosArray.push_back(uboObj); + + } + obj.insert(QLatin1String("ubos"), ubosArray); + + const QVector &ssbos = pack.shaderStorageBuffers(); + QJsonArray ssbosArray; + for (const auto &ssbo : ssbos) { + QJsonObject ssboObj; + ssboObj.insert(QLatin1String("index"), ssbo.m_blockIndex); + ssboObj.insert(QLatin1String("bufferId"), qint64(ssbo.m_bufferID.id())); + ssbosArray.push_back(ssboObj); + } + obj.insert(QLatin1String("ssbos"), ssbosArray); + + return obj; +} + +} // anonymous + +CommandExecuter::CommandExecuter(Render::Renderer *renderer) + : m_renderer(renderer) +{ +} + +// Render thread +void CommandExecuter::performAsynchronousCommandExecution(const QVector &views) +{ + QMutexLocker lock(&m_pendingCommandsMutex); + const QVector shellCommands = std::move(m_pendingCommands); + lock.unlock(); + + for (auto *reply : shellCommands) { + if (reply->commandName() == QLatin1String("glinfo")) { + QJsonObject replyObj; + const GraphicsApiFilterData *contextInfo = m_renderer->submissionContext()->contextInfo(); + if (contextInfo != nullptr) { + replyObj.insert(QLatin1String("api"), + contextInfo->m_api == QGraphicsApiFilter::OpenGL + ? QLatin1String("OpenGL") + : QLatin1String("OpenGLES")); + const QString versionString = + QString::number(contextInfo->m_major) + + QStringLiteral(".") + + QString::number(contextInfo->m_minor); + replyObj.insert(QLatin1String("version"), versionString); + replyObj.insert(QLatin1String("profile"), + contextInfo->m_profile == QGraphicsApiFilter::CoreProfile + ? QLatin1String("Core") + : contextInfo->m_profile == QGraphicsApiFilter::CompatibilityProfile + ? QLatin1String("Compatibility") + : QLatin1String("None")); + } + reply->setData(QJsonDocument(replyObj).toJson()); + } else if (reply->commandName() == QLatin1String("rendercommands")) { + QJsonObject replyObj; + + QJsonArray viewArray; + for (Render::RenderView *v : views) { + QJsonObject viewObj; + viewObj.insert(QLatin1String("viewport"), typeToJsonValue(v->viewport())); + viewObj.insert(QLatin1String("surfaceSize"), typeToJsonValue(v->surfaceSize())); + viewObj.insert(QLatin1String("devicePixelRatio"), v->devicePixelRatio()); + viewObj.insert(QLatin1String("noDraw"), v->noDraw()); + viewObj.insert(QLatin1String("frustumCulling"), v->frustumCulling()); + viewObj.insert(QLatin1String("compute"), v->isCompute()); + viewObj.insert(QLatin1String("clearDepthValue"), v->clearDepthValue()); + viewObj.insert(QLatin1String("clearStencilValue"), v->clearStencilValue()); + + QJsonArray renderCommandsArray; + for (const Render::RenderCommand &c : v->commands()) { + QJsonObject commandObj; + Render::NodeManagers *nodeManagers = m_renderer->nodeManagers(); + commandObj.insert(QLatin1String("shader"), typeToJsonValue(QVariant::fromValue(c.m_shaderId))); + commandObj.insert(QLatin1String("vao"), double(c.m_vao.handle())); + commandObj.insert(QLatin1String("instanceCount"), c.m_instanceCount); + commandObj.insert(QLatin1String("geometry"), backendNodeToJSon(c.m_geometry, nodeManagers->geometryManager())); + commandObj.insert(QLatin1String("geometryRenderer"), backendNodeToJSon(c.m_geometryRenderer, nodeManagers->geometryRendererManager())); + commandObj.insert(QLatin1String("shaderParameterPack"), parameterPackToJson(c.m_parameterPack)); + + renderCommandsArray.push_back(commandObj); + } + viewObj.insert(QLatin1String("commands"), renderCommandsArray); + viewArray.push_back(viewObj); + } + + replyObj.insert(QLatin1String("renderViews"), viewArray); + reply->setData(QJsonDocument(replyObj).toJson()); + } + reply->setFinished(true); + } +} + +// Main thread +QVariant CommandExecuter::executeCommand(const QStringList &args) +{ + // Note: The replies will be deleted by the AspectCommandDebugger + if (args.length() > 0 && + (args.first() == QLatin1String("glinfo") || + args.first() == QLatin1String("rendercommands"))) { + auto reply = new Qt3DCore::Debug::AsynchronousCommandReply(args.first()); + QMutexLocker lock(&m_pendingCommandsMutex); + m_pendingCommands.push_back(reply); + return QVariant::fromValue(reply); + } + return QVariant(); +} + +} // Debug + +} // Qt3DRenderer + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/commandexecuter_p.h b/src/plugins/renderers/opengl/renderer/commandexecuter_p.h new file mode 100644 index 000000000..2d90bf4d6 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/commandexecuter_p.h @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_DEBUG_COMMANDEXECUTER_H +#define QT3DRENDER_DEBUG_COMMANDEXECUTER_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DCore { + +namespace Debug { +class AsynchronousCommandReply; +} // Debug + +} // Qt3DCore + +namespace Qt3DRender { + +namespace Render { +class Renderer; +class RenderView; +} // Render + +namespace Debug { + +class CommandExecuter +{ +public: + explicit CommandExecuter(Render::Renderer *renderer); + + void performAsynchronousCommandExecution(const QVector &views); + + QVariant executeCommand(const QStringList &args); + +private: + Render::Renderer *m_renderer; + QVector m_pendingCommands; + QMutex m_pendingCommandsMutex; +}; + +} // Debug + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_DEBUG_COMMANDEXECUTER_H diff --git a/src/plugins/renderers/opengl/renderer/glfence_p.h b/src/plugins/renderers/opengl/renderer/glfence_p.h new file mode 100644 index 000000000..366065048 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/glfence_p.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLFENCE_P_H +#define GLFENCE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +// GLsync is a pointer to a struct (unlike the rest of GL which used int ids) +// We cannot reference GLsync as it's only available since 3.2 We use FenceId +// to wrap that around and trust the GLHelpers will convert them accordingly. +using GLFence = void *; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + + +#endif // GLFENCE_P_H diff --git a/src/plugins/renderers/opengl/renderer/glshader.cpp b/src/plugins/renderers/opengl/renderer/glshader.cpp new file mode 100644 index 000000000..02fa2de6d --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/glshader.cpp @@ -0,0 +1,316 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glshader_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +GLShader::GLShader() + : m_isLoaded(false) + , m_graphicsContext(nullptr) +{ + m_shaderCode.resize(static_cast(QShaderProgram::Compute) + 1); +} + +void GLShader::setGraphicsContext(GraphicsContext *context) +{ + QMutexLocker lock(&m_mutex); + m_graphicsContext = context; + if (m_graphicsContext) { + m_contextConnection = QObject::connect(m_graphicsContext->openGLContext(), + &QOpenGLContext::aboutToBeDestroyed, + [this] { setGraphicsContext(nullptr); }); + } +} + +GraphicsContext *GLShader::graphicsContext() +{ + QMutexLocker lock(&m_mutex); + return m_graphicsContext; +} + + +QVector GLShader::uniformsNames() const +{ + return m_uniformsNames; +} + +QVector GLShader::attributesNames() const +{ + return m_attributesNames; +} + +QVector GLShader::uniformBlockNames() const +{ + return m_uniformBlockNames; +} + +QVector GLShader::storageBlockNames() const +{ + return m_shaderStorageBlockNames; +} + +QVector GLShader::shaderCode() const +{ + return m_shaderCode; +} + +QHash GLShader::activeUniformsForUniformBlock(int blockIndex) const +{ + return m_uniformBlockIndexToShaderUniforms.value(blockIndex); +} + +ShaderUniformBlock GLShader::uniformBlockForBlockIndex(int blockIndex) +{ + for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { + if (m_uniformBlocks[i].m_index == blockIndex) { + return m_uniformBlocks[i]; + } + } + return ShaderUniformBlock(); +} + +ShaderUniformBlock GLShader::uniformBlockForBlockNameId(int blockNameId) +{ + for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { + if (m_uniformBlocks[i].m_nameId == blockNameId) { + return m_uniformBlocks[i]; + } + } + return ShaderUniformBlock(); +} + +ShaderUniformBlock GLShader::uniformBlockForBlockName(const QString &blockName) +{ + for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { + if (m_uniformBlocks[i].m_name == blockName) { + return m_uniformBlocks[i]; + } + } + return ShaderUniformBlock(); +} + +ShaderStorageBlock GLShader::storageBlockForBlockIndex(int blockIndex) +{ + for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { + if (m_shaderStorageBlocks[i].m_index == blockIndex) + return m_shaderStorageBlocks[i]; + } + return ShaderStorageBlock(); +} + +ShaderStorageBlock GLShader::storageBlockForBlockNameId(int blockNameId) +{ + for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { + if (m_shaderStorageBlocks[i].m_nameId == blockNameId) + return m_shaderStorageBlocks[i]; + } + return ShaderStorageBlock(); +} + +ShaderStorageBlock GLShader::storageBlockForBlockName(const QString &blockName) +{ + for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { + if (m_shaderStorageBlocks[i].m_name == blockName) + return m_shaderStorageBlocks[i]; + } + return ShaderStorageBlock(); +} + +void GLShader::prepareUniforms(ShaderParameterPack &pack) +{ + const PackUniformHash &values = pack.uniforms(); + + auto it = values.keys.cbegin(); + const auto end = values.keys.cend(); + + while (it != end) { + // Find if there's a uniform with the same name id + for (const ShaderUniform &uniform : qAsConst(m_uniforms)) { + if (uniform.m_nameId == *it) { + pack.setSubmissionUniform(uniform); + break; + } + } + ++it; + } +} + +void GLShader::setFragOutputs(const QHash &fragOutputs) +{ + { + QMutexLocker lock(&m_mutex); + m_fragOutputs = fragOutputs; + } +// updateDNA(); +} + +const QHash GLShader::fragOutputs() const +{ + QMutexLocker lock(&m_mutex); + return m_fragOutputs; +} + +void GLShader::initializeUniforms(const QVector &uniformsDescription) +{ + m_uniforms = uniformsDescription; + m_uniformsNames.resize(uniformsDescription.size()); + m_uniformsNamesIds.reserve(uniformsDescription.size()); + m_standardUniformNamesIds.reserve(5); + QHash activeUniformsInDefaultBlock; + + static const QVector standardUniformNameIds = { + Shader::modelMatrixNameId, + Shader::viewMatrixNameId, + Shader::projectionMatrixNameId, + Shader::modelViewMatrixNameId, + Shader::viewProjectionMatrixNameId, + Shader::modelViewProjectionNameId, + Shader::mvpNameId, + Shader::inverseModelMatrixNameId, + Shader::inverseViewMatrixNameId, + Shader::inverseProjectionMatrixNameId, + Shader::inverseModelViewNameId, + Shader::inverseViewProjectionMatrixNameId, + Shader::inverseModelViewProjectionNameId, + Shader::modelNormalMatrixNameId, + Shader::modelViewNormalNameId, + Shader::viewportMatrixNameId, + Shader::inverseViewportMatrixNameId, + Shader::aspectRatioNameId, + Shader::exposureNameId, + Shader::gammaNameId, + Shader::timeNameId, + Shader::eyePositionNameId, + Shader::skinningPaletteNameId, + }; + + for (int i = 0, m = uniformsDescription.size(); i < m; i++) { + m_uniformsNames[i] = m_uniforms[i].m_name; + const int nameId = StringToInt::lookupId(m_uniformsNames[i]); + m_uniforms[i].m_nameId = nameId; + + // Is the uniform a Qt3D "Standard" uniform or a user defined one? + if (standardUniformNameIds.contains(nameId)) + m_standardUniformNamesIds.push_back(nameId); + else + m_uniformsNamesIds.push_back(nameId); + + if (uniformsDescription[i].m_blockIndex == -1) { // Uniform is in default block + qCDebug(Shaders) << "Active Uniform in Default Block " << uniformsDescription[i].m_name << uniformsDescription[i].m_blockIndex; + activeUniformsInDefaultBlock.insert(uniformsDescription[i].m_name, uniformsDescription[i]); + } + } + m_uniformBlockIndexToShaderUniforms.insert(-1, activeUniformsInDefaultBlock); +} + +void GLShader::initializeAttributes(const QVector &attributesDescription) +{ + m_attributes = attributesDescription; + m_attributesNames.resize(attributesDescription.size()); + m_attributeNamesIds.resize(attributesDescription.size()); + for (int i = 0, m = attributesDescription.size(); i < m; i++) { + m_attributesNames[i] = attributesDescription[i].m_name; + m_attributes[i].m_nameId = StringToInt::lookupId(m_attributesNames[i]); + m_attributeNamesIds[i] = m_attributes[i].m_nameId; + qCDebug(Shaders) << "Active Attribute " << attributesDescription[i].m_name; + } +} + +void GLShader::initializeUniformBlocks(const QVector &uniformBlockDescription) +{ + m_uniformBlocks = uniformBlockDescription; + m_uniformBlockNames.resize(uniformBlockDescription.size()); + m_uniformBlockNamesIds.resize(uniformBlockDescription.size()); + for (int i = 0, m = uniformBlockDescription.size(); i < m; ++i) { + m_uniformBlockNames[i] = m_uniformBlocks[i].m_name; + m_uniformBlockNamesIds[i] = StringToInt::lookupId(m_uniformBlockNames[i]); + m_uniformBlocks[i].m_nameId = m_uniformBlockNamesIds[i]; + qCDebug(Shaders) << "Initializing Uniform Block {" << m_uniformBlockNames[i] << "}"; + + // Find all active uniforms for the shader block + QVector::const_iterator uniformsIt = m_uniforms.cbegin(); + const QVector::const_iterator uniformsEnd = m_uniforms.cend(); + + QVector::const_iterator uniformNamesIt = m_uniformsNames.cbegin(); + const QVector::const_iterator uniformNamesEnd = m_attributesNames.cend(); + + QHash activeUniformsInBlock; + + while (uniformsIt != uniformsEnd && uniformNamesIt != uniformNamesEnd) { + if (uniformsIt->m_blockIndex == uniformBlockDescription[i].m_index) { + QString uniformName = *uniformNamesIt; + if (!m_uniformBlockNames[i].isEmpty() && !uniformName.startsWith(m_uniformBlockNames[i])) + uniformName = m_uniformBlockNames[i] + QLatin1Char('.') + *uniformNamesIt; + activeUniformsInBlock.insert(uniformName, *uniformsIt); + qCDebug(Shaders) << "Active Uniform Block " << uniformName << " in block " << m_uniformBlockNames[i] << " at index " << uniformsIt->m_blockIndex; + } + ++uniformsIt; + ++uniformNamesIt; + } + m_uniformBlockIndexToShaderUniforms.insert(uniformBlockDescription[i].m_index, activeUniformsInBlock); + } +} + +void GLShader::initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription) +{ + m_shaderStorageBlocks = shaderStorageBlockDescription; + m_shaderStorageBlockNames.resize(shaderStorageBlockDescription.size()); + m_shaderStorageBlockNamesIds.resize(shaderStorageBlockDescription.size()); + + for (int i = 0, m = shaderStorageBlockDescription.size(); i < m; ++i) { + m_shaderStorageBlockNames[i] = m_shaderStorageBlocks[i].m_name; + m_shaderStorageBlockNamesIds[i] = StringToInt::lookupId(m_shaderStorageBlockNames[i]); + m_shaderStorageBlocks[i].m_nameId =m_shaderStorageBlockNamesIds[i]; + qCDebug(Shaders) << "Initializing Shader Storage Block {" << m_shaderStorageBlockNames[i] << "}"; + } +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/glshader_p.h b/src/plugins/renderers/opengl/renderer/glshader_p.h new file mode 100644 index 000000000..18293ac54 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/glshader_p.h @@ -0,0 +1,160 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GLSHADER_P_H +#define QT3DRENDER_RENDER_GLSHADER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + + +#include +#include +#include +#include + + +QT_BEGIN_NAMESPACE + +class QOpenGLShaderProgram; + +namespace Qt3DRender { + +namespace Render { + +class Q_AUTOTEST_EXPORT GLShader +{ +public: + GLShader(); + + void setGraphicsContext(GraphicsContext *context); + GraphicsContext *graphicsContext(); + + bool isLoaded() const { return m_isLoaded; } + void setLoaded(bool loaded) { m_isLoaded = loaded; } + + void prepareUniforms(ShaderParameterPack &pack); + + void setFragOutputs(const QHash &fragOutputs); + const QHash fragOutputs() const; + + inline QVector uniformsNamesIds() const { return m_uniformsNamesIds; } + inline QVector standardUniformNameIds() const { return m_standardUniformNamesIds; } + inline QVector uniformBlockNamesIds() const { return m_uniformBlockNamesIds; } + inline QVector storageBlockNamesIds() const { return m_shaderStorageBlockNamesIds; } + inline QVector attributeNamesIds() const { return m_attributeNamesIds; } + + QVector uniformsNames() const; + QVector attributesNames() const; + QVector uniformBlockNames() const; + QVector storageBlockNames() const; + + inline QVector uniforms() const { return m_uniforms; } + inline QVector attributes() const { return m_attributes; } + inline QVector uniformBlocks() const { return m_uniformBlocks; } + inline QVector storageBlocks() const { return m_shaderStorageBlocks; } + + QHash activeUniformsForUniformBlock(int blockIndex) const; + + ShaderUniformBlock uniformBlockForBlockIndex(int blockNameId); + ShaderUniformBlock uniformBlockForBlockNameId(int blockIndex); + ShaderUniformBlock uniformBlockForBlockName(const QString &blockName); + + ShaderStorageBlock storageBlockForBlockIndex(int blockIndex); + ShaderStorageBlock storageBlockForBlockNameId(int blockNameId); + ShaderStorageBlock storageBlockForBlockName(const QString &blockName); + + QOpenGLShaderProgram *shaderProgram() { return &m_shader; } + + void setShaderCode(const QVector shaderCode) { m_shaderCode = shaderCode; } + QVector shaderCode() const; + +private: + bool m_isLoaded; + QOpenGLShaderProgram m_shader; + GraphicsContext *m_graphicsContext; + + QVector m_uniformsNames; + QVector m_uniformsNamesIds; + QVector m_standardUniformNamesIds; + QVector m_uniforms; + + QVector m_attributesNames; + QVector m_attributeNamesIds; + QVector m_attributes; + + QVector m_uniformBlockNames; + QVector m_uniformBlockNamesIds; + QVector m_uniformBlocks; + QHash > m_uniformBlockIndexToShaderUniforms; + + QVector m_shaderStorageBlockNames; + QVector m_shaderStorageBlockNamesIds; + QVector m_shaderStorageBlocks; + + QHash m_fragOutputs; + QVector m_shaderCode; + + // Private so that only GraphicContext can call it + void initializeUniforms(const QVector &uniformsDescription); + void initializeAttributes(const QVector &attributesDescription); + void initializeUniformBlocks(const QVector &uniformBlockDescription); + void initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription); + + friend class GraphicsContext; + + mutable QMutex m_mutex; + QMetaObject::Connection m_contextConnection; +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GLSHADER_P_H diff --git a/src/plugins/renderers/opengl/renderer/logging.cpp b/src/plugins/renderers/opengl/renderer/logging.cpp new file mode 100644 index 000000000..ab7437eba --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/logging.cpp @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "logging_p.h" + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +Q_LOGGING_CATEGORY(Backend, "Qt3D.Renderer.OpenGL.Backend", QtWarningMsg) +Q_LOGGING_CATEGORY(Frontend, "Qt3D.Renderer.OpenGL.Frontend", QtWarningMsg) +Q_LOGGING_CATEGORY(Io, "Qt3D.Renderer.OpenGL.IO", QtWarningMsg) +Q_LOGGING_CATEGORY(Jobs, "Qt3D.Renderer.OpenGL.Jobs", QtWarningMsg) +Q_LOGGING_CATEGORY(SceneLoaders, "Qt3D.Renderer.OpenGL.SceneLoaders", QtWarningMsg) +Q_LOGGING_CATEGORY(Framegraph, "Qt3D.Renderer.OpenGL.Framegraph", QtWarningMsg) +Q_LOGGING_CATEGORY(RenderNodes, "Qt3D.Renderer.OpenGL.RenderNodes", QtWarningMsg) +Q_LOGGING_CATEGORY(Rendering, "Qt3D.Renderer.OpenGL.Rendering", QtWarningMsg) +Q_LOGGING_CATEGORY(Memory, "Qt3D.Renderer.OpenGL.Memory", QtWarningMsg) +Q_LOGGING_CATEGORY(Shaders, "Qt3D.Renderer.OpenGL.Shaders", QtWarningMsg) +Q_LOGGING_CATEGORY(RenderStates, "Qt3D.Renderer.OpenGL.RenderStates", QtWarningMsg) +Q_LOGGING_CATEGORY(VSyncAdvanceService, "Qt3D.Renderer.OpenGL.VsyncAdvanceService", QtWarningMsg) + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/logging_p.h b/src/plugins/renderers/opengl/renderer/logging_p.h new file mode 100644 index 000000000..8a550e22f --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/logging_p.h @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERLOGGING_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERLOGGING_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +Q_DECLARE_LOGGING_CATEGORY(Backend) +Q_DECLARE_LOGGING_CATEGORY(Frontend) +Q_DECLARE_LOGGING_CATEGORY(Io) +Q_DECLARE_LOGGING_CATEGORY(Jobs) +Q_DECLARE_LOGGING_CATEGORY(SceneLoaders) +Q_DECLARE_LOGGING_CATEGORY(Framegraph) +Q_DECLARE_LOGGING_CATEGORY(RenderNodes) +Q_DECLARE_LOGGING_CATEGORY(Rendering) +Q_DECLARE_LOGGING_CATEGORY(Memory) +Q_DECLARE_LOGGING_CATEGORY(Shaders) +Q_DECLARE_LOGGING_CATEGORY(RenderStates) +Q_DECLARE_LOGGING_CATEGORY(VSyncAdvanceService) + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_OPENGL_RENDERLOGGING_P_H diff --git a/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp new file mode 100644 index 000000000..19ae4fa55 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp @@ -0,0 +1,165 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "openglvertexarrayobject_p.h" +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +OpenGLVertexArrayObject::OpenGLVertexArrayObject() + : m_ctx(nullptr) + , m_specified(false) + , m_supportsVao(false) +{} + +void OpenGLVertexArrayObject::bind() +{ + Q_ASSERT(m_ctx); + if (m_supportsVao) { + Q_ASSERT(!m_vao.isNull()); + Q_ASSERT(m_vao->isCreated()); + m_vao->bind(); + } else { + // Unbind any other VAO that may have been bound and not released correctly + if (m_ctx->m_currentVAO != nullptr && m_ctx->m_currentVAO != this) + m_ctx->m_currentVAO->release(); + + m_ctx->m_currentVAO = this; + // We need to specify array and vertex attributes + for (const SubmissionContext::VAOVertexAttribute &attr : qAsConst(m_vertexAttributes)) + m_ctx->enableAttribute(attr); + if (!m_indexAttribute.isNull()) + m_ctx->bindGLBuffer(m_ctx->m_renderer->glResourceManagers()->glBufferManager()->data(m_indexAttribute), + GLBuffer::IndexBuffer); + } +} + +void OpenGLVertexArrayObject::release() +{ + Q_ASSERT(m_ctx); + if (m_supportsVao) { + Q_ASSERT(!m_vao.isNull()); + Q_ASSERT(m_vao->isCreated()); + m_vao->release(); + } else { + if (m_ctx->m_currentVAO == this) { + for (const SubmissionContext::VAOVertexAttribute &attr : qAsConst(m_vertexAttributes)) + m_ctx->disableAttribute(attr); + m_ctx->m_currentVAO = nullptr; + } + } +} + +// called from Render thread +void OpenGLVertexArrayObject::create(SubmissionContext *ctx, const VAOIdentifier &key) +{ + QMutexLocker lock(&m_mutex); + + Q_ASSERT(!m_ctx && !m_vao); + + m_ctx = ctx; + m_supportsVao = m_ctx->supportsVAO(); + if (m_supportsVao) { + m_vao.reset(new QOpenGLVertexArrayObject()); + m_vao->create(); + } + m_owners = key; +} + +VAOIdentifier OpenGLVertexArrayObject::key() const +{ + return m_owners; +} + +// called from Render thread +void OpenGLVertexArrayObject::destroy() +{ + QMutexLocker locker(&m_mutex); + + Q_ASSERT(m_ctx); + cleanup(); +} + +void OpenGLVertexArrayObject::cleanup() +{ + m_vao.reset(); + m_ctx = nullptr; + m_specified = false; + m_supportsVao = false; + m_indexAttribute = SubmissionContext::VAOIndexAttribute(); + m_vertexAttributes.clear(); +} + +// called from job +bool OpenGLVertexArrayObject::isAbandoned(GeometryManager *geomMgr, GLShaderManager *shaderMgr) +{ + QMutexLocker lock(&m_mutex); + + if (!m_ctx) + return false; + + const bool geometryExists = (geomMgr->data(m_owners.first) != nullptr); + const bool shaderExists = (shaderMgr->lookupResource(m_owners.second) != nullptr); + + return !geometryExists || !shaderExists; +} + +void OpenGLVertexArrayObject::saveVertexAttribute(const SubmissionContext::VAOVertexAttribute &attr) +{ + // Remove any vertexAttribute already at location + for (auto i = m_vertexAttributes.size() - 1; i >= 0; --i) { + if (m_vertexAttributes.at(i).location == attr.location) { + m_vertexAttributes.removeAt(i); + break; + } + } + m_vertexAttributes.push_back(attr); +} + + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h new file mode 100644 index 000000000..99cf51ee8 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h @@ -0,0 +1,111 @@ +/**************************************************************************** +** +** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef OPENGLVERTEXARRAYOBJECT_H +#define OPENGLVERTEXARRAYOBJECT_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +class GeometryManager; +class GLShaderManager; + +typedef QPair VAOIdentifier; + +class Q_AUTOTEST_EXPORT OpenGLVertexArrayObject +{ +public: + OpenGLVertexArrayObject(); + + void bind(); + void release(); + + void create(SubmissionContext *ctx, const VAOIdentifier &key); + VAOIdentifier key() const; + void destroy(); + void cleanup(); + + bool isAbandoned(GeometryManager *geomMgr, GLShaderManager *shaderMgr); + + QOpenGLVertexArrayObject *vao() { return m_vao.data(); } + const QOpenGLVertexArrayObject *vao() const { return m_vao.data(); } + + void setSpecified(bool b) { m_specified = b; } + bool isSpecified() const { return m_specified; } + + +private: + QMutex m_mutex; + SubmissionContext *m_ctx; + QScopedPointer m_vao; + bool m_specified; + bool m_supportsVao; + VAOIdentifier m_owners; + + friend class SubmissionContext; + + void saveVertexAttribute(const SubmissionContext::VAOVertexAttribute &attr); + inline void saveIndexAttribute(HGLBuffer glBufferHandle) { m_indexAttribute = glBufferHandle; } + + QVector m_vertexAttributes; + SubmissionContext::VAOIndexAttribute m_indexAttribute; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // OPENGLVERTEXARRAYOBJECT_H diff --git a/src/plugins/renderers/opengl/renderer/rendercommand.cpp b/src/plugins/renderers/opengl/renderer/rendercommand.cpp new file mode 100644 index 000000000..c6d42fde1 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/rendercommand.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "rendercommand_p.h" + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +RenderCommand::RenderCommand() + : m_glShader(nullptr) + , m_stateSet(nullptr) + , m_depth(0.0f) + , m_changeCost(0) + , m_type(RenderCommand::Draw) + , m_primitiveCount(0) + , m_primitiveType(QGeometryRenderer::Triangles) + , m_restartIndexValue(-1) + , m_firstInstance(0) + , m_firstVertex(0) + , m_verticesPerPatch(0) + , m_instanceCount(0) + , m_indexOffset(0) + , m_indexAttributeByteOffset(0) + , m_indexAttributeDataType(GL_UNSIGNED_SHORT) + , m_indirectAttributeByteOffset(0) + , m_drawIndexed(false) + , m_drawIndirect(false) + , m_primitiveRestartEnabled(false) + , m_isValid(false) +{ + m_workGroups[0] = 0; + m_workGroups[1] = 0; + m_workGroups[2] = 0; +} + +bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept +{ + return (a.m_vao == b.m_vao && a.m_glShader == b.m_glShader && a.m_material == b.m_material && + a.m_stateSet == b.m_stateSet && a.m_geometry == b.m_geometry && a.m_geometryRenderer == b.m_geometryRenderer && + a.m_indirectDrawBuffer == b.m_indirectDrawBuffer && a.m_activeAttributes == b.m_activeAttributes && + a.m_depth == b.m_depth && a.m_changeCost == b.m_changeCost && a.m_shaderId == b.m_shaderId && + a.m_workGroups[0] == b.m_workGroups[0] && a.m_workGroups[1] == b.m_workGroups[1] && a.m_workGroups[2] == b.m_workGroups[2] && + a.m_primitiveCount == b.m_primitiveCount && a.m_primitiveType == b.m_primitiveType && a.m_restartIndexValue == b.m_restartIndexValue && + a.m_firstInstance == b.m_firstInstance && a.m_firstVertex == b.m_firstVertex && a.m_verticesPerPatch == b.m_verticesPerPatch && + a.m_instanceCount == b.m_instanceCount && a.m_indexOffset == b.m_indexOffset && a.m_indexAttributeByteOffset == b.m_indexAttributeByteOffset && + a.m_drawIndexed == b.m_drawIndexed && a.m_drawIndirect == b.m_drawIndirect && a.m_primitiveRestartEnabled == b.m_primitiveRestartEnabled && + a.m_isValid == b.m_isValid && a.m_computeCommand == b.m_computeCommand); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/rendercommand_p.h b/src/plugins/renderers/opengl/renderer/rendercommand_p.h new file mode 100644 index 000000000..600c52959 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/rendercommand_p.h @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERCOMMAND_H +#define QT3DRENDER_RENDER_RENDERCOMMAND_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLVertexArrayObject; + +namespace Qt3DRender { + +namespace Render { + +class RenderStateSet; +using RenderStateSetPtr = QSharedPointer; +class GLShader; + +class Q_AUTOTEST_EXPORT RenderCommand +{ +public: + RenderCommand(); + + HVao m_vao; // VAO used during the submission step to store all states and VBOs + HMaterial m_material; // Purely used to ease sorting (minimize stage changes, binding changes ....) + GLShader *m_glShader; // GL Shader to be used at render time + Qt3DCore::QNodeId m_shaderId; // Shader for given pass and mesh + ShaderParameterPack m_parameterPack; // Might need to be reworked so as to be able to destroy the + // Texture while submission is happening. + RenderStateSetPtr m_stateSet; + + HGeometry m_geometry; + HGeometryRenderer m_geometryRenderer; + + HBuffer m_indirectDrawBuffer; // Reference to indirect draw buffer (valid only m_drawIndirect == true) + HComputeCommand m_computeCommand; + + // A QAttribute pack might be interesting + // This is a temporary fix in the meantime, to remove the hacked methods in Technique + QVector m_activeAttributes; + + float m_depth; + int m_changeCost; + + enum CommandType { + Draw, + Compute + }; + + CommandType m_type; + int m_workGroups[3]; + + // Values filled for draw calls by Renderer (in prepare Submission) + GLsizei m_primitiveCount; + QGeometryRenderer::PrimitiveType m_primitiveType; + int m_restartIndexValue; + int m_firstInstance; + int m_firstVertex; + int m_verticesPerPatch; + int m_instanceCount; + int m_indexOffset; + uint m_indexAttributeByteOffset; + GLint m_indexAttributeDataType; + uint m_indirectAttributeByteOffset; + bool m_drawIndexed; + bool m_drawIndirect; + bool m_primitiveRestartEnabled; + bool m_isValid; +}; + +Q_AUTOTEST_EXPORT bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept; + +inline bool operator!=(const RenderCommand &lhs, const RenderCommand &rhs) noexcept +{ return !operator==(lhs, rhs); } + +struct EntityRenderCommandData +{ + QVector entities; + QVector commands; + QVector passesData; + + void reserve(int size) + { + entities.reserve(size); + commands.reserve(size); + passesData.reserve(size); + } + + inline int size() const { return entities.size(); } + + inline void push_back(Entity *e, const RenderCommand &c, const RenderPassParameterData &p) + { + entities.push_back(e); + commands.push_back(c); + passesData.push_back(p); + } + + inline void push_back(Entity *e, RenderCommand &&c, RenderPassParameterData &&p) + { + entities.push_back(e); + commands.push_back(std::move(c)); + passesData.push_back(std::move(p)); + } + + EntityRenderCommandData &operator+=(EntityRenderCommandData &&t) + { + entities += std::move(t.entities); + commands += std::move(t.commands); + passesData += std::move(t.passesData); + return *this; + } + +}; + +using EntityRenderCommandDataPtr = QSharedPointer; + + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERCOMMAND_H diff --git a/src/plugins/renderers/opengl/renderer/renderer.cpp b/src/plugins/renderers/opengl/renderer/renderer.cpp new file mode 100644 index 000000000..2b9a34059 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderer.cpp @@ -0,0 +1,2459 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderer_p.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef Q_OS_INTEGRITY +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +QT_BEGIN_NAMESPACE + +// Crashes on AMD Radeon drivers on Windows. Disable for now. +//#define SHADER_LOADING_IN_COMMAND_THREAD + +using namespace Qt3DCore; + +namespace Qt3DRender { +namespace Render { + +namespace { + +class SyncLightsGatherer +{ +public: + explicit SyncLightsGatherer(LightGathererPtr gatherJob, + RendererCache *cache) + : m_gatherJob(gatherJob) + , m_cache(cache) + { + } + + void operator()() + { + QMutexLocker lock(m_cache->mutex()); + m_cache->gatheredLights = m_gatherJob->lights(); + m_cache->environmentLight = m_gatherJob->takeEnvironmentLight(); + } + +private: + LightGathererPtr m_gatherJob; + RendererCache *m_cache; +}; + +class SyncRenderableEntities +{ +public: + explicit SyncRenderableEntities(RenderableEntityFilterPtr gatherJob, + RendererCache *cache) + : m_gatherJob(gatherJob) + , m_cache(cache) + { + } + + void operator()() + { + QVector selectedEntities = m_gatherJob->filteredEntities(); + std::sort(selectedEntities.begin(), selectedEntities.end()); + + QMutexLocker lock(m_cache->mutex()); + m_cache->renderableEntities = selectedEntities; + } + +private: + RenderableEntityFilterPtr m_gatherJob; + RendererCache *m_cache; +}; + +class SyncComputableEntities +{ +public: + explicit SyncComputableEntities(ComputableEntityFilterPtr gatherJob, + RendererCache *cache) + : m_gatherJob(gatherJob) + , m_cache(cache) + { + } + + void operator()() + { + QVector selectedEntities = m_gatherJob->filteredEntities(); + std::sort(selectedEntities.begin(), selectedEntities.end()); + + QMutexLocker lock(m_cache->mutex()); + m_cache->computeEntities = selectedEntities; + } + +private: + ComputableEntityFilterPtr m_gatherJob; + RendererCache *m_cache; +}; + +} // anonymous + + +/*! + \internal + + Renderer shutdown procedure: + + Since the renderer relies on the surface and OpenGLContext to perform its cleanup, + it is shutdown when the surface is set to nullptr + + When the surface is set to nullptr this will request the RenderThread to terminate + and will prevent createRenderBinJobs from returning a set of jobs as there is nothing + more to be rendered. + + In turn, this will call shutdown which will make the OpenGL context current one last time + to allow cleanups requiring a call to QOpenGLContext::currentContext to execute properly. + At the end of that function, the GraphicsContext is set to null. + + At this point though, the QAspectThread is still running its event loop and will only stop + a short while after. + */ + +Renderer::Renderer(QRenderAspect::RenderType type) + : m_services(nullptr) + , m_nodesManager(nullptr) + , m_renderSceneRoot(nullptr) + , m_defaultRenderStateSet(nullptr) + , m_submissionContext(nullptr) + , m_renderQueue(new RenderQueue()) + , m_renderThread(type == QRenderAspect::Threaded ? new RenderThread(this) : nullptr) + , m_vsyncFrameAdvanceService(new VSyncFrameAdvanceService(m_renderThread != nullptr)) + , m_waitForInitializationToBeCompleted(0) + , m_hasBeenInitializedMutex() + , m_pickEventFilter(new PickEventFilter()) + , m_exposed(0) + , m_lastFrameCorrect(0) + , m_glContext(nullptr) + , m_shareContext(nullptr) + , m_pickBoundingVolumeJob(PickBoundingVolumeJobPtr::create()) + , m_rayCastingJob(RayCastingJobPtr::create()) + , m_time(0) + , m_settings(nullptr) + , m_updateShaderDataTransformJob(Render::UpdateShaderDataTransformJobPtr::create()) + , m_cleanupJob(Render::FrameCleanupJobPtr::create()) + , m_worldTransformJob(Render::UpdateWorldTransformJobPtr::create()) + , m_expandBoundingVolumeJob(Render::ExpandBoundingVolumeJobPtr::create()) + , m_calculateBoundingVolumeJob(Render::CalculateBoundingVolumeJobPtr::create()) + , m_updateWorldBoundingVolumeJob(Render::UpdateWorldBoundingVolumeJobPtr::create()) + , m_updateTreeEnabledJob(Render::UpdateTreeEnabledJobPtr::create()) + , m_sendBufferCaptureJob(Render::SendBufferCaptureJobPtr::create()) + , m_updateSkinningPaletteJob(Render::UpdateSkinningPaletteJobPtr::create()) + , m_updateLevelOfDetailJob(Render::UpdateLevelOfDetailJobPtr::create()) + , m_updateMeshTriangleListJob(Render::UpdateMeshTriangleListJobPtr::create()) + , m_filterCompatibleTechniqueJob(Render::FilterCompatibleTechniqueJobPtr::create()) + , m_updateEntityLayersJob(Render::UpdateEntityLayersJobPtr::create()) + , m_lightGathererJob(Render::LightGathererPtr::create()) + , m_renderableEntityFilterJob(Render::RenderableEntityFilterPtr::create()) + , m_computableEntityFilterJob(Render::ComputableEntityFilterPtr::create()) + , m_bufferGathererJob(SynchronizerJobPtr::create([this] { lookForDirtyBuffers(); }, JobTypes::DirtyBufferGathering)) + , m_vaoGathererJob(SynchronizerJobPtr::create([this] { lookForAbandonedVaos(); }, JobTypes::DirtyVaoGathering)) + , m_textureGathererJob(SynchronizerJobPtr::create([this] { lookForDirtyTextures(); }, JobTypes::DirtyTextureGathering)) + , m_sendSetFenceHandlesToFrontendJob(SynchronizerJobPtr::create([this] { sendSetFenceHandlesToFrontend(); }, JobTypes::SendSetFenceHandlesToFrontend)) + , m_introspectShaderJob(SynchronizerPostFramePtr::create([this] { reloadDirtyShaders(); }, + [this] (Qt3DCore::QAspectManager *m) { sendShaderChangesToFrontend(m); }, + JobTypes::DirtyShaderGathering)) + , m_syncLoadingJobs(SynchronizerJobPtr::create([] {}, JobTypes::SyncLoadingJobs)) + , m_cacheRenderableEntitiesJob(SynchronizerJobPtr::create(SyncRenderableEntities(m_renderableEntityFilterJob, &m_cache), + JobTypes::EntityComponentTypeFiltering)) + , m_cacheComputableEntitiesJob(SynchronizerJobPtr::create(SyncComputableEntities(m_computableEntityFilterJob, &m_cache), + JobTypes::EntityComponentTypeFiltering)) + , m_cacheLightsJob(SynchronizerJobPtr::create(SyncLightsGatherer(m_lightGathererJob, &m_cache), + JobTypes::EntityComponentTypeFiltering)) + , m_ownedContext(false) + , m_offscreenHelper(nullptr) + , m_glResourceManagers(nullptr) + , m_commandExecuter(new Qt3DRender::Debug::CommandExecuter(this)) + , m_shouldSwapBuffers(true) + , m_imGuiRenderer(nullptr) + , m_jobsInLastFrame(0) +{ + // Set renderer as running - it will wait in the context of the + // RenderThread for RenderViews to be submitted + m_running.fetchAndStoreOrdered(1); + if (m_renderThread) + m_renderThread->waitForStart(); + + // Create jobs to update transforms and bounding volumes + // We can only update bounding volumes once all world transforms are known + m_updateWorldBoundingVolumeJob->addDependency(m_worldTransformJob); + m_updateWorldBoundingVolumeJob->addDependency(m_calculateBoundingVolumeJob); + m_expandBoundingVolumeJob->addDependency(m_updateWorldBoundingVolumeJob); + m_updateShaderDataTransformJob->addDependency(m_worldTransformJob); + m_pickBoundingVolumeJob->addDependency(m_expandBoundingVolumeJob); + m_rayCastingJob->addDependency(m_expandBoundingVolumeJob); + // m_calculateBoundingVolumeJob's dependency on m_updateTreeEnabledJob is set in renderBinJobs + + // Ensures all skeletons are loaded before we try to update them + m_updateSkinningPaletteJob->addDependency(m_syncLoadingJobs); + + // All world stuff depends on the RenderEntity's localBoundingVolume + m_updateLevelOfDetailJob->addDependency(m_updateMeshTriangleListJob); + m_pickBoundingVolumeJob->addDependency(m_updateMeshTriangleListJob); + m_rayCastingJob->addDependency(m_updateMeshTriangleListJob); + + m_introspectShaderJob->addDependency(m_filterCompatibleTechniqueJob); + + m_cacheLightsJob->addDependency(m_lightGathererJob); + m_cacheRenderableEntitiesJob->addDependency(m_renderableEntityFilterJob); + m_cacheComputableEntitiesJob->addDependency(m_computableEntityFilterJob); + + m_filterCompatibleTechniqueJob->setRenderer(this); + + m_defaultRenderStateSet = new RenderStateSet; + m_defaultRenderStateSet->addState(StateVariant::createState(GL_LESS)); + m_defaultRenderStateSet->addState(StateVariant::createState(GL_BACK)); + m_defaultRenderStateSet->addState(StateVariant::createState(true, true, true, true)); +} + +Renderer::~Renderer() +{ + Q_ASSERT(m_running.fetchAndStoreOrdered(0) == 0); + if (m_renderThread) + Q_ASSERT(m_renderThread->isFinished()); + + delete m_renderQueue; + delete m_defaultRenderStateSet; + delete m_glResourceManagers; + + if (!m_ownedContext) + QObject::disconnect(m_contextConnection); + +#ifndef Q_OS_INTEGRITY + delete m_imGuiRenderer; +#endif +} + +void Renderer::dumpInfo() const +{ + qDebug() << Q_FUNC_INFO << "t =" << m_time; + + const ShaderManager *shaderManager = m_nodesManager->shaderManager(); + qDebug() << "=== Shader Manager ==="; + qDebug() << *shaderManager; + + const TextureManager *textureManager = m_nodesManager->textureManager(); + qDebug() << "=== Texture Manager ==="; + qDebug() << *textureManager; + + const TextureImageManager *textureImageManager = m_nodesManager->textureImageManager(); + qDebug() << "=== Texture Image Manager ==="; + qDebug() << *textureImageManager; +} + +qint64 Renderer::time() const +{ + return m_time; +} + +void Renderer::setTime(qint64 time) +{ + m_time = time; +} + +void Renderer::setJobsInLastFrame(int jobsInLastFrame) +{ + m_jobsInLastFrame = jobsInLastFrame; +} + +void Renderer::setNodeManagers(NodeManagers *managers) +{ + m_nodesManager = managers; + m_glResourceManagers = new GLResourceManagers(); + m_scene2DResourceAccessor.reset(new ResourceAccessor(this, m_nodesManager)); + + m_updateShaderDataTransformJob->setManagers(m_nodesManager); + m_cleanupJob->setManagers(m_nodesManager); + m_calculateBoundingVolumeJob->setManagers(m_nodesManager); + m_expandBoundingVolumeJob->setManagers(m_nodesManager); + m_worldTransformJob->setManagers(m_nodesManager); + m_pickBoundingVolumeJob->setManagers(m_nodesManager); + m_rayCastingJob->setManagers(m_nodesManager); + m_updateWorldBoundingVolumeJob->setManager(m_nodesManager->renderNodesManager()); + m_updateLevelOfDetailJob->setManagers(m_nodesManager); + m_updateSkinningPaletteJob->setManagers(m_nodesManager); + m_updateMeshTriangleListJob->setManagers(m_nodesManager); + m_filterCompatibleTechniqueJob->setManager(m_nodesManager->techniqueManager()); + m_updateEntityLayersJob->setManager(m_nodesManager); + m_updateTreeEnabledJob->setManagers(m_nodesManager); + m_sendBufferCaptureJob->setManagers(m_nodesManager); + m_lightGathererJob->setManager(m_nodesManager->renderNodesManager()); + m_renderableEntityFilterJob->setManager(m_nodesManager->renderNodesManager()); + m_computableEntityFilterJob->setManager(m_nodesManager->renderNodesManager()); +} + +void Renderer::setServices(QServiceLocator *services) +{ + m_services = services; + + m_nodesManager->sceneManager()->setDownloadService(m_services->downloadHelperService()); +} + +NodeManagers *Renderer::nodeManagers() const +{ + return m_nodesManager; +} + +/*! + \internal + + Return context which can be used to share resources safely + with qt3d main render context. +*/ +QOpenGLContext *Renderer::shareContext() const +{ + QMutexLocker lock(&m_shareContextMutex); + return m_shareContext ? m_shareContext + : (m_submissionContext->openGLContext() + ? m_submissionContext->openGLContext()->shareContext() + : nullptr); +} + +// Executed in the reloadDirtyShader job +void Renderer::loadShader(Shader *shader, HShader shaderHandle) +{ + Q_UNUSED(shader); + if (!m_dirtyShaders.contains(shaderHandle)) + m_dirtyShaders.push_back(shaderHandle); +} + +void Renderer::setOpenGLContext(QOpenGLContext *context) +{ + m_glContext = context; +} + +void Renderer::setScreen(QScreen *scr) +{ + m_screen = scr; +} + +QScreen *Renderer::screen() const +{ + return m_screen; +} + +bool Renderer::accessOpenGLTexture(Qt3DCore::QNodeId nodeId, + QOpenGLTexture **texture, + QMutex **lock, + bool readonly) +{ + Texture *tex = m_nodesManager->textureManager()->lookupResource(nodeId); + if (!tex) + return false; + + GLTexture *glTex = m_glResourceManagers->glTextureManager()->lookupResource(tex->peerId()); + if (!glTex) + return false; + + if (glTex->isDirty()) + return false; + + if (!readonly) + glTex->setExternalRenderingEnabled(true); + + GLTexture::TextureUpdateInfo texInfo = glTex->createOrUpdateGLTexture(); + *texture = texInfo.texture; + + if (!readonly) + *lock = glTex->externalRenderingLock(); + + return true; +} + +QSharedPointer Renderer::resourceAccessor() const +{ + return m_scene2DResourceAccessor; +} + +// Called in RenderThread context by the run method of RenderThread +// RenderThread has locked the mutex already and unlocks it when this +// method termintates +void Renderer::initialize() +{ + QMutexLocker lock(&m_hasBeenInitializedMutex); + m_submissionContext.reset(new SubmissionContext); + m_submissionContext->setRenderer(this); + + QOpenGLContext* ctx = m_glContext; + + { + QMutexLocker lock(&m_shareContextMutex); + // If we are using our own context (not provided by QtQuick), + // we need to create it + if (!m_glContext) { + ctx = new QOpenGLContext; + if (m_screen) + ctx->setScreen(m_screen); + ctx->setShareContext(qt_gl_global_share_context()); + + // TO DO: Shouldn't we use the highest context available and trust + // QOpenGLContext to fall back on the best lowest supported ? + const QByteArray debugLoggingMode = qgetenv("QT3DRENDER_DEBUG_LOGGING"); + + if (!debugLoggingMode.isEmpty()) { + QSurfaceFormat sf = ctx->format(); + sf.setOption(QSurfaceFormat::DebugContext); + ctx->setFormat(sf); + } + + // Create OpenGL context + if (ctx->create()) + qCDebug(Backend) << "OpenGL context created with actual format" << ctx->format(); + else + qCWarning(Backend) << Q_FUNC_INFO << "OpenGL context creation failed"; + m_ownedContext = true; + + QObject::connect(m_glContext, &QOpenGLContext::aboutToBeDestroyed, + [this] { m_frameProfiler.reset(); }); + } else { + // Context is not owned by us, so we need to know if it gets destroyed + m_contextConnection = QObject::connect(m_glContext, &QOpenGLContext::aboutToBeDestroyed, + [this] { releaseGraphicsResources(); }); + } + + qCDebug(Backend) << "Qt3D shared context:" << ctx->shareContext(); + qCDebug(Backend) << "Qt global shared context:" << qt_gl_global_share_context(); + + if (!ctx->shareContext()) { + m_shareContext = new QOpenGLContext; + if (ctx->screen()) + m_shareContext->setScreen(ctx->screen()); + m_shareContext->setFormat(ctx->format()); + m_shareContext->setShareContext(ctx); + m_shareContext->create(); + } + + // Note: we don't have a surface at this point + // The context will be made current later on (at render time) + m_submissionContext->setOpenGLContext(ctx); + + // Store the format used by the context and queue up creating an + // offscreen surface in the main thread so that it is available + // for use when we want to shutdown the renderer. We need to create + // the offscreen surface on the main thread because on some platforms + // (MS Windows), an offscreen surface is just a hidden QWindow. + m_format = ctx->format(); + QMetaObject::invokeMethod(m_offscreenHelper, "createOffscreenSurface"); + } + + // Awake setScenegraphRoot in case it was waiting + m_waitForInitializationToBeCompleted.release(1); + // Allow the aspect manager to proceed + m_vsyncFrameAdvanceService->proceedToNextFrame(); + + // Force initial refresh + markDirty(AllDirty, nullptr); +} + +/*! + * \internal + * + * Signals for the renderer to stop rendering. If a threaded renderer is in use, + * the render thread will call releaseGraphicsResources() just before the thread exits. + * If rendering synchronously, this function will call releaseGraphicsResources(). + */ +void Renderer::shutdown() +{ + // Ensure we have waited to be fully initialized before trying to shut down + // (in case initialization is taking place at the same time) + QMutexLocker lock(&m_hasBeenInitializedMutex); + + qCDebug(Backend) << Q_FUNC_INFO << "Requesting renderer shutdown"; + m_running.storeRelaxed(0); + + // We delete any renderqueue that we may not have had time to render + // before the surface was destroyed + QMutexLocker lockRenderQueue(m_renderQueue->mutex()); + qDeleteAll(m_renderQueue->nextFrameQueue()); + m_renderQueue->reset(); + lockRenderQueue.unlock(); + + if (!m_renderThread) { + releaseGraphicsResources(); + } else { + // Wake up the render thread in case it is waiting for some renderviews + // to be ready. The isReadyToSubmit() function checks for a shutdown + // having been requested. + m_submitRenderViewsSemaphore.release(1); + m_renderThread->wait(); + } + + // Destroy internal managers + // This needs to be done before the nodeManager is destroy + // as the internal resources might somehow rely on nodeManager resources + delete m_glResourceManagers; + m_glResourceManagers = nullptr; +} + +/*! + \internal + + When using a threaded renderer this function is called in the context of the + RenderThread to do any shutdown and cleanup that needs to be performed in the + thread where the OpenGL context lives. + + When using Scene3D or anything that provides a custom QOpenGLContext (not + owned by Qt3D) this function is called whenever the signal + QOpenGLContext::aboutToBeDestroyed is emitted. In that case this function + is called in the context of the emitter's thread. +*/ +void Renderer::releaseGraphicsResources() +{ + // We may get called twice when running inside of a Scene3D. Once when Qt Quick + // wants to shutdown, and again when the render aspect gets unregistered. So + // check that we haven't already cleaned up before going any further. + if (!m_submissionContext) + return; + + // Try to temporarily make the context current so we can free up any resources + QMutexLocker locker(&m_offscreenSurfaceMutex); + QOffscreenSurface *offscreenSurface = m_offscreenHelper->offscreenSurface(); + if (!offscreenSurface) { + qWarning() << "Failed to make context current: OpenGL resources will not be destroyed"; + // We still need to delete the submission context + m_submissionContext.reset(nullptr); + return; + } + + QOpenGLContext *context = m_submissionContext->openGLContext(); + Q_ASSERT(context); + + if (context->thread() == QThread::currentThread() && context->makeCurrent(offscreenSurface)) { + + // Clean up the graphics context and any resources + const QVector activeTexturesHandles = m_glResourceManagers->glTextureManager()->activeHandles(); + for (const HGLTexture &textureHandle : activeTexturesHandles) { + GLTexture *tex = m_glResourceManagers->glTextureManager()->data(textureHandle); + tex->destroy(); + } + + // Do the same thing with buffers + const QVector activeBuffers = m_glResourceManagers->glBufferManager()->activeHandles(); + for (const HGLBuffer &bufferHandle : activeBuffers) { + GLBuffer *buffer = m_glResourceManagers->glBufferManager()->data(bufferHandle); + buffer->destroy(m_submissionContext.data()); + } + + // Do the same thing with shaders + const QVector shaders = m_glResourceManagers->glShaderManager()->takeActiveResources(); + qDeleteAll(shaders); + + // Do the same thing with VAOs + const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); + for (const HVao &vaoHandle : activeVaos) { + OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(vaoHandle); + vao->destroy(); + } + + m_frameProfiler.reset(); + context->doneCurrent(); + } else { + qWarning() << "Failed to make context current: OpenGL resources will not be destroyed"; + } + + if (m_ownedContext) + delete context; + if (m_shareContext) + delete m_shareContext; + + m_submissionContext.reset(nullptr); + qCDebug(Backend) << Q_FUNC_INFO << "Renderer properly shutdown"; +} + +void Renderer::setSurfaceExposed(bool exposed) +{ + qCDebug(Backend) << "Window exposed: " << exposed; + m_exposed.fetchAndStoreOrdered(exposed); +} + +Render::FrameGraphNode *Renderer::frameGraphRoot() const +{ + Q_ASSERT(m_settings); + if (m_nodesManager && m_nodesManager->frameGraphManager() && m_settings) + return m_nodesManager->frameGraphManager()->lookupNode(m_settings->activeFrameGraphID()); + return nullptr; +} + +// QAspectThread context +// Order of execution : +// 1) RenderThread is created -> release 1 of m_waitForInitializationToBeCompleted when started +// 2) setSceneRoot waits to acquire initialization +// 3) submitRenderView -> check for surface +// -> make surface current + create proper glHelper if needed +void Renderer::setSceneRoot(Entity *sgRoot) +{ + Q_ASSERT(sgRoot); + + // If initialization hasn't been completed we must wait + m_waitForInitializationToBeCompleted.acquire(); + + m_renderSceneRoot = sgRoot; + if (!m_renderSceneRoot) + qCWarning(Backend) << "Failed to build render scene"; + m_renderSceneRoot->dump(); + qCDebug(Backend) << Q_FUNC_INFO << "DUMPING SCENE"; + + // Set the scene root on the jobs + m_worldTransformJob->setRoot(m_renderSceneRoot); + m_expandBoundingVolumeJob->setRoot(m_renderSceneRoot); + m_calculateBoundingVolumeJob->setRoot(m_renderSceneRoot); + m_cleanupJob->setRoot(m_renderSceneRoot); + m_pickBoundingVolumeJob->setRoot(m_renderSceneRoot); + m_rayCastingJob->setRoot(m_renderSceneRoot); + m_updateLevelOfDetailJob->setRoot(m_renderSceneRoot); + m_updateSkinningPaletteJob->setRoot(m_renderSceneRoot); + m_updateTreeEnabledJob->setRoot(m_renderSceneRoot); + + // Set all flags to dirty + m_dirtyBits.marked |= AbstractRenderer::AllDirty; +} + +void Renderer::registerEventFilter(QEventFilterService *service) +{ + qCDebug(Backend) << Q_FUNC_INFO << QThread::currentThread(); + service->registerEventFilter(m_pickEventFilter.data(), 1024); +} + +void Renderer::setSettings(RenderSettings *settings) +{ + m_settings = settings; +} + +RenderSettings *Renderer::settings() const +{ + return m_settings; +} + +void Renderer::render() +{ + // Traversing the framegraph tree from root to lead node + // Allows us to define the rendering set up + // Camera, RenderTarget ... + + // Utimately the renderer should be a framework + // For the processing of the list of renderviews + + // Matrice update, bounding volumes computation ... + // Should be jobs + + // namespace Qt3DCore has 2 distincts node trees + // One scene description + // One framegraph description + + while (m_running.loadRelaxed() > 0) { + doRender(); + // TO DO: Restore windows exposed detection + // Probably needs to happens some place else though + } +} + +// Either called by render if Qt3D is in charge of the RenderThread +// or by QRenderAspectPrivate::renderSynchronous (for Scene3D) +void Renderer::doRender(bool swapBuffers) +{ + Renderer::ViewSubmissionResultData submissionData; + bool hasCleanedQueueAndProceeded = false; + bool preprocessingComplete = false; + bool beganDrawing = false; + + // Blocking until RenderQueue is full + const bool canSubmit = isReadyToSubmit(); + m_shouldSwapBuffers = swapBuffers; + + // Lock the mutex to protect access to the renderQueue while we look for its state + QMutexLocker locker(m_renderQueue->mutex()); + const bool queueIsComplete = m_renderQueue->isFrameQueueComplete(); + const bool queueIsEmpty = m_renderQueue->targetRenderViewCount() == 0; + + // When using synchronous rendering (QtQuick) + // We are not sure that the frame queue is actually complete + // Since a call to render may not be synched with the completions + // of the RenderViewJobs + // In such a case we return early, waiting for a next call with + // the frame queue complete at this point + + // RenderQueue is complete (but that means it may be of size 0) + if (canSubmit && (queueIsComplete && !queueIsEmpty)) { + const QVector renderViews = m_renderQueue->nextFrameQueue(); + QTaskLogger submissionStatsPart1(m_services->systemInformation(), + {JobTypes::FrameSubmissionPart1, 0}, + QTaskLogger::Submission); + QTaskLogger submissionStatsPart2(m_services->systemInformation(), + {JobTypes::FrameSubmissionPart2, 0}, + QTaskLogger::Submission); + + if (canRender()) { + { // Scoped to destroy surfaceLock + QSurface *surface = nullptr; + for (const Render::RenderView *rv: renderViews) { + surface = rv->surface(); + if (surface) + break; + } + + SurfaceLocker surfaceLock(surface); + const bool surfaceIsValid = (surface && surfaceLock.isSurfaceValid()); + if (surfaceIsValid) { + // Reset state for each draw if we don't have complete control of the context + if (!m_ownedContext) + m_submissionContext->setCurrentStateSet(nullptr); + beganDrawing = m_submissionContext->beginDrawing(surface); + if (beganDrawing) { + // 1) Execute commands for buffer uploads, texture updates, shader loading first + updateGLResources(); + // 2) Update VAO and copy data into commands to allow concurrent submission + prepareCommandsSubmission(renderViews); + preprocessingComplete = true; + + // Purge shader which aren't used any longer + static int callCount = 0; + ++callCount; + const int shaderPurgePeriod = 600; + if (callCount % shaderPurgePeriod == 0) + m_glResourceManagers->glShaderManager()->purge(); + } + } + } + // 2) Proceed to next frame and start preparing frame n + 1 + m_renderQueue->reset(); + locker.unlock(); // Done protecting RenderQueue + m_vsyncFrameAdvanceService->proceedToNextFrame(); + hasCleanedQueueAndProceeded = true; + + // Only try to submit the RenderViews if the preprocessing was successful + // This part of the submission is happening in parallel to the RV building for the next frame + if (preprocessingComplete) { + submissionStatsPart1.end(submissionStatsPart2.restart()); + + // 3) Submit the render commands for frame n (making sure we never reference something that could be changing) + // Render using current device state and renderer configuration + submissionData = submitRenderViews(renderViews); + + // Perform any required cleanup of the Graphics resources (Buffers deleted, Shader deleted...) + cleanGraphicsResources(); + } + } + + // Execute the pending shell commands + m_commandExecuter->performAsynchronousCommandExecution(renderViews); + + // Delete all the RenderViews which will clear the allocators + // that were used for their allocation + qDeleteAll(renderViews); + + if (preprocessingComplete && activeProfiler()) + m_frameProfiler->writeResults(); + } + + // If hasCleanedQueueAndProceeded isn't true this implies that something went wrong + // with the rendering and/or the renderqueue is incomplete from some reason + // or alternatively it could be complete but empty (RenderQueue of size 0) + + if (!hasCleanedQueueAndProceeded) { + // RenderQueue was full but something bad happened when + // trying to render it and therefore proceedToNextFrame was not called + // Note: in this case the renderQueue mutex is still locked + + // Reset the m_renderQueue so that we won't try to render + // with a queue used by a previous frame with corrupted content + // if the current queue was correctly submitted + m_renderQueue->reset(); + + // We allow the RenderTickClock service to proceed to the next frame + // In turn this will allow the aspect manager to request a new set of jobs + // to be performed for each aspect + m_vsyncFrameAdvanceService->proceedToNextFrame(); + } + + // Perform the last swapBuffers calls after the proceedToNextFrame + // as this allows us to gain a bit of time for the preparation of the + // next frame + // Finish up with last surface used in the list of RenderViews + if (beganDrawing) { + SurfaceLocker surfaceLock(submissionData.surface); + // Finish up with last surface used in the list of RenderViews + const bool swapBuffers = submissionData.lastBoundFBOId == m_submissionContext->defaultFBO() + && surfaceLock.isSurfaceValid() + && m_shouldSwapBuffers; + m_submissionContext->endDrawing(swapBuffers); + } +} + +// Called by RenderViewJobs +// When the frameQueue is complete and we are using a renderThread +// we allow the render thread to proceed +void Renderer::enqueueRenderView(Render::RenderView *renderView, int submitOrder) +{ + QMutexLocker locker(m_renderQueue->mutex()); // Prevent out of order execution + // We cannot use a lock free primitive here because: + // - QVector is not thread safe + // - Even if the insert is made correctly, the isFrameComplete call + // could be invalid since depending on the order of execution + // the counter could be complete but the renderview not yet added to the + // buffer depending on whichever order the cpu decides to process this + const bool isQueueComplete = m_renderQueue->queueRenderView(renderView, submitOrder); + locker.unlock(); // We're done protecting the queue at this point + if (isQueueComplete) { + if (m_renderThread && m_running.loadRelaxed()) + Q_ASSERT(m_submitRenderViewsSemaphore.available() == 0); + m_submitRenderViewsSemaphore.release(1); + } +} + +bool Renderer::canRender() const + +{ + // Make sure that we've not been told to terminate + if (m_renderThread && !m_running.loadRelaxed()) { + qCDebug(Rendering) << "RenderThread termination requested whilst waiting"; + return false; + } + + // TO DO: Check if all surfaces have been destroyed... + // It may be better if the last window to be closed trigger a call to shutdown + // Rather than having checks for the surface everywhere + + return true; +} + +Profiling::FrameProfiler *Renderer::activeProfiler() const +{ + if (m_services && m_services->systemInformation()->isGraphicsTraceEnabled()) { + if (m_frameProfiler.isNull()) + m_frameProfiler.reset(new Profiling::FrameProfiler(m_services->systemInformation())); + + return m_frameProfiler.data(); + } + + return nullptr; +} + +bool Renderer::isReadyToSubmit() +{ + // Make sure that we've been told to render before rendering + // Prevent ouf of order execution + m_submitRenderViewsSemaphore.acquire(1); + + // Check if shutdown has been requested + if (m_running.loadRelaxed() == 0) + return false; + + // The semaphore should only + // be released when the frame queue is complete and there's + // something to render + // The case of shutdown should have been handled just before + Q_ASSERT(m_renderQueue->isFrameQueueComplete()); + return true; +} + +// Main thread +QVariant Renderer::executeCommand(const QStringList &args) +{ + return m_commandExecuter->executeCommand(args); +} + +/*! + \internal + Called in the context of the aspect thread from QRenderAspect::onRegistered +*/ +void Renderer::setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) +{ + QMutexLocker locker(&m_offscreenSurfaceMutex); + m_offscreenHelper = helper; +} + +QSurfaceFormat Renderer::format() +{ + return m_format; +} + +// When this function is called, we must not be processing the commands for frame n+1 +void Renderer::prepareCommandsSubmission(const QVector &renderViews) +{ + OpenGLVertexArrayObject *vao = nullptr; + QHash updatedTable; + + for (RenderView *rv: renderViews) { + QVector &commands = rv->commands(); + for (RenderCommand &command : commands) { + // Update/Create VAO + if (command.m_type == RenderCommand::Draw) { + Geometry *rGeometry = m_nodesManager->data(command.m_geometry); + GeometryRenderer *rGeometryRenderer = m_nodesManager->data(command.m_geometryRenderer); + GLShader *shader = command.m_glShader; + + // We should never have inserted a command for which these are null + // in the first place + Q_ASSERT(rGeometry && rGeometryRenderer && shader); + + // The VAO should be created only once for a QGeometry and a ShaderProgram + // Manager should have a VAO Manager that are indexed by QMeshData and Shader + // RenderCommand should have a handle to the corresponding VAO for the Mesh and Shader + HVao vaoHandle; + + // Create VAO or return already created instance associated with command shader/geometry + // (VAO is emulated if not supported) + createOrUpdateVAO(&command, &vaoHandle, &vao); + command.m_vao = vaoHandle; + + // Avoids redoing the same thing for the same VAO + if (!updatedTable.contains(vaoHandle)) { + updatedTable.insert(vaoHandle, true); + + // Do we have any attributes that are dirty ? + const bool requiresPartialVAOUpdate = requiresVAOAttributeUpdate(rGeometry, &command); + + // If true, we need to reupload all attributes to set the VAO + // Otherwise only dirty attributes will be updates + const bool requiresFullVAOUpdate = (!vao->isSpecified()) || (rGeometry->isDirty() || rGeometryRenderer->isDirty()); + + // Append dirty Geometry to temporary vector + // so that its dirtiness can be unset later + if (rGeometry->isDirty()) + m_dirtyGeometry.push_back(rGeometry); + + if (!command.m_activeAttributes.isEmpty() && (requiresFullVAOUpdate || requiresPartialVAOUpdate)) { + Profiling::GLTimeRecorder recorder(Profiling::VAOUpload, activeProfiler()); + // Activate shader + m_submissionContext->activateShader(shader); + // Bind VAO + vao->bind(); + // Update or set Attributes and Buffers for the given rGeometry and Command + // Note: this fills m_dirtyAttributes as well + if (updateVAOWithAttributes(rGeometry, &command, shader, requiresFullVAOUpdate)) + vao->setSpecified(true); + } + } + + // Unset dirtiness on rGeometryRenderer only + // The rGeometry may be shared by several rGeometryRenderer + // so we cannot unset its dirtiness at this point + if (rGeometryRenderer->isDirty()) + rGeometryRenderer->unsetDirty(); + + // Prepare the ShaderParameterPack based on the active uniforms of the shader + shader->prepareUniforms(command.m_parameterPack); + + } else if (command.m_type == RenderCommand::Compute) { + GLShader *shader = command.m_glShader; + Q_ASSERT(shader); + + // Prepare the ShaderParameterPack based on the active uniforms of the shader + shader->prepareUniforms(command.m_parameterPack); + } + } + } + + // Make sure we leave nothing bound + if (vao) + vao->release(); + + // Unset dirtiness on Geometry and Attributes + // Note: we cannot do it in the loop above as we want to be sure that all + // the VAO which reference the geometry/attributes are properly updated + for (Attribute *attribute : qAsConst(m_dirtyAttributes)) + attribute->unsetDirty(); + m_dirtyAttributes.clear(); + + for (Geometry *geometry : qAsConst(m_dirtyGeometry)) + geometry->unsetDirty(); + m_dirtyGeometry.clear(); +} + +// Executed in a job +void Renderer::lookForAbandonedVaos() +{ + const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); + for (HVao handle : activeVaos) { + OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(handle); + + // Make sure to only mark VAOs for deletion that were already created + // (ignore those that might be currently under construction in the render thread) + if (vao && vao->isAbandoned(m_nodesManager->geometryManager(), m_glResourceManagers->glShaderManager())) { + m_abandonedVaosMutex.lock(); + m_abandonedVaos.push_back(handle); + m_abandonedVaosMutex.unlock(); + } + } +} + +// Executed in a job +void Renderer::lookForDirtyBuffers() +{ + const QVector activeBufferHandles = m_nodesManager->bufferManager()->activeHandles(); + for (const HBuffer &handle: activeBufferHandles) { + Buffer *buffer = m_nodesManager->bufferManager()->data(handle); + if (buffer->isDirty()) + m_dirtyBuffers.push_back(handle); + } +} + +// Called in prepareSubmission +void Renderer::lookForDownloadableBuffers() +{ + m_downloadableBuffers.clear(); + const QVector activeBufferHandles = m_nodesManager->bufferManager()->activeHandles(); + for (const HBuffer &handle : activeBufferHandles) { + Buffer *buffer = m_nodesManager->bufferManager()->data(handle); + if (buffer->access() & QBuffer::Read) + m_downloadableBuffers.push_back(buffer->peerId()); + } +} + +// Executed in a job +void Renderer::lookForDirtyTextures() +{ + // To avoid having Texture or TextureImage maintain relationships between + // one another, we instead perform a lookup here to check if a texture + // image has been updated to then notify textures referencing the image + // that they need to be updated + TextureImageManager *imageManager = m_nodesManager->textureImageManager(); + const QVector activeTextureImageHandles = imageManager->activeHandles(); + Qt3DCore::QNodeIdVector dirtyImageIds; + for (const HTextureImage &handle: activeTextureImageHandles) { + TextureImage *image = imageManager->data(handle); + if (image->isDirty()) { + dirtyImageIds.push_back(image->peerId()); + image->unsetDirty(); + } + } + + TextureManager *textureManager = m_nodesManager->textureManager(); + const QVector activeTextureHandles = textureManager->activeHandles(); + for (const HTexture &handle: activeTextureHandles) { + Texture *texture = textureManager->data(handle); + const QNodeIdVector imageIds = texture->textureImageIds(); + + // Does the texture reference any of the dirty texture images? + for (const QNodeId imageId: imageIds) { + if (dirtyImageIds.contains(imageId)) { + texture->addDirtyFlag(Texture::DirtyImageGenerators); + break; + } + } + + // Dirty meaning that something has changed on the texture + // either properties, parameters, shared texture id, generator or a texture image + if (texture->dirtyFlags() != Texture::NotDirty) + m_dirtyTextures.push_back(handle); + // Note: texture dirty flags are reset when actually updating the + // textures in updateGLResources() as resetting flags here would make + // us lose information about what was dirty exactly. + } +} + +// Executed in a job +void Renderer::reloadDirtyShaders() +{ + Q_ASSERT(isRunning()); + const QVector activeTechniques = m_nodesManager->techniqueManager()->activeHandles(); + const QVector activeBuilders = m_nodesManager->shaderBuilderManager()->activeHandles(); + for (const HTechnique &techniqueHandle : activeTechniques) { + Technique *technique = m_nodesManager->techniqueManager()->data(techniqueHandle); + // If api of the renderer matches the one from the technique + if (technique->isCompatibleWithRenderer()) { + const auto passIds = technique->renderPasses(); + for (const QNodeId &passId : passIds) { + RenderPass *renderPass = m_nodesManager->renderPassManager()->lookupResource(passId); + HShader shaderHandle = m_nodesManager->shaderManager()->lookupHandle(renderPass->shaderProgram()); + Shader *shader = m_nodesManager->shaderManager()->data(shaderHandle); + + ShaderBuilder *shaderBuilder = nullptr; + for (const HShaderBuilder &builderHandle : activeBuilders) { + ShaderBuilder *builder = m_nodesManager->shaderBuilderManager()->data(builderHandle); + if (builder->shaderProgramId() == shader->peerId()) { + shaderBuilder = builder; + break; + } + } + + if (shaderBuilder) { + shaderBuilder->setGraphicsApi(*technique->graphicsApiFilter()); + + for (int i = 0; i <= QShaderProgram::Compute; i++) { + const auto shaderType = static_cast(i); + if (!shaderBuilder->shaderGraph(shaderType).isValid()) + continue; + + if (shaderBuilder->isShaderCodeDirty(shaderType)) { + shaderBuilder->generateCode(shaderType); + m_shaderBuilderUpdates.append(shaderBuilder->takePendingUpdates()); + } + + const auto code = shaderBuilder->shaderCode(shaderType); + shader->setShaderCode(shaderType, code); + } + } + + if (shader != nullptr && shader->isDirty()) + loadShader(shader, shaderHandle); + } + } + } +} + +// Executed in job (in main thread when jobs are done) +void Renderer::sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager) +{ + Q_ASSERT(isRunning()); + + // Sync Shader + const QVector activeShaders = m_nodesManager->shaderManager()->activeHandles(); + for (const HShader &handle :activeShaders) { + Shader *s = m_nodesManager->shaderManager()->data(handle); + if (s->requiresFrontendSync()) { + QShaderProgram *frontend = static_cast(manager->lookupNode(s->peerId())); + QShaderProgramPrivate *dFrontend = static_cast(QNodePrivate::get(frontend)); + s->unsetRequiresFrontendSync(); + dFrontend->setStatus(s->status()); + dFrontend->setLog(s->log()); + } + } + + // Sync ShaderBuilder + const QVector shaderBuilderUpdates = std::move(m_shaderBuilderUpdates); + for (const ShaderBuilderUpdate &update : shaderBuilderUpdates) { + QShaderProgramBuilder *builder = static_cast(manager->lookupNode(update.builderId)); + QShaderProgramBuilderPrivate *dBuilder = static_cast(QNodePrivate::get(builder)); + dBuilder->setShaderCode(update.shaderCode, update.shaderType); + } +} + +// Executed in a job (in main thread when jobs are done) +void Renderer::sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager) +{ + const QVector> updateTextureProperties = std::move(m_updatedTextureProperties); + for (const auto &pair : updateTextureProperties) { + const Qt3DCore::QNodeIdVector targetIds = pair.second; + for (const Qt3DCore::QNodeId &targetId: targetIds) { + // Lookup texture + Texture *t = m_nodesManager->textureManager()->lookupResource(targetId); + // If backend texture is Dirty, some property has changed and the properties we are + // about to send are already outdate + if (t == nullptr || t->dirtyFlags() != Texture::NotDirty) + continue; + + QAbstractTexture *texture = static_cast(manager->lookupNode(targetId)); + if (!texture) + continue; + const TextureProperties &properties = pair.first.properties; + + const bool blocked = texture->blockNotifications(true); + texture->setWidth(properties.width); + texture->setHeight(properties.height); + texture->setDepth(properties.depth); + texture->setLayers(properties.layers); + texture->setFormat(properties.format); + texture->blockNotifications(blocked); + + QAbstractTexturePrivate *dTexture = static_cast(QNodePrivate::get(texture)); + + dTexture->setStatus(properties.status); + dTexture->setHandleType(pair.first.handleType); + dTexture->setHandle(pair.first.handle); + } + } +} + +// Executed in a job +void Renderer::sendSetFenceHandlesToFrontend() +{ + const QVector> updatedSetFence = std::move(m_updatedSetFences); + FrameGraphManager *fgManager = m_nodesManager->frameGraphManager(); + for (const auto &pair : updatedSetFence) { + FrameGraphNode *fgNode = fgManager->lookupNode(pair.first); + if (fgNode != nullptr) { // Node could have been deleted before we got a chance to notify it + Q_ASSERT(fgNode->nodeType() == FrameGraphNode::SetFence); + SetFence *setFenceNode = static_cast(fgNode); + setFenceNode->setHandleType(QSetFence::OpenGLFenceId); + setFenceNode->setHandle(QVariant::fromValue(pair.second)); + } + } +} + +// Executed in a job (in main thread when jobs done) +void Renderer::sendDisablesToFrontend(Qt3DCore::QAspectManager *manager) +{ + // SubtreeEnabled + const auto updatedDisables = std::move(m_updatedDisableSubtreeEnablers); + for (const auto &nodeId : updatedDisables) { + QSubtreeEnabler *frontend = static_cast(manager->lookupNode(nodeId)); + frontend->setEnabled(false); + } + + // Compute Commands + const QVector activeCommands = m_nodesManager->computeJobManager()->activeHandles(); + for (const HComputeCommand &handle :activeCommands) { + ComputeCommand *c = m_nodesManager->computeJobManager()->data(handle); + if (c->hasReachedFrameCount()) { + QComputeCommand *frontend = static_cast(manager->lookupNode(c->peerId())); + frontend->setEnabled(false); + c->resetHasReachedFrameCount(); + } + } +} + +// Render Thread (or QtQuick RenderThread when using Scene3D) +// Scene3D: When using Scene3D rendering, we can't assume that when +// updateGLResources is called, the resource handles points to still existing +// objects. This is because Scene3D calls doRender independently of whether all +// jobs have completed or not which in turn calls proceedToNextFrame under some +// conditions. Such conditions are usually met on startup to avoid deadlocks. +// proceedToNextFrame triggers the syncChanges calls for the next frame, which +// may contain destruction changes targeting resources. When the above +// happens, this can result in the dirtyResource vectors containing handles of +// objects that may already have been destroyed +void Renderer::updateGLResources() +{ + { + // Update active fence objects: + // - Destroy fences that have reached their signaled state + GLFenceManager *fenceManager = m_glResourceManagers->glFenceManager(); + const auto end = fenceManager->end(); + auto it = fenceManager->begin(); + while (it != end) { + const GLFence fence = it.value(); + if (m_submissionContext->wasSyncSignaled(fence)) { + // Fence was signaled, we delete it + // before removing the entry from the manager + m_submissionContext->deleteSync(fence); + it = fenceManager->erase(it); + } else { + ++it; + } + } + } + + { + Profiling::GLTimeRecorder recorder(Profiling::BufferUpload, activeProfiler()); + const QVector dirtyBufferHandles = std::move(m_dirtyBuffers); + for (const HBuffer &handle: dirtyBufferHandles) { + Buffer *buffer = m_nodesManager->bufferManager()->data(handle); + + // Can be null when using Scene3D rendering + if (buffer == nullptr) + continue; + + // Forces creation if it doesn't exit + // Also note the binding point doesn't really matter here, we just upload data + if (!m_submissionContext->hasGLBufferForBuffer(buffer)) + m_submissionContext->glBufferForRenderBuffer(buffer); + // Update the glBuffer data + m_submissionContext->updateBuffer(buffer); + buffer->unsetDirty(); + } + } + +#ifndef SHADER_LOADING_IN_COMMAND_THREAD + { + Profiling::GLTimeRecorder recorder(Profiling::ShaderUpload, activeProfiler()); + const QVector dirtyShaderHandles = std::move(m_dirtyShaders); + ShaderManager *shaderManager = m_nodesManager->shaderManager(); + for (const HShader &handle: dirtyShaderHandles) { + Shader *shader = shaderManager->data(handle); + + // Can be null when using Scene3D rendering + if (shader == nullptr) + continue; + + // Compile shader + m_submissionContext->loadShader(shader, shaderManager, m_glResourceManagers->glShaderManager()); + } + } +#endif + + { + Profiling::GLTimeRecorder recorder(Profiling::TextureUpload, activeProfiler()); + const QVector activeTextureHandles = std::move(m_dirtyTextures); + for (const HTexture &handle: activeTextureHandles) { + Texture *texture = m_nodesManager->textureManager()->data(handle); + + // Can be null when using Scene3D rendering + if (texture == nullptr) + continue; + + // Create or Update GLTexture (the GLTexture instance is created if required + // and all things that can take place without a GL context are done here) + updateTexture(texture); + } + // We want to upload textures data at this point as the SubmissionThread and + // AspectThread are locked ensuring no races between Texture/TextureImage and + // GLTexture + if (m_submissionContext != nullptr) { + GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); + const QVector glTextureHandles = glTextureManager->activeHandles(); + // Upload texture data + for (const HGLTexture &glTextureHandle : glTextureHandles) { + GLTexture *glTexture = glTextureManager->data(glTextureHandle); + + // We create/update the actual GL texture using the GL context at this point + const GLTexture::TextureUpdateInfo info = glTexture->createOrUpdateGLTexture(); + + // GLTexture creation provides us width/height/format ... information + // for textures which had not initially specified these information (TargetAutomatic...) + // Gather these information and store them to be distributed by a change next frame + const QNodeIdVector referenceTextureIds = { glTextureManager->texNodeIdForGLTexture.value(glTexture) }; + // Store properties and referenceTextureIds + if (info.wasUpdated) { + Texture::TextureUpdateInfo updateInfo; + updateInfo.properties = info.properties; + updateInfo.handleType = QAbstractTexture::OpenGLTextureId; + updateInfo.handle = info.texture ? QVariant(info.texture->textureId()) : QVariant(); + m_updatedTextureProperties.push_back({updateInfo, referenceTextureIds}); + } + } + } + + // Record ids of texture to cleanup while we are still blocking the aspect thread + m_textureIdsToCleanup += m_nodesManager->textureManager()->takeTexturesIdsToCleanup(); + } + + // Record list of buffer that might need uploading + lookForDownloadableBuffers(); +} + +// Render Thread +void Renderer::updateTexture(Texture *texture) +{ + // Check that the current texture images are still in place, if not, do not update + const bool isValid = texture->isValid(m_nodesManager->textureImageManager()); + if (!isValid) { + qWarning() << Q_FUNC_INFO << "QTexture referencing invalid QTextureImages"; + return; + } + + // All textures are unique, if you instanciate twice the exact same texture + // this will create 2 identical GLTextures, no sharing will take place + + // Try to find the associated GLTexture for the backend Texture + GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); + GLTexture *glTexture = glTextureManager->lookupResource(texture->peerId()); + + // No GLTexture associated yet -> create it + if (glTexture == nullptr) { + glTexture = glTextureManager->getOrCreateResource(texture->peerId()); + glTextureManager->texNodeIdForGLTexture.insert(glTexture, texture->peerId()); + } + + // Update GLTexture to match Texture instance + const Texture::DirtyFlags dirtyFlags = texture->dirtyFlags(); + if (dirtyFlags.testFlag(Texture::DirtySharedTextureId)) + glTexture->setSharedTextureId(texture->sharedTextureId()); + + if (dirtyFlags.testFlag(Texture::DirtyProperties)) + glTexture->setProperties(texture->properties()); + + if (dirtyFlags.testFlag(Texture::DirtyParameters)) + glTexture->setParameters(texture->parameters()); + + // Will make the texture requestUpload + if (dirtyFlags.testFlag(Texture::DirtyImageGenerators)) { + const QNodeIdVector textureImageIds = texture->textureImageIds(); + QVector images; + images.reserve(textureImageIds.size()); + // TODO: Move this into GLTexture directly + for (const QNodeId textureImageId : textureImageIds) { + const TextureImage *img = m_nodesManager->textureImageManager()->lookupResource(textureImageId); + if (img == nullptr) { + qWarning() << Q_FUNC_INFO << "invalid TextureImage handle"; + } else { + GLTexture::Image glImg {img->dataGenerator(), img->layer(), img->mipLevel(), img->face()}; + images.push_back(glImg); + } + } + glTexture->setImages(images); + } + + // Will make the texture requestUpload + if (dirtyFlags.testFlag(Texture::DirtyDataGenerator)) + glTexture->setGenerator(texture->dataGenerator()); + + // Will make the texture requestUpload + if (dirtyFlags.testFlag(Texture::DirtyPendingDataUpdates)) + glTexture->addTextureDataUpdates(texture->takePendingTextureDataUpdates()); + + // Unset the dirty flag on the texture + texture->unsetDirty(); +} + +// Render Thread +void Renderer::cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId) +{ + GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); + GLTexture *glTexture = glTextureManager->lookupResource(cleanedUpTextureId); + + // Destroying the GLTexture implicitely also destroy the GL resources + if (glTexture != nullptr) { + glTextureManager->releaseResource(cleanedUpTextureId); + glTextureManager->texNodeIdForGLTexture.remove(glTexture); + } +} + +// Render Thread +void Renderer::cleanupShader(const Shader *shader) +{ + GLShaderManager *glShaderManager = m_glResourceManagers->glShaderManager(); + GLShader *glShader = glShaderManager->lookupResource(shader->peerId()); + + if (glShader != nullptr) + glShaderManager->abandon(glShader, shader); +} + +// Called by SubmitRenderView +void Renderer::downloadGLBuffers() +{ + const QVector downloadableHandles = std::move(m_downloadableBuffers); + for (const Qt3DCore::QNodeId &bufferId : downloadableHandles) { + BufferManager *bufferManager = m_nodesManager->bufferManager(); + BufferManager::ReadLocker locker(const_cast(bufferManager)); + Buffer *buffer = bufferManager->lookupResource(bufferId); + // Buffer could have been destroyed at this point + if (!buffer) + continue; + // locker is protecting us from the buffer being destroy while we're looking + // up its content + const QByteArray content = m_submissionContext->downloadBufferContent(buffer); + m_sendBufferCaptureJob->addRequest(QPair(bufferId, content)); + } +} + +// Happens in RenderThread context when all RenderViewJobs are done +// Returns the id of the last bound FBO +Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector &renderViews) +{ + QElapsedTimer timer; + quint64 queueElapsed = 0; + timer.start(); + + const int renderViewsCount = renderViews.size(); + quint64 frameElapsed = queueElapsed; + m_lastFrameCorrect.storeRelaxed(1); // everything fine until now..... + + qCDebug(Memory) << Q_FUNC_INFO << "rendering frame "; + + // We might not want to render on the default FBO + uint lastBoundFBOId = m_submissionContext->boundFrameBufferObject(); + QSurface *surface = nullptr; + QSurface *previousSurface = nullptr; + for (const Render::RenderView *rv: renderViews) { + previousSurface = rv->surface(); + if (previousSurface) + break; + } + QSurface *lastUsedSurface = nullptr; + + bool imGuiOverlayShown = false; + for (int i = 0; i < renderViewsCount; ++i) { + // Initialize GraphicsContext for drawing + // If the RenderView has a RenderStateSet defined + const RenderView *renderView = renderViews.at(i); + + // Check if using the same surface as the previous RenderView. + // If not, we have to free up the context from the previous surface + // and make the context current on the new surface + surface = renderView->surface(); + SurfaceLocker surfaceLock(surface); + + // TO DO: Make sure that the surface we are rendering too has not been unset + + // For now, if we do not have a surface, skip this renderview + // TODO: Investigate if it's worth providing a fallback offscreen surface + // to use when surface is null. Or if we should instead expose an + // offscreensurface to Qt3D. + if (!surface || !surfaceLock.isSurfaceValid()) { + m_lastFrameCorrect.storeRelaxed(0); + continue; + } + + lastUsedSurface = surface; + const bool surfaceHasChanged = surface != previousSurface; + + if (surfaceHasChanged && previousSurface) { + const bool swapBuffers = lastBoundFBOId == m_submissionContext->defaultFBO() + && surfaceLock.isSurfaceValid() + && m_shouldSwapBuffers; + // We only call swap buffer if we are sure the previous surface is still valid + m_submissionContext->endDrawing(swapBuffers); + } + + if (surfaceHasChanged) { + // If we can't make the context current on the surface, skip to the + // next RenderView. We won't get the full frame but we may get something + if (!m_submissionContext->beginDrawing(surface)) { + qWarning() << "Failed to make OpenGL context current on surface"; + m_lastFrameCorrect.storeRelaxed(0); + continue; + } + + previousSurface = surface; + lastBoundFBOId = m_submissionContext->boundFrameBufferObject(); + } + + // Apply Memory Barrier if needed + if (renderView->memoryBarrier() != QMemoryBarrier::None) + m_submissionContext->memoryBarrier(renderView->memoryBarrier()); + + + // Insert Fence into command stream if needed + const Qt3DCore::QNodeIdVector insertFenceIds = renderView->insertFenceIds(); + GLFenceManager *fenceManager = m_glResourceManagers->glFenceManager(); + for (const Qt3DCore::QNodeId insertFenceId : insertFenceIds) { + // If the fence is not in the manager, then it hasn't been inserted + // into the command stream yet. + if (fenceManager->find(insertFenceId) == fenceManager->end()) { + // Insert fence into command stream + GLFence glFence = m_submissionContext->fenceSync(); + // Record glFence + fenceManager->insert(insertFenceId, glFence); + // Add entry for notification changes to be sent + m_updatedSetFences.push_back({insertFenceId, glFence}); + } + // If it is in the manager, then it hasn't been signaled yet, + // nothing we can do but try at the next frame + } + + // Wait for fences if needed + const QVector waitFences = renderView->waitFences(); + for (const QWaitFenceData &waitFence : waitFences) { + // TO DO + if (waitFence.handleType != QWaitFence::OpenGLFenceId) { + qWarning() << "WaitFence handleType should be OpenGLFenceId when using the Qt 3D OpenGL renderer"; + continue; + } + GLFence fence = reinterpret_cast(waitFence.handle.value()); + if (fence == nullptr) + continue; + + if (waitFence.waitOnCPU) { + m_submissionContext->clientWaitSync(fence, + waitFence.timeout); + } else { + m_submissionContext->waitSync(fence); + } + } + + // Note: the RenderStateSet is allocated once per RV if needed + // and it contains a list of StateVariant value types + RenderStateSet *renderViewStateSet = renderView->stateSet(); + + { + Profiling::GLTimeRecorder recorder(Profiling::StateUpdate, activeProfiler()); + // Set the RV state if not null, + if (renderViewStateSet != nullptr) + m_submissionContext->setCurrentStateSet(renderViewStateSet); + else + m_submissionContext->setCurrentStateSet(m_defaultRenderStateSet); + } + + // Set RenderTarget ... + // Activate RenderTarget + { + Profiling::GLTimeRecorder recorder(Profiling::RenderTargetUpdate, activeProfiler()); + m_submissionContext->activateRenderTarget(renderView->renderTargetId(), + renderView->attachmentPack(), + lastBoundFBOId); + } + + { + Profiling::GLTimeRecorder recorder(Profiling::ClearBuffer, activeProfiler()); + // set color, depth, stencil clear values (only if needed) + auto clearBufferTypes = renderView->clearTypes(); + if (clearBufferTypes & QClearBuffers::ColorBuffer) { + const QVector4D vCol = renderView->globalClearColorBufferInfo().clearColor; + m_submissionContext->clearColor(QColor::fromRgbF(vCol.x(), vCol.y(), vCol.z(), vCol.w())); + } + if (clearBufferTypes & QClearBuffers::DepthBuffer) + m_submissionContext->clearDepthValue(renderView->clearDepthValue()); + if (clearBufferTypes & QClearBuffers::StencilBuffer) + m_submissionContext->clearStencilValue(renderView->clearStencilValue()); + + // Clear BackBuffer + m_submissionContext->clearBackBuffer(clearBufferTypes); + + // if there are ClearColors set for different draw buffers, + // clear each of these draw buffers individually now + const QVector clearDrawBuffers = renderView->specificClearColorBufferInfo(); + for (const ClearBufferInfo &clearBuffer : clearDrawBuffers) + m_submissionContext->clearBufferf(clearBuffer.drawBufferIndex, clearBuffer.clearColor); + } + + // Set the Viewport + m_submissionContext->setViewport(renderView->viewport(), renderView->surfaceSize()); + + // Execute the render commands + if (!executeCommandsSubmission(renderView)) + m_lastFrameCorrect.storeRelaxed(0); // something went wrong; make sure to render the next frame! + + // executeCommandsSubmission takes care of restoring the stateset to the value + // of gc->currentContext() at the moment it was called (either + // renderViewStateSet or m_defaultRenderStateSet) + if (!renderView->renderCaptureNodeId().isNull()) { + const QRenderCaptureRequest request = renderView->renderCaptureRequest(); + const QSize size = m_submissionContext->renderTargetSize(renderView->surfaceSize()); + QRect rect(QPoint(0, 0), size); + if (!request.rect.isEmpty()) + rect = rect.intersected(request.rect); + QImage image; + if (!rect.isEmpty()) { + // Bind fbo as read framebuffer + m_submissionContext->bindFramebuffer(m_submissionContext->activeFBO(), GraphicsHelperInterface::FBORead); + image = m_submissionContext->readFramebuffer(rect); + } else { + qWarning() << "Requested capture rectangle is outside framebuffer"; + } + Render::RenderCapture *renderCapture = + static_cast(m_nodesManager->frameGraphManager()->lookupNode(renderView->renderCaptureNodeId())); + renderCapture->addRenderCapture(request.captureId, image); + if (!m_pendingRenderCaptureSendRequests.contains(renderView->renderCaptureNodeId())) + m_pendingRenderCaptureSendRequests.push_back(renderView->renderCaptureNodeId()); + } + + if (renderView->isDownloadBuffersEnable()) + downloadGLBuffers(); + + // Perform BlitFramebuffer operations + if (renderView->hasBlitFramebufferInfo()) { + const auto &blitFramebufferInfo = renderView->blitFrameBufferInfo(); + const QNodeId inputTargetId = blitFramebufferInfo.sourceRenderTargetId; + const QNodeId outputTargetId = blitFramebufferInfo.destinationRenderTargetId; + const QRect inputRect = blitFramebufferInfo.sourceRect; + const QRect outputRect = blitFramebufferInfo.destinationRect; + const QRenderTargetOutput::AttachmentPoint inputAttachmentPoint = blitFramebufferInfo.sourceAttachmentPoint; + const QRenderTargetOutput::AttachmentPoint outputAttachmentPoint = blitFramebufferInfo.destinationAttachmentPoint; + const QBlitFramebuffer::InterpolationMethod interpolationMethod = blitFramebufferInfo.interpolationMethod; + m_submissionContext->blitFramebuffer(inputTargetId, outputTargetId, inputRect, outputRect, lastBoundFBOId, + inputAttachmentPoint, outputAttachmentPoint, + interpolationMethod); + } + +#ifndef Q_OS_INTEGRITY + if (!imGuiOverlayShown && renderView->showDebugOverlay()) { + imGuiOverlayShown = true; + if (!m_imGuiRenderer) { + m_imGuiRenderer = new Debug::ImGuiRenderer(this); + if (m_settings) + m_imGuiRenderer->setCapabilities(m_settings->capabilities()); + } + + { + QMutexLocker l(&m_frameEventsMutex); + for (auto &keyEvent: m_frameKeyEvents) + m_imGuiRenderer->processEvent(&keyEvent); + for (auto &mouseEvent: m_frameMouseEvents) + m_imGuiRenderer->processEvent(&mouseEvent.second); + } + m_imGuiRenderer->renderDebugOverlay(renderViews, renderView, m_jobsInLastFrame); + } +#endif + + frameElapsed = timer.elapsed() - frameElapsed; + qCDebug(Rendering) << Q_FUNC_INFO << "Submitted Renderview " << i + 1 << "/" << renderViewsCount << "in " << frameElapsed << "ms"; + frameElapsed = timer.elapsed(); + } + + // Bind lastBoundFBOId back. Needed also in threaded mode. + // lastBoundFBOId != m_graphicsContext->activeFBO() when the last FrameGraph leaf node/renderView + // contains RenderTargetSelector/RenderTarget + if (lastBoundFBOId != m_submissionContext->activeFBO()) + m_submissionContext->bindFramebuffer(lastBoundFBOId, GraphicsHelperInterface::FBOReadAndDraw); + + // Reset state and call doneCurrent if the surface + // is valid and was actually activated + if (lastUsedSurface && m_submissionContext->hasValidGLHelper()) { + // Reset state to the default state if the last stateset is not the + // defaultRenderStateSet + if (m_submissionContext->currentStateSet() != m_defaultRenderStateSet) + m_submissionContext->setCurrentStateSet(m_defaultRenderStateSet); + } + + queueElapsed = timer.elapsed() - queueElapsed; + qCDebug(Rendering) << Q_FUNC_INFO << "Submission of Queue in " << queueElapsed << "ms <=> " << queueElapsed / renderViewsCount << "ms per RenderView <=> Avg " << 1000.0f / (queueElapsed * 1.0f/ renderViewsCount * 1.0f) << " RenderView/s"; + qCDebug(Rendering) << Q_FUNC_INFO << "Submission Completed in " << timer.elapsed() << "ms"; + + // Stores the necessary information to safely perform + // the last swap buffer call + ViewSubmissionResultData resultData; + resultData.lastBoundFBOId = lastBoundFBOId; + resultData.surface = lastUsedSurface; + return resultData; +} + +void Renderer::markDirty(BackendNodeDirtySet changes, BackendNode *node) +{ + Q_UNUSED(node) + m_dirtyBits.marked |= changes; +} + +Renderer::BackendNodeDirtySet Renderer::dirtyBits() +{ + return m_dirtyBits.marked; +} + +#if defined(QT_BUILD_INTERNAL) +void Renderer::clearDirtyBits(BackendNodeDirtySet changes) +{ + m_dirtyBits.remaining &= ~changes; + m_dirtyBits.marked &= ~changes; +} +#endif + +bool Renderer::shouldRender() const +{ + // Only render if something changed during the last frame, or the last frame + // was not rendered successfully (or render-on-demand is disabled) + return (m_settings->renderPolicy() == QRenderSettings::Always + || m_dirtyBits.marked != 0 + || m_dirtyBits.remaining != 0 + || !m_lastFrameCorrect.loadRelaxed()); +} + +void Renderer::skipNextFrame() +{ + Q_ASSERT(m_settings->renderPolicy() != QRenderSettings::Always); + + // make submitRenderViews() actually run + m_renderQueue->setNoRender(); + m_submitRenderViewsSemaphore.release(1); +} + +void Renderer::jobsDone(Qt3DCore::QAspectManager *manager) +{ + // called in main thread once all jobs are done running + + // sync captured renders to frontend + const QVector pendingCaptureIds = std::move(m_pendingRenderCaptureSendRequests); + for (const Qt3DCore::QNodeId &id : qAsConst(pendingCaptureIds)) { + auto *backend = static_cast + (m_nodesManager->frameGraphManager()->lookupNode(id)); + backend->syncRenderCapturesToFrontend(manager); + } + + // Do we need to notify any texture about property changes? + if (m_updatedTextureProperties.size() > 0) + sendTextureChangesToFrontend(manager); + + sendDisablesToFrontend(manager); +} + +// Jobs we may have to run even if no rendering will happen +QVector Renderer::preRenderingJobs() +{ + { + QMutexLocker l(&m_frameEventsMutex); + m_frameMouseEvents = m_pickEventFilter->pendingMouseEvents(); + m_frameKeyEvents = m_pickEventFilter->pendingKeyEvents(); + } + + // Set values on picking jobs + RenderSettings *renderSetting = settings(); + if (renderSetting != nullptr) { + m_pickBoundingVolumeJob->setRenderSettings(renderSetting); + m_pickBoundingVolumeJob->setFrameGraphRoot(frameGraphRoot()); + m_pickBoundingVolumeJob->setMouseEvents(m_frameMouseEvents); + m_pickBoundingVolumeJob->setKeyEvents(m_frameKeyEvents); + + m_rayCastingJob->setRenderSettings(renderSetting); + m_rayCastingJob->setFrameGraphRoot(frameGraphRoot()); + } + + QVector jobs; + + // Do we need to notify frontend about fence change? + if (m_updatedSetFences.size() > 0) + jobs.push_back(m_sendSetFenceHandlesToFrontendJob); + + if (m_sendBufferCaptureJob->hasRequests()) + jobs.push_back(m_sendBufferCaptureJob); + + jobs.append(pickBoundingVolumeJob()); + jobs.append(rayCastingJob()); + + return jobs; +} + +// Waits to be told to create jobs for the next frame +// Called by QRenderAspect jobsToExecute context of QAspectThread +// Returns all the jobs (and with proper dependency chain) required +// for the rendering of the scene +QVector Renderer::renderBinJobs() +{ + QVector renderBinJobs; + // Create the jobs to build the frame + const QVector bufferJobs = createRenderBufferJobs(); + + // Remove previous dependencies + m_calculateBoundingVolumeJob->removeDependency(QWeakPointer()); + m_cleanupJob->removeDependency(QWeakPointer()); + + // Set dependencies + for (const QAspectJobPtr &bufferJob : bufferJobs) + m_calculateBoundingVolumeJob->addDependency(bufferJob); + + m_updateLevelOfDetailJob->setFrameGraphRoot(frameGraphRoot()); + + const BackendNodeDirtySet dirtyBitsForFrame = m_dirtyBits.marked | m_dirtyBits.remaining; + m_dirtyBits.marked = {}; + m_dirtyBits.remaining = {}; + BackendNodeDirtySet notCleared = {}; + + // Add jobs + const bool entitiesEnabledDirty = dirtyBitsForFrame & AbstractRenderer::EntityEnabledDirty; + if (entitiesEnabledDirty) { + renderBinJobs.push_back(m_updateTreeEnabledJob); + // This dependency is added here because we clear all dependencies + // at the start of this function. + m_calculateBoundingVolumeJob->addDependency(m_updateTreeEnabledJob); + } + + if (dirtyBitsForFrame & AbstractRenderer::TransformDirty) { + renderBinJobs.push_back(m_worldTransformJob); + renderBinJobs.push_back(m_updateWorldBoundingVolumeJob); + renderBinJobs.push_back(m_updateShaderDataTransformJob); + } + + if (dirtyBitsForFrame & AbstractRenderer::GeometryDirty || + dirtyBitsForFrame & AbstractRenderer::BuffersDirty) { + renderBinJobs.push_back(m_calculateBoundingVolumeJob); + renderBinJobs.push_back(m_updateMeshTriangleListJob); + } + + if (dirtyBitsForFrame & AbstractRenderer::GeometryDirty || + dirtyBitsForFrame & AbstractRenderer::TransformDirty) { + renderBinJobs.push_back(m_expandBoundingVolumeJob); + } + + // TO DO: Conditionally add if skeletons dirty + renderBinJobs.push_back(m_syncLoadingJobs); + m_updateSkinningPaletteJob->setDirtyJoints(m_nodesManager->jointManager()->dirtyJoints()); + renderBinJobs.push_back(m_updateSkinningPaletteJob); + renderBinJobs.push_back(m_updateLevelOfDetailJob); + renderBinJobs.push_back(m_cleanupJob); + renderBinJobs.append(bufferJobs); + + // Jobs to prepare GL Resource upload + renderBinJobs.push_back(m_vaoGathererJob); + + if (dirtyBitsForFrame & AbstractRenderer::BuffersDirty) + renderBinJobs.push_back(m_bufferGathererJob); + + if (dirtyBitsForFrame & AbstractRenderer::TexturesDirty) + renderBinJobs.push_back(m_textureGathererJob); + + + // Layer cache is dependent on layers, layer filters (hence FG structure + // changes) and the enabled flag on entities + const bool frameGraphDirty = dirtyBitsForFrame & AbstractRenderer::FrameGraphDirty; + const bool layersDirty = dirtyBitsForFrame & AbstractRenderer::LayersDirty; + const bool layersCacheNeedsToBeRebuilt = layersDirty || entitiesEnabledDirty || frameGraphDirty; + const bool shadersDirty = dirtyBitsForFrame & AbstractRenderer::ShadersDirty; + const bool materialDirty = dirtyBitsForFrame & AbstractRenderer::MaterialDirty; + const bool lightsDirty = dirtyBitsForFrame & AbstractRenderer::LightsDirty; + const bool computeableDirty = dirtyBitsForFrame & AbstractRenderer::ComputeDirty; + const bool renderableDirty = dirtyBitsForFrame & AbstractRenderer::GeometryDirty; + const bool materialCacheNeedsToBeRebuilt = shadersDirty || materialDirty || frameGraphDirty; + const bool renderCommandsDirty = materialCacheNeedsToBeRebuilt || renderableDirty || computeableDirty; + + // Rebuild Entity Layers list if layers are dirty + if (layersDirty) + renderBinJobs.push_back(m_updateEntityLayersJob); + + if (renderableDirty) { + renderBinJobs.push_back(m_renderableEntityFilterJob); + renderBinJobs.push_back(m_cacheRenderableEntitiesJob); + } + + if (computeableDirty) { + renderBinJobs.push_back(m_computableEntityFilterJob); + renderBinJobs.push_back(m_cacheComputableEntitiesJob); + } + + if (lightsDirty) { + renderBinJobs.push_back(m_lightGathererJob); + renderBinJobs.push_back(m_cacheLightsJob); + } + + QMutexLocker lock(m_renderQueue->mutex()); + if (m_renderQueue->wasReset()) { // Have we rendered yet? (Scene3D case) + // Traverse the current framegraph. For each leaf node create a + // RenderView and set its configuration then create a job to + // populate the RenderView with a set of RenderCommands that get + // their details from the RenderNodes that are visible to the + // Camera selected by the framegraph configuration + if (frameGraphDirty) { + FrameGraphVisitor visitor(m_nodesManager->frameGraphManager()); + m_frameGraphLeaves = visitor.traverse(frameGraphRoot()); + // Remove leaf nodes that no longer exist from cache + const QList keys = m_cache.leafNodeCache.keys(); + for (FrameGraphNode *leafNode : keys) { + if (!m_frameGraphLeaves.contains(leafNode)) + m_cache.leafNodeCache.remove(leafNode); + } + + // Handle single shot subtree enablers + const auto subtreeEnablers = visitor.takeEnablersToDisable(); + for (auto *node : subtreeEnablers) + m_updatedDisableSubtreeEnablers.push_back(node->peerId()); + } + + const int fgBranchCount = m_frameGraphLeaves.size(); + for (int i = 0; i < fgBranchCount; ++i) { + FrameGraphNode *leaf = m_frameGraphLeaves.at(i); + RenderViewBuilder builder(leaf, i, this); + // If we have a new RV (wasn't in the cache before, then it contains no cached data) + const bool isNewRV = !m_cache.leafNodeCache.contains(leaf); + builder.setLayerCacheNeedsToBeRebuilt(layersCacheNeedsToBeRebuilt || isNewRV); + builder.setMaterialGathererCacheNeedsToBeRebuilt(materialCacheNeedsToBeRebuilt || isNewRV); + builder.setRenderCommandCacheNeedsToBeRebuilt(renderCommandsDirty || isNewRV); + + builder.prepareJobs(); + renderBinJobs.append(builder.buildJobHierachy()); + } + + // Set target number of RenderViews + m_renderQueue->setTargetRenderViewCount(fgBranchCount); + } else { + // FilterLayerEntityJob is part of the RenderViewBuilder jobs and must be run later + // if none of those jobs are started this frame + notCleared |= AbstractRenderer::EntityEnabledDirty; + notCleared |= AbstractRenderer::FrameGraphDirty; + notCleared |= AbstractRenderer::LayersDirty; + } + + if (isRunning() && m_submissionContext->isInitialized()) { + if (dirtyBitsForFrame & AbstractRenderer::TechniquesDirty ) + renderBinJobs.push_back(m_filterCompatibleTechniqueJob); + if (dirtyBitsForFrame & AbstractRenderer::ShadersDirty) + renderBinJobs.push_back(m_introspectShaderJob); + } else { + notCleared |= AbstractRenderer::TechniquesDirty; + notCleared |= AbstractRenderer::ShadersDirty; + } + + m_dirtyBits.remaining = dirtyBitsForFrame & notCleared; + + return renderBinJobs; +} + +QAspectJobPtr Renderer::pickBoundingVolumeJob() +{ + return m_pickBoundingVolumeJob; +} + +QAspectJobPtr Renderer::rayCastingJob() +{ + return m_rayCastingJob; +} + +QAspectJobPtr Renderer::syncLoadingJobs() +{ + return m_syncLoadingJobs; +} + +QAspectJobPtr Renderer::expandBoundingVolumeJob() +{ + return m_expandBoundingVolumeJob; +} + +QAbstractFrameAdvanceService *Renderer::frameAdvanceService() const +{ + return static_cast(m_vsyncFrameAdvanceService.data()); +} + +// Called by executeCommands +void Renderer::performDraw(RenderCommand *command) +{ + // Indirect Draw Calls + if (command->m_drawIndirect) { + + // Bind the indirect draw buffer + Buffer *indirectDrawBuffer = m_nodesManager->bufferManager()->data(command->m_indirectDrawBuffer); + if (Q_UNLIKELY(indirectDrawBuffer == nullptr)) { + qWarning() << "Invalid Indirect Draw Buffer - failed to retrieve Buffer"; + return; + } + + // Get GLBuffer from Buffer; + GLBuffer *indirectDrawGLBuffer = m_submissionContext->glBufferForRenderBuffer(indirectDrawBuffer); + if (Q_UNLIKELY(indirectDrawGLBuffer == nullptr)) { + qWarning() << "Invalid Indirect Draw Buffer - failed to retrieve GLBuffer"; + return; + } + + // Bind GLBuffer + const bool successfullyBound = indirectDrawGLBuffer->bind(m_submissionContext.data(), GLBuffer::DrawIndirectBuffer); + + if (Q_LIKELY(successfullyBound)) { + // TO DO: Handle multi draw variants if attribute count > 1 + if (command->m_drawIndexed) { + m_submissionContext->drawElementsIndirect(command->m_primitiveType, + command->m_indexAttributeDataType, + reinterpret_cast(quintptr(command->m_indirectAttributeByteOffset))); + } else { + m_submissionContext->drawArraysIndirect(command->m_primitiveType, + reinterpret_cast(quintptr(command->m_indirectAttributeByteOffset))); + } + } else { + qWarning() << "Failed to bind IndirectDrawBuffer"; + } + + } else { // Direct Draw Calls + + // TO DO: Add glMulti Draw variants + if (command->m_primitiveType == QGeometryRenderer::Patches) + m_submissionContext->setVerticesPerPatch(command->m_verticesPerPatch); + + if (command->m_primitiveRestartEnabled) + m_submissionContext->enablePrimitiveRestart(command->m_restartIndexValue); + + // TO DO: Add glMulti Draw variants + if (command->m_drawIndexed) { + Profiling::GLTimeRecorder recorder(Profiling::DrawElement, activeProfiler()); + m_submissionContext->drawElementsInstancedBaseVertexBaseInstance(command->m_primitiveType, + command->m_primitiveCount, + command->m_indexAttributeDataType, + reinterpret_cast(quintptr(command->m_indexAttributeByteOffset)), + command->m_instanceCount, + command->m_indexOffset, + command->m_firstInstance); + } else { + Profiling::GLTimeRecorder recorder(Profiling::DrawArray, activeProfiler()); + m_submissionContext->drawArraysInstancedBaseInstance(command->m_primitiveType, + command->m_firstVertex, + command->m_primitiveCount, + command->m_instanceCount, + command->m_firstInstance); + } + } + +#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) + int err = m_submissionContext->openGLContext()->functions()->glGetError(); + if (err) + qCWarning(Rendering) << "GL error after drawing mesh:" << QString::number(err, 16); +#endif + + if (command->m_primitiveRestartEnabled) + m_submissionContext->disablePrimitiveRestart(); +} + +void Renderer::performCompute(const RenderView *, RenderCommand *command) +{ + { + Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler()); + GLShader *shader = m_glResourceManagers->glShaderManager()->lookupResource(command->m_shaderId); + m_submissionContext->activateShader(shader); + } + { + Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler()); + m_submissionContext->setParameters(command->m_parameterPack); + } + { + Profiling::GLTimeRecorder recorder(Profiling::DispatchCompute, activeProfiler()); + m_submissionContext->dispatchCompute(command->m_workGroups[0], + command->m_workGroups[1], + command->m_workGroups[2]); + } + // HACK: Reset the compute flag to dirty + m_dirtyBits.marked |= AbstractRenderer::ComputeDirty; + +#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) + int err = m_submissionContext->openGLContext()->functions()->glGetError(); + if (err) + qCWarning(Rendering) << "GL error after drawing mesh:" << QString::number(err, 16); +#endif +} + +void Renderer::createOrUpdateVAO(RenderCommand *command, + HVao *previousVaoHandle, + OpenGLVertexArrayObject **vao) +{ + const VAOIdentifier vaoKey(command->m_geometry, command->m_shaderId); + + VAOManager *vaoManager = m_glResourceManagers->vaoManager(); + command->m_vao = vaoManager->lookupHandle(vaoKey); + + if (command->m_vao.isNull()) { + qCDebug(Rendering) << Q_FUNC_INFO << "Allocating new VAO"; + command->m_vao = vaoManager->getOrAcquireHandle(vaoKey); + vaoManager->data(command->m_vao)->create(m_submissionContext.data(), vaoKey); + } + + if (*previousVaoHandle != command->m_vao) { + *previousVaoHandle = command->m_vao; + *vao = vaoManager->data(command->m_vao); + } + Q_ASSERT(*vao); +} + +// Called by RenderView->submit() in RenderThread context +// Returns true, if all RenderCommands were sent to the GPU +bool Renderer::executeCommandsSubmission(const RenderView *rv) +{ + bool allCommandsIssued = true; + + // Render drawing commands + QVector commands = rv->commands(); + + // Use the graphicscontext to submit the commands to the underlying + // graphics API (OpenGL) + + // Save the RenderView base stateset + RenderStateSet *globalState = m_submissionContext->currentStateSet(); + OpenGLVertexArrayObject *vao = nullptr; + + for (RenderCommand &command : commands) { + + if (command.m_type == RenderCommand::Compute) { // Compute Call + performCompute(rv, &command); + } else { // Draw Command + // Check if we have a valid command that can be drawn + if (!command.m_isValid) { + allCommandsIssued = false; + continue; + } + + vao = m_glResourceManagers->vaoManager()->data(command.m_vao); + + // something may have went wrong when initializing the VAO + if (!vao->isSpecified()) { + allCommandsIssued = false; + continue; + } + + { + Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler()); + //// We activate the shader here + GLShader *shader = command.m_glShader; + if (!m_submissionContext->activateShader(shader)) { + allCommandsIssued = false; + continue; + } + } + + { + Profiling::GLTimeRecorder recorder(Profiling::VAOUpdate, activeProfiler()); + // Bind VAO + vao->bind(); + } + + { + Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler()); + //// Update program uniforms + if (!m_submissionContext->setParameters(command.m_parameterPack)) { + allCommandsIssued = false; + // If we have failed to set uniform (e.g unable to bind a texture) + // we won't perform the draw call which could show invalid content + continue; + } + } + + //// OpenGL State + // TO DO: Make states not dependendent on their backend node for this step + // Set state + RenderStateSet *localState = command.m_stateSet.data(); + + + { + Profiling::GLTimeRecorder recorder(Profiling::StateUpdate, activeProfiler()); + // Merge the RenderCommand state with the globalState of the RenderView + // Or restore the globalState if no stateSet for the RenderCommand + if (localState != nullptr) { + command.m_stateSet->merge(globalState); + m_submissionContext->setCurrentStateSet(localState); + } else { + m_submissionContext->setCurrentStateSet(globalState); + } + } + // All Uniforms for a pass are stored in the QUniformPack of the command + // Uniforms for Effect, Material and Technique should already have been correctly resolved + // at that point + + //// Draw Calls + performDraw(&command); + } + } // end of RenderCommands loop + + // We cache the VAO and release it only at the end of the exectute frame + // We try to minimize VAO binding between RenderCommands + if (vao) + vao->release(); + + // Reset to the state we were in before executing the render commands + m_submissionContext->setCurrentStateSet(globalState); + + return allCommandsIssued; +} + +bool Renderer::updateVAOWithAttributes(Geometry *geometry, + const RenderCommand *command, + GLShader *shader, + bool forceUpdate) +{ + m_dirtyAttributes.reserve(m_dirtyAttributes.size() + geometry->attributes().size()); + const auto attributeIds = geometry->attributes(); + + for (QNodeId attributeId : attributeIds) { + // TO DO: Improvement we could store handles and use the non locking policy on the attributeManager + Attribute *attribute = m_nodesManager->attributeManager()->lookupResource(attributeId); + + if (attribute == nullptr) + return false; + + Buffer *buffer = m_nodesManager->bufferManager()->lookupResource(attribute->bufferId()); + + // Buffer update was already performed at this point + // Just make sure the attribute reference a valid buffer + if (buffer == nullptr) + return false; + + // Index Attribute + bool attributeWasDirty = false; + if (attribute->attributeType() == QAttribute::IndexAttribute) { + if ((attributeWasDirty = attribute->isDirty()) == true || forceUpdate) + m_submissionContext->specifyIndices(buffer); + // Vertex Attribute + } else if (command->m_activeAttributes.contains(attribute->nameId())) { + if ((attributeWasDirty = attribute->isDirty()) == true || forceUpdate) { + // Find the location for the attribute + const QVector shaderAttributes = shader->attributes(); + const ShaderAttribute *attributeDescription = nullptr; + for (const ShaderAttribute &shaderAttribute : shaderAttributes) { + if (shaderAttribute.m_nameId == attribute->nameId()) { + attributeDescription = &shaderAttribute; + break; + } + } + if (!attributeDescription || attributeDescription->m_location < 0) + return false; + m_submissionContext->specifyAttribute(attribute, buffer, attributeDescription); + } + } + + // Append attribute to temporary vector so that its dirtiness + // can be cleared at the end of the frame + if (attributeWasDirty) + m_dirtyAttributes.push_back(attribute); + + // Note: We cannot call unsertDirty on the Attribute at this + // point as we don't know if the attributes are being shared + // with other geometry / geometryRenderer in which case they still + // should remain dirty so that VAO for these commands are properly + // updated + } + + return true; +} + +bool Renderer::requiresVAOAttributeUpdate(Geometry *geometry, + const RenderCommand *command) const +{ + const auto attributeIds = geometry->attributes(); + + for (QNodeId attributeId : attributeIds) { + // TO DO: Improvement we could store handles and use the non locking policy on the attributeManager + Attribute *attribute = m_nodesManager->attributeManager()->lookupResource(attributeId); + + if (attribute == nullptr) + continue; + + if ((attribute->attributeType() == QAttribute::IndexAttribute && attribute->isDirty()) || + (command->m_activeAttributes.contains(attribute->nameId()) && attribute->isDirty())) + return true; + } + return false; +} + +// Erase graphics related resources that may become unused after a frame +void Renderer::cleanGraphicsResources() +{ + // Clean buffers + const QVector buffersToRelease = m_nodesManager->bufferManager()->takeBuffersToRelease(); + for (Qt3DCore::QNodeId bufferId : buffersToRelease) + m_submissionContext->releaseBuffer(bufferId); + + // When Textures are cleaned up, their id is saved so that they can be + // cleaned up in the render thread + const QVector cleanedUpTextureIds = std::move(m_textureIdsToCleanup); + for (const Qt3DCore::QNodeId textureCleanedUpId: cleanedUpTextureIds) + cleanupTexture(textureCleanedUpId); + + // Delete abandoned VAOs + m_abandonedVaosMutex.lock(); + const QVector abandonedVaos = std::move(m_abandonedVaos); + m_abandonedVaosMutex.unlock(); + for (const HVao &vaoHandle : abandonedVaos) { + // might have already been destroyed last frame, but added by the cleanup job before, so + // check if the VAO is really still existent + OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(vaoHandle); + if (vao) { + vao->destroy(); + // We remove VAO from manager using its VAOIdentifier + m_glResourceManagers->vaoManager()->release(vaoHandle); + } + } + + // Abandon GL shaders when a Shader node is destroyed Note: We are sure + // that when this gets executed, all scene changes have been received and + // shader nodes updated + const QVector cleanedUpShaderIds = m_nodesManager->shaderManager()->takeShaderIdsToCleanup(); + for (const Qt3DCore::QNodeId shaderCleanedUpId: cleanedUpShaderIds) { + cleanupShader(m_nodesManager->shaderManager()->lookupResource(shaderCleanedUpId)); + // We can really release the texture at this point + m_nodesManager->shaderManager()->releaseResource(shaderCleanedUpId); + } +} + +const GraphicsApiFilterData *Renderer::contextInfo() const +{ + return m_submissionContext->contextInfo(); +} + +SubmissionContext *Renderer::submissionContext() const +{ + return m_submissionContext.data(); +} + +// Returns a vector of jobs to be performed for dirty buffers +// 1 dirty buffer == 1 job, all job can be performed in parallel +QVector Renderer::createRenderBufferJobs() const +{ + const QVector dirtyBuffers = m_nodesManager->bufferManager()->takeDirtyBuffers(); + QVector dirtyBuffersJobs; + dirtyBuffersJobs.reserve(dirtyBuffers.size()); + + for (const QNodeId bufId : dirtyBuffers) { + Render::HBuffer bufferHandle = m_nodesManager->lookupHandle(bufId); + if (!bufferHandle.isNull()) { + // Create new buffer job + auto job = Render::LoadBufferJobPtr::create(bufferHandle); + job->setNodeManager(m_nodesManager); + dirtyBuffersJobs.push_back(job); + } + } + + return dirtyBuffersJobs; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/renderer.pri b/src/plugins/renderers/opengl/renderer/renderer.pri new file mode 100644 index 000000000..0f68aa481 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderer.pri @@ -0,0 +1,28 @@ +INCLUDEPATH += $$PWD + +SOURCES += \ + $$PWD/openglvertexarrayobject.cpp \ + $$PWD/rendercommand.cpp \ + $$PWD/renderer.cpp \ + $$PWD/renderqueue.cpp \ + $$PWD/renderview.cpp \ + $$PWD/renderviewbuilder.cpp \ + $$PWD/shaderparameterpack.cpp \ + $$PWD/glshader.cpp \ + $$PWD/logging.cpp \ + $$PWD/commandexecuter.cpp + +HEADERS += \ + $$PWD/openglvertexarrayobject_p.h \ + $$PWD/renderercache_p.h \ + $$PWD/rendercommand_p.h \ + $$PWD/renderer_p.h \ + $$PWD/renderqueue_p.h \ + $$PWD/renderview_p.h \ + $$PWD/renderviewbuilder_p.h \ + $$PWD/shaderparameterpack_p.h \ + $$PWD/shadervariables_p.h \ + $$PWD/glshader_p.h \ + $$PWD/glfence_p.h \ + $$PWD/logging_p.h \ + $$PWD/commandexecuter_p.h diff --git a/src/plugins/renderers/opengl/renderer/renderer_p.h b/src/plugins/renderers/opengl/renderer/renderer_p.h new file mode 100644 index 000000000..bb05694fb --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderer_p.h @@ -0,0 +1,479 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERER_H +#define QT3DRENDER_RENDER_RENDERER_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if defined(QT_BUILD_INTERNAL) +class tst_Renderer; +#endif + +QT_BEGIN_NAMESPACE + +class QSurface; +class QMouseEvent; +class QScreen; + +namespace Qt3DCore { +class QEntity; +class QFrameAllocator; +class QEventFilterService; +} + +namespace Qt3DRender { + +class QCamera; +class QMaterial; +class QShaderProgram; +class QMesh; +class QRenderPass; +class QAbstractShapeMesh; +struct GraphicsApiFilterData; +class QSceneImporter; + +namespace Debug { +class CommandExecuter; +} + +namespace Render { + +namespace Profiling { +class FrameProfiler; +} + +class CameraLens; +class SubmissionContext; +class FrameGraphNode; +class Material; +class Technique; +class Shader; +class Entity; +class RenderCommand; +class RenderQueue; +class RenderView; +class Effect; +class RenderPass; +class RenderThread; +class RenderStateSet; +class VSyncFrameAdvanceService; +class PickEventFilter; +class NodeManagers; +class GLResourceManagers; +class GLShader; +class ResourceAccessor; + +class UpdateLevelOfDetailJob; +typedef QSharedPointer UpdateLevelOfDetailJobPtr; + +using SynchronizerJobPtr = GenericLambdaJobPtr>; +using SynchronizerPostFramePtr = GenericLambdaJobAndPostFramePtr, std::function>; + +template +class FilterEntityByComponentJob; +template +using FilterEntityByComponentJobPtr = QSharedPointer>; +using ComputableEntityFilterPtr = FilterEntityByComponentJobPtr; +using RenderableEntityFilterPtr = FilterEntityByComponentJobPtr; + +namespace Debug { +class ImGuiRenderer; +} + +class Q_AUTOTEST_EXPORT Renderer : public AbstractRenderer +{ +public: + explicit Renderer(QRenderAspect::RenderType type); + ~Renderer(); + + void dumpInfo() const override; + API api() const override { return AbstractRenderer::OpenGL; } + + qint64 time() const override; + void setTime(qint64 time) override; + void setJobsInLastFrame(int jobsInLastFrame) override; + + void setNodeManagers(NodeManagers *managers) override; + void setServices(Qt3DCore::QServiceLocator *services) override; + void setSurfaceExposed(bool exposed) override; + + NodeManagers *nodeManagers() const override; + Qt3DCore::QServiceLocator *services() const override { return m_services; } + + void initialize() override; + void shutdown() override; + void releaseGraphicsResources() override; + + void render() override; + void doRender(bool swapBuffers = true) override; + void cleanGraphicsResources() override; + + bool isRunning() const override { return m_running.loadRelaxed(); } + + void setSceneRoot(Entity *sgRoot) override; + Entity *sceneRoot() const override { return m_renderSceneRoot; } + + FrameGraphNode *frameGraphRoot() const override; + RenderQueue *renderQueue() const { return m_renderQueue; } + + void markDirty(BackendNodeDirtySet changes, BackendNode *node) override; + BackendNodeDirtySet dirtyBits() override; + +#if defined(QT_BUILD_INTERNAL) + void clearDirtyBits(BackendNodeDirtySet changes) override; +#endif + bool shouldRender() const override; + void skipNextFrame() override; + void jobsDone(Qt3DCore::QAspectManager *manager) override; + + QVector preRenderingJobs() override; + QVector renderBinJobs() override; + Qt3DCore::QAspectJobPtr pickBoundingVolumeJob() override; + Qt3DCore::QAspectJobPtr rayCastingJob() override; + Qt3DCore::QAspectJobPtr syncLoadingJobs() override; + Qt3DCore::QAspectJobPtr expandBoundingVolumeJob() override; + + QVector createRenderBufferJobs() const; + + inline FrameCleanupJobPtr frameCleanupJob() const { return m_cleanupJob; } + inline UpdateShaderDataTransformJobPtr updateShaderDataTransformJob() const { return m_updateShaderDataTransformJob; } + inline CalculateBoundingVolumeJobPtr calculateBoundingVolumeJob() const { return m_calculateBoundingVolumeJob; } + inline UpdateTreeEnabledJobPtr updateTreeEnabledJob() const { return m_updateTreeEnabledJob; } + inline UpdateWorldTransformJobPtr updateWorldTransformJob() const { return m_worldTransformJob; } + inline UpdateWorldBoundingVolumeJobPtr updateWorldBoundingVolumeJob() const { return m_updateWorldBoundingVolumeJob; } + inline UpdateLevelOfDetailJobPtr updateLevelOfDetailJob() const { return m_updateLevelOfDetailJob; } + inline UpdateMeshTriangleListJobPtr updateMeshTriangleListJob() const { return m_updateMeshTriangleListJob; } + inline FilterCompatibleTechniqueJobPtr filterCompatibleTechniqueJob() const { return m_filterCompatibleTechniqueJob; } + inline SynchronizerJobPtr syncLoadingJobs() const { return m_syncLoadingJobs; } + inline UpdateSkinningPaletteJobPtr updateSkinningPaletteJob() const { return m_updateSkinningPaletteJob; } + inline SynchronizerPostFramePtr introspectShadersJob() const { return m_introspectShaderJob; } + inline Qt3DCore::QAspectJobPtr bufferGathererJob() const { return m_bufferGathererJob; } + inline Qt3DCore::QAspectJobPtr textureGathererJob() const { return m_textureGathererJob; } + inline UpdateEntityLayersJobPtr updateEntityLayersJob() const { return m_updateEntityLayersJob; } + inline LightGathererPtr lightGathererJob() const { return m_lightGathererJob; } + inline RenderableEntityFilterPtr renderableEntityFilterJob() const { return m_renderableEntityFilterJob; } + inline ComputableEntityFilterPtr computableEntityFilterJob() const { return m_computableEntityFilterJob; } + inline SynchronizerJobPtr cacheLightJob() const { return m_cacheLightsJob; } + inline SynchronizerJobPtr cacheRenderableEntitiesJob() const { return m_cacheRenderableEntitiesJob; } + inline SynchronizerJobPtr cacheComputableEntitiesJob() const { return m_cacheComputableEntitiesJob; } + + Qt3DCore::QAbstractFrameAdvanceService *frameAdvanceService() const override; + + void registerEventFilter(Qt3DCore::QEventFilterService *service) override; + + void setSettings(RenderSettings *settings) override; + RenderSettings *settings() const override; + QOpenGLContext *shareContext() const override; + + inline GLResourceManagers *glResourceManagers() const { return m_glResourceManagers; } + + // Executed in secondary GL thread + void loadShader(Shader *shader, Qt3DRender::Render::HShader shaderHandle) override; + + + void updateGLResources(); + void updateTexture(Texture *texture); + void cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId); + void cleanupShader(const Shader *shader); + void downloadGLBuffers(); + void blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId, + Qt3DCore::QNodeId outputRenderTargetId, + QRect inputRect, + QRect outputRect, + GLuint defaultFramebuffer); + + void prepareCommandsSubmission(const QVector &renderViews); + bool executeCommandsSubmission(const RenderView *rv); + bool updateVAOWithAttributes(Geometry *geometry, + const RenderCommand *command, + GLShader *shader, + bool forceUpdate); + + bool requiresVAOAttributeUpdate(Geometry *geometry, + const RenderCommand *command) const; + + // For Scene2D rendering + void setOpenGLContext(QOpenGLContext *context) override; + bool accessOpenGLTexture(Qt3DCore::QNodeId nodeId, + QOpenGLTexture **texture, + QMutex **lock, + bool readonly) override; + QSharedPointer resourceAccessor() const override; + + + const GraphicsApiFilterData *contextInfo() const; + SubmissionContext *submissionContext() const; + + inline RenderStateSet *defaultRenderState() const { return m_defaultRenderStateSet; } + + void enqueueRenderView(RenderView *renderView, int submitOrder); + bool isReadyToSubmit(); + + QVariant executeCommand(const QStringList &args) override; + void setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) override; + QSurfaceFormat format() override; + + struct ViewSubmissionResultData + { + ViewSubmissionResultData() + : lastBoundFBOId(0) + , surface(nullptr) + {} + + uint lastBoundFBOId; + QSurface *surface; + }; + + ViewSubmissionResultData submitRenderViews(const QVector &renderViews); + + RendererCache *cache() { return &m_cache; } + void setScreen(QScreen *scr) override; + QScreen *screen() const override; + +#ifdef QT3D_RENDER_UNIT_TESTS +public: +#else + +private: +#endif + bool canRender() const; + Profiling::FrameProfiler *activeProfiler() const; + + Qt3DCore::QServiceLocator *m_services; + NodeManagers *m_nodesManager; + + // Frame graph root + Qt3DCore::QNodeId m_frameGraphRootUuid; + + Entity *m_renderSceneRoot; + + // Fail safe values that we can use if a RenderCommand + // is missing a shader + RenderStateSet *m_defaultRenderStateSet; + ShaderParameterPack m_defaultUniformPack; + + QScopedPointer m_submissionContext; + QSurfaceFormat m_format; + + RenderQueue *m_renderQueue; + QScopedPointer m_renderThread; + QScopedPointer m_vsyncFrameAdvanceService; + + QSemaphore m_submitRenderViewsSemaphore; + QSemaphore m_waitForInitializationToBeCompleted; + QMutex m_hasBeenInitializedMutex; + + QAtomicInt m_running; + + QScopedPointer m_pickEventFilter; + + QVector m_dirtyAttributes; + QVector m_dirtyGeometry; + QAtomicInt m_exposed; + + struct DirtyBits { + BackendNodeDirtySet marked; // marked dirty since last job build + BackendNodeDirtySet remaining; // remaining dirty after jobs have finished + }; + DirtyBits m_dirtyBits; + + QAtomicInt m_lastFrameCorrect; + QOpenGLContext *m_glContext; + QOpenGLContext *m_shareContext; + mutable QMutex m_shareContextMutex; + PickBoundingVolumeJobPtr m_pickBoundingVolumeJob; + RayCastingJobPtr m_rayCastingJob; + + qint64 m_time; + + RenderSettings *m_settings; + + UpdateShaderDataTransformJobPtr m_updateShaderDataTransformJob; + FrameCleanupJobPtr m_cleanupJob; + UpdateWorldTransformJobPtr m_worldTransformJob; + ExpandBoundingVolumeJobPtr m_expandBoundingVolumeJob; + CalculateBoundingVolumeJobPtr m_calculateBoundingVolumeJob; + UpdateWorldBoundingVolumeJobPtr m_updateWorldBoundingVolumeJob; + UpdateTreeEnabledJobPtr m_updateTreeEnabledJob; + SendBufferCaptureJobPtr m_sendBufferCaptureJob; + UpdateSkinningPaletteJobPtr m_updateSkinningPaletteJob; + UpdateLevelOfDetailJobPtr m_updateLevelOfDetailJob; + UpdateMeshTriangleListJobPtr m_updateMeshTriangleListJob; + FilterCompatibleTechniqueJobPtr m_filterCompatibleTechniqueJob; + UpdateEntityLayersJobPtr m_updateEntityLayersJob; + LightGathererPtr m_lightGathererJob; + RenderableEntityFilterPtr m_renderableEntityFilterJob; + ComputableEntityFilterPtr m_computableEntityFilterJob; + + QVector m_pendingRenderCaptureSendRequests; + + void performDraw(RenderCommand *command); + void performCompute(const RenderView *rv, RenderCommand *command); + void createOrUpdateVAO(RenderCommand *command, + HVao *previousVAOHandle, + OpenGLVertexArrayObject **vao); + + SynchronizerJobPtr m_bufferGathererJob; + SynchronizerJobPtr m_vaoGathererJob; + SynchronizerJobPtr m_textureGathererJob; + SynchronizerJobPtr m_sendSetFenceHandlesToFrontendJob; + SynchronizerPostFramePtr m_introspectShaderJob; + SynchronizerJobPtr m_syncLoadingJobs; + SynchronizerJobPtr m_cacheRenderableEntitiesJob; + SynchronizerJobPtr m_cacheComputableEntitiesJob; + SynchronizerJobPtr m_cacheLightsJob; + + void lookForAbandonedVaos(); + void lookForDirtyBuffers(); + void lookForDownloadableBuffers(); + void lookForDirtyTextures(); + void reloadDirtyShaders(); + void sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager); + void sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager); + void sendSetFenceHandlesToFrontend(); + void sendDisablesToFrontend(Qt3DCore::QAspectManager *manager); + + QMutex m_abandonedVaosMutex; + QVector m_abandonedVaos; + + QVector m_dirtyBuffers; + QVector m_downloadableBuffers; + QVector m_dirtyShaders; + QVector m_dirtyTextures; + QVector> m_updatedTextureProperties; + QVector> m_updatedSetFences; + QVector m_updatedDisableSubtreeEnablers; + Qt3DCore::QNodeIdVector m_textureIdsToCleanup; + QVector m_shaderBuilderUpdates; + + bool m_ownedContext; + + OffscreenSurfaceHelper *m_offscreenHelper; + GLResourceManagers *m_glResourceManagers; + QMutex m_offscreenSurfaceMutex; + + QScopedPointer m_commandExecuter; + + mutable QScopedPointer m_frameProfiler; + +#ifdef QT_BUILD_INTERNAL + friend class ::tst_Renderer; +#endif + + QMetaObject::Connection m_contextConnection; + RendererCache m_cache; + bool m_shouldSwapBuffers; + + QVector m_frameGraphLeaves; + QScreen *m_screen = nullptr; + QSharedPointer m_scene2DResourceAccessor; + + Debug::ImGuiRenderer *m_imGuiRenderer; + QList> m_frameMouseEvents; + QList m_frameKeyEvents; + QMutex m_frameEventsMutex; + int m_jobsInLastFrame; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERER_H diff --git a/src/plugins/renderers/opengl/renderer/renderercache_p.h b/src/plugins/renderers/opengl/renderer/renderercache_p.h new file mode 100644 index 000000000..70a5ef43c --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderercache_p.h @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERERCACHE_P_H +#define QT3DRENDER_RENDER_RENDERERCACHE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +struct RendererCache +{ + struct LeafNodeData + { + QVector filterEntitiesByLayer; + MaterialParameterGathererData materialParameterGatherer; + EntityRenderCommandData renderCommandData; + }; + + // Shared amongst all RV cache + QVector renderableEntities; + QVector computeEntities; + QVector gatheredLights; + EnvironmentLight* environmentLight; + + // Per RV cache + QHash leafNodeCache; + + QMutex *mutex() { return &m_mutex; } + +private: + QMutex m_mutex; +}; + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERERCACHE_P_H diff --git a/src/plugins/renderers/opengl/renderer/renderqueue.cpp b/src/plugins/renderers/opengl/renderer/renderqueue.cpp new file mode 100644 index 000000000..9ba66952f --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderqueue.cpp @@ -0,0 +1,133 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderqueue_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +RenderQueue::RenderQueue() + : m_noRender(false) + , m_wasReset(true) + , m_targetRenderViewCount(0) + , m_currentRenderViewCount(0) + , m_currentWorkQueue(1) +{ +} + +int RenderQueue::currentRenderViewCount() const +{ + return m_currentRenderViewCount; +} + +/* + * In case the framegraph changed or when the current number of render queue + * needs to be reset. + */ +void RenderQueue::reset() +{ + m_currentRenderViewCount = 0; + m_targetRenderViewCount = 0; + m_currentWorkQueue.clear(); + m_noRender = false; + m_wasReset = true; +} + +void RenderQueue::setNoRender() +{ + Q_ASSERT(m_targetRenderViewCount == 0); + m_noRender = true; +} + +/* + * Queue up a RenderView for the frame being built. + * Thread safe as this is called from the renderer which is locked. + * Returns true if the renderView is complete + */ +bool RenderQueue::queueRenderView(RenderView *renderView, uint submissionOrderIndex) +{ + Q_ASSERT(!m_noRender); + m_currentWorkQueue[submissionOrderIndex] = renderView; + ++m_currentRenderViewCount; + Q_ASSERT(m_currentRenderViewCount <= m_targetRenderViewCount); + return isFrameQueueComplete(); +} + +/* + * Called by the Rendering Thread to retrieve the a frame queue to render. + * A call to reset is required after rendering of the frame. Otherwise under some + * conditions the current but then invalidated frame queue could be reused. + */ +QVector RenderQueue::nextFrameQueue() +{ + return m_currentWorkQueue; +} + +/* + * Sets the number \a targetRenderViewCount of RenderView objects that make up a frame. + */ +void RenderQueue::setTargetRenderViewCount(int targetRenderViewCount) +{ + Q_ASSERT(!m_noRender); + m_targetRenderViewCount = targetRenderViewCount; + m_currentWorkQueue.resize(targetRenderViewCount); + m_wasReset = false; +} + +/* + * Returns true if all the RenderView objects making up the current frame have been queued. + * Returns false otherwise. + * \note a frameQueue or size 0 is considered incomplete. + */ +bool RenderQueue::isFrameQueueComplete() const +{ + return (m_noRender + || (m_targetRenderViewCount > 0 && m_targetRenderViewCount == m_currentRenderViewCount)); +} + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/renderqueue_p.h b/src/plugins/renderers/opengl/renderer/renderqueue_p.h new file mode 100644 index 000000000..e565115f2 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderqueue_p.h @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERQUEUE_H +#define QT3DRENDER_RENDER_RENDERQUEUE_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class RenderView; + +class Q_AUTOTEST_EXPORT RenderQueue +{ +public: + RenderQueue(); + + void setTargetRenderViewCount(int targetRenderViewCount); + int targetRenderViewCount() const { return m_targetRenderViewCount; } + int currentRenderViewCount() const; + bool isFrameQueueComplete() const; + + bool queueRenderView(RenderView *renderView, uint submissionOrderIndex); + QVector nextFrameQueue(); + void reset(); + + void setNoRender(); + inline bool isNoRender() const { return m_noRender; } + + inline bool wasReset() const { return m_wasReset; } + + inline QMutex *mutex() { return &m_mutex; } + +private: + bool m_noRender; + bool m_wasReset; + int m_targetRenderViewCount; + int m_currentRenderViewCount; + QVector m_currentWorkQueue; + QMutex m_mutex; +}; + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERQUEUE_H diff --git a/src/plugins/renderers/opengl/renderer/renderview.cpp b/src/plugins/renderers/opengl/renderer/renderview.cpp new file mode 100644 index 000000000..c6a6ddbbb --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderview.cpp @@ -0,0 +1,1238 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderview_p.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) +#include +#endif + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + + +namespace { + +// register our QNodeId's as a metatype during program loading +const int Q_DECL_UNUSED qNodeIdTypeId = qMetaTypeId(); + +const int MAX_LIGHTS = 8; + +#define LIGHT_POSITION_NAME QLatin1String(".position") +#define LIGHT_TYPE_NAME QLatin1String(".type") +#define LIGHT_COLOR_NAME QLatin1String(".color") +#define LIGHT_INTENSITY_NAME QLatin1String(".intensity") + +int LIGHT_COUNT_NAME_ID = 0; +int LIGHT_POSITION_NAMES[MAX_LIGHTS]; +int LIGHT_TYPE_NAMES[MAX_LIGHTS]; +int LIGHT_COLOR_NAMES[MAX_LIGHTS]; +int LIGHT_INTENSITY_NAMES[MAX_LIGHTS]; +QString LIGHT_STRUCT_NAMES[MAX_LIGHTS]; + +int LIGHT_POSITION_UNROLL_NAMES[MAX_LIGHTS]; +int LIGHT_TYPE_UNROLL_NAMES[MAX_LIGHTS]; +int LIGHT_COLOR_UNROLL_NAMES[MAX_LIGHTS]; +int LIGHT_INTENSITY_UNROLL_NAMES[MAX_LIGHTS]; +QString LIGHT_STRUCT_UNROLL_NAMES[MAX_LIGHTS]; + +bool wasInitialized = false; + +} // anonymous namespace + +RenderView::StandardUniformsNameToTypeHash RenderView::ms_standardUniformSetters; + + +RenderView::StandardUniformsNameToTypeHash RenderView::initializeStandardUniformSetters() +{ + RenderView::StandardUniformsNameToTypeHash setters; + + setters.insert(Shader::modelMatrixNameId, ModelMatrix); + setters.insert(Shader::viewMatrixNameId, ViewMatrix); + setters.insert(Shader::projectionMatrixNameId, ProjectionMatrix); + setters.insert(Shader::modelViewMatrixNameId, ModelViewMatrix); + setters.insert(Shader::viewProjectionMatrixNameId, ViewProjectionMatrix); + setters.insert(Shader::modelViewProjectionNameId, ModelViewProjectionMatrix); + setters.insert(Shader::mvpNameId, ModelViewProjectionMatrix); + setters.insert(Shader::inverseModelMatrixNameId, InverseModelMatrix); + setters.insert(Shader::inverseViewMatrixNameId, InverseViewMatrix); + setters.insert(Shader::inverseProjectionMatrixNameId, InverseProjectionMatrix); + setters.insert(Shader::inverseModelViewNameId, InverseModelViewMatrix); + setters.insert(Shader::inverseViewProjectionMatrixNameId, InverseViewProjectionMatrix); + setters.insert(Shader::inverseModelViewProjectionNameId, InverseModelViewProjectionMatrix); + setters.insert(Shader::modelNormalMatrixNameId, ModelNormalMatrix); + setters.insert(Shader::modelViewNormalNameId, ModelViewNormalMatrix); + setters.insert(Shader::viewportMatrixNameId, ViewportMatrix); + setters.insert(Shader::inverseViewportMatrixNameId, InverseViewportMatrix); + setters.insert(Shader::aspectRatioNameId, AspectRatio); + setters.insert(Shader::exposureNameId, Exposure); + setters.insert(Shader::gammaNameId, Gamma); + setters.insert(Shader::timeNameId, Time); + setters.insert(Shader::eyePositionNameId, EyePosition); + setters.insert(Shader::skinningPaletteNameId, SkinningPalette); + + return setters; +} + +// TODO: Move this somewhere global where GraphicsContext::setViewport() can use it too +static QRectF resolveViewport(const QRectF &fractionalViewport, const QSize &surfaceSize) +{ + return QRectF(fractionalViewport.x() * surfaceSize.width(), + (1.0 - fractionalViewport.y() - fractionalViewport.height()) * surfaceSize.height(), + fractionalViewport.width() * surfaceSize.width(), + fractionalViewport.height() * surfaceSize.height()); +} + +static Matrix4x4 getProjectionMatrix(const CameraLens *lens) +{ + if (!lens) + qWarning() << "[Qt3D Renderer] No Camera Lens found. Add a CameraSelector to your Frame Graph or make sure that no entities will be rendered."; + return lens ? lens->projection() : Matrix4x4(); +} + +UniformValue RenderView::standardUniformValue(RenderView::StandardUniform standardUniformType, + Entity *entity, + const Matrix4x4 &model) const +{ + switch (standardUniformType) { + case ModelMatrix: + return UniformValue(model); + case ViewMatrix: + return UniformValue(m_data.m_viewMatrix); + case ProjectionMatrix: + return UniformValue(getProjectionMatrix(m_data.m_renderCameraLens)); + case ModelViewMatrix: + return UniformValue(m_data.m_viewMatrix * model); + case ViewProjectionMatrix: + return UniformValue(getProjectionMatrix(m_data.m_renderCameraLens) * m_data.m_viewMatrix); + case ModelViewProjectionMatrix: + return UniformValue(m_data.m_viewProjectionMatrix * model); + case InverseModelMatrix: + return UniformValue(model.inverted()); + case InverseViewMatrix: + return UniformValue(m_data.m_viewMatrix.inverted()); + case InverseProjectionMatrix: { + return UniformValue(getProjectionMatrix(m_data.m_renderCameraLens).inverted()); + } + case InverseModelViewMatrix: + return UniformValue((m_data.m_viewMatrix * model).inverted()); + case InverseViewProjectionMatrix: { + const Matrix4x4 viewProjectionMatrix = getProjectionMatrix(m_data.m_renderCameraLens) * m_data.m_viewMatrix; + return UniformValue(viewProjectionMatrix.inverted()); + } + case InverseModelViewProjectionMatrix: + return UniformValue((m_data.m_viewProjectionMatrix * model).inverted()); + case ModelNormalMatrix: + return UniformValue(convertToQMatrix4x4(model).normalMatrix()); + case ModelViewNormalMatrix: + return UniformValue(convertToQMatrix4x4(m_data.m_viewMatrix * model).normalMatrix()); + case ViewportMatrix: { + QMatrix4x4 viewportMatrix; + // TO DO: Implement on Matrix4x4 + viewportMatrix.viewport(resolveViewport(m_viewport, m_surfaceSize)); + return UniformValue(Matrix4x4(viewportMatrix)); + } + case InverseViewportMatrix: { + QMatrix4x4 viewportMatrix; + // TO DO: Implement on Matrix4x4 + viewportMatrix.viewport(resolveViewport(m_viewport, m_surfaceSize)); + return UniformValue(Matrix4x4(viewportMatrix.inverted())); + } + case AspectRatio: + return float(m_surfaceSize.width()) / std::max(1.f, float(m_surfaceSize.height())); + case Exposure: + return UniformValue(m_data.m_renderCameraLens ? m_data.m_renderCameraLens->exposure() : 0.0f); + case Gamma: + return UniformValue(m_gamma); + case Time: + return UniformValue(float(m_renderer->time() / 1000000000.0f)); + case EyePosition: + return UniformValue(m_data.m_eyePos); + case SkinningPalette: { + const Armature *armature = entity->renderComponent(); + if (!armature) { + qCWarning(Jobs, "Requesting skinningPalette uniform but no armature set on entity"); + return UniformValue(); + } + return armature->skinningPaletteUniform(); + } + default: + Q_UNREACHABLE(); + return UniformValue(); + } +} + +RenderView::RenderView() + : m_isDownloadBuffersEnable(false) + , m_hasBlitFramebufferInfo(false) + , m_renderer(nullptr) + , m_manager(nullptr) + , m_devicePixelRatio(1.) + , m_viewport(QRectF(0., 0., 1., 1.)) + , m_gamma(2.2f) + , m_surface(nullptr) + , m_clearBuffer(QClearBuffers::None) + , m_clearDepthValue(1.f) + , m_clearStencilValue(0) + , m_stateSet(nullptr) + , m_noDraw(false) + , m_compute(false) + , m_frustumCulling(false) + , m_showDebugOverlay(false) + , m_memoryBarrier(QMemoryBarrier::None) + , m_environmentLight(nullptr) +{ + m_workGroups[0] = 1; + m_workGroups[1] = 1; + m_workGroups[2] = 1; + + if (Q_UNLIKELY(!wasInitialized)) { + // Needed as we can control the init order of static/global variables across compile units + // and this hash relies on the static StringToInt class + wasInitialized = true; + RenderView::ms_standardUniformSetters = RenderView::initializeStandardUniformSetters(); + LIGHT_COUNT_NAME_ID = StringToInt::lookupId(QLatin1String("lightCount")); + for (int i = 0; i < MAX_LIGHTS; ++i) { + Q_STATIC_ASSERT_X(MAX_LIGHTS < 10, "can't use the QChar trick anymore"); + LIGHT_STRUCT_NAMES[i] = QLatin1String("lights[") + QLatin1Char(char('0' + i)) + QLatin1Char(']'); + LIGHT_POSITION_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_POSITION_NAME); + LIGHT_TYPE_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_TYPE_NAME); + LIGHT_COLOR_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_COLOR_NAME); + LIGHT_INTENSITY_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_INTENSITY_NAME); + + LIGHT_STRUCT_UNROLL_NAMES[i] = QLatin1String("light_") + QLatin1Char(char('0' + i)); + LIGHT_POSITION_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_POSITION_NAME); + LIGHT_TYPE_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_TYPE_NAME); + LIGHT_COLOR_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_COLOR_NAME); + LIGHT_INTENSITY_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_INTENSITY_NAME); + } + } +} + +RenderView::~RenderView() +{ + delete m_stateSet; +} + +namespace { + +template +struct AdjacentSubRangeFinder +{ + static bool adjacentSubRange(const RenderCommand &, const RenderCommand &) + { + Q_UNREACHABLE(); + return false; + } +}; + +template<> +struct AdjacentSubRangeFinder +{ + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) + { + return a.m_changeCost == b.m_changeCost; + } +}; + +template<> +struct AdjacentSubRangeFinder +{ + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) + { + return a.m_depth == b.m_depth; + } +}; + +template<> +struct AdjacentSubRangeFinder +{ + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) + { + return a.m_glShader == b.m_glShader; + } +}; + +template<> +struct AdjacentSubRangeFinder +{ + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) + { + return a.m_depth == b.m_depth; + } +}; + +template<> +struct AdjacentSubRangeFinder +{ + static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) + { + // Two renderCommands are adjacent if one contains all the other command's textures + QVector texturesA = a.m_parameterPack.textures(); + QVector texturesB = b.m_parameterPack.textures(); + + if (texturesB.size() > texturesA.size()) + qSwap(texturesA, texturesB); + + // textureB.size() is always <= textureA.size() + for (const ShaderParameterPack::NamedResource &texB : qAsConst(texturesB)) { + if (!texturesA.contains(texB)) + return false; + } + return true; + } +}; + +template +int advanceUntilNonAdjacent(const QVector &commands, + const int beg, const int end, Predicate pred) +{ + int i = beg + 1; + while (i < end) { + if (!pred(*(commands.begin() + beg), *(commands.begin() + i))) + break; + ++i; + } + return i; +} + + +using CommandIt = QVector::iterator; + +template +struct SubRangeSorter +{ + static void sortSubRange(CommandIt begin, const CommandIt end) + { + Q_UNUSED(begin); + Q_UNUSED(end); + Q_UNREACHABLE(); + } +}; + +template<> +struct SubRangeSorter +{ + static void sortSubRange(CommandIt begin, const CommandIt end) + { + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_changeCost > b.m_changeCost; + }); + } +}; + +template<> +struct SubRangeSorter +{ + static void sortSubRange(CommandIt begin, const CommandIt end) + { + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_depth > b.m_depth; + }); + } +}; + +template<> +struct SubRangeSorter +{ + static void sortSubRange(CommandIt begin, const CommandIt end) + { + // First we sort by shader + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_glShader > b.m_glShader; + }); + } +}; + +template<> +struct SubRangeSorter +{ + static void sortSubRange(CommandIt begin, const CommandIt end) + { + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + return a.m_depth < b.m_depth; + }); + } +}; + +template<> +struct SubRangeSorter +{ + static void sortSubRange(CommandIt begin, const CommandIt end) + { + std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { + QVector texturesA = a.m_parameterPack.textures(); + QVector texturesB = b.m_parameterPack.textures(); + + const int originalTextureASize = texturesA.size(); + + if (texturesB.size() > texturesA.size()) + qSwap(texturesA, texturesB); + + int identicalTextureCount = 0; + + for (const ShaderParameterPack::NamedResource &texB : qAsConst(texturesB)) { + if (texturesA.contains(texB)) + ++identicalTextureCount; + } + + return identicalTextureCount < originalTextureASize; + }); + } +}; + +int findSubRange(const QVector &commands, + const int begin, const int end, + const QSortPolicy::SortType sortType) +{ + switch (sortType) { + case QSortPolicy::StateChangeCost: + return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + case QSortPolicy::BackToFront: + return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + case QSortPolicy::Material: + return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + case QSortPolicy::FrontToBack: + return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + case QSortPolicy::Texture: + return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + case QSortPolicy::Uniform: + return end; + default: + Q_UNREACHABLE(); + return end; + } +} + +void sortByMaterial(QVector &commands, int begin, const int end) +{ + // We try to arrange elements so that their rendering cost is minimized for a given shader + int rangeEnd = advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + while (begin != end) { + if (begin + 1 < rangeEnd) { + std::stable_sort(commands.begin() + begin + 1, commands.begin() + rangeEnd, [] (const RenderCommand &a, const RenderCommand &b){ + return a.m_material.handle() < b.m_material.handle(); + }); + } + begin = rangeEnd; + rangeEnd = advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); + } +} + +void sortCommandRange(QVector &commands, int begin, const int end, const int level, + const QVector &sortingTypes) +{ + if (level >= sortingTypes.size()) + return; + + switch (sortingTypes.at(level)) { + case QSortPolicy::StateChangeCost: + SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); + break; + case QSortPolicy::BackToFront: + SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); + break; + case QSortPolicy::Material: + // Groups all same shader DNA together + SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); + // Group all same material together (same parameters most likely) + sortByMaterial(commands, begin, end); + break; + case QSortPolicy::FrontToBack: + SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); + break; + case QSortPolicy::Texture: + SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); + break; + case QSortPolicy::Uniform: + break; + default: + Q_UNREACHABLE(); + } + + // For all sub ranges of adjacent item for sortType[i] + // Perform filtering with sortType[i + 1] + int rangeEnd = findSubRange(commands, begin, end, sortingTypes.at(level)); + while (begin != end) { + sortCommandRange(commands, begin, rangeEnd, level + 1, sortingTypes); + begin = rangeEnd; + rangeEnd = findSubRange(commands, begin, end, sortingTypes.at(level)); + } +} + +} // anonymous + +void RenderView::sort() +{ + // Compares the bitsetKey of the RenderCommands + // Key[Depth | StateCost | Shader] + sortCommandRange(m_commands, 0, m_commands.size(), 0, m_data.m_sortingTypes); + + // For RenderCommand with the same shader + // We compute the adjacent change cost + + // Only perform uniform minimization if we explicitly asked for it + if (!m_data.m_sortingTypes.contains(QSortPolicy::Uniform)) + return; + + // Minimize uniform changes + int i = 0; + const int commandSize = m_commands.size(); + while (i < commandSize) { + int j = i; + + // Advance while commands share the same shader + while (i < commandSize && + m_commands[j].m_glShader == m_commands[i].m_glShader) + ++i; + + if (i - j > 0) { // Several commands have the same shader, so we minimize uniform changes + PackUniformHash cachedUniforms = m_commands[j++].m_parameterPack.uniforms(); + + while (j < i) { + // We need the reference here as we are modifying the original container + // not the copy + PackUniformHash &uniforms = m_commands[j].m_parameterPack.m_uniforms; + + for (int u = 0; u < uniforms.keys.size();) { + // We are comparing the values: + // - raw uniform values + // - the texture Node id if the uniform represents a texture + // since all textures are assigned texture units before the RenderCommands + // sharing the same material (shader) are rendered, we can't have the case + // where two uniforms, referencing the same texture eventually have 2 different + // texture unit values + const int uniformNameId = uniforms.keys.at(u); + const UniformValue &refValue = cachedUniforms.value(uniformNameId); + const UniformValue &newValue = uniforms.values.at(u); + if (newValue == refValue) { + uniforms.erase(u); + } else { + // Record updated value so that subsequent comparison + // for the next command will be made againts latest + // uniform value + cachedUniforms.insert(uniformNameId, newValue); + ++u; + } + } + ++j; + } + } + } +} + +void RenderView::setRenderer(Renderer *renderer) +{ + m_renderer = renderer; + m_manager = renderer->nodeManagers(); +} + +void RenderView::addClearBuffers(const ClearBuffers *cb) { + QClearBuffers::BufferTypeFlags type = cb->type(); + + if (type & QClearBuffers::StencilBuffer) { + m_clearStencilValue = cb->clearStencilValue(); + m_clearBuffer |= QClearBuffers::StencilBuffer; + } + if (type & QClearBuffers::DepthBuffer) { + m_clearDepthValue = cb->clearDepthValue(); + m_clearBuffer |= QClearBuffers::DepthBuffer; + } + // keep track of global ClearColor (if set) and collect all DrawBuffer-specific + // ClearColors + if (type & QClearBuffers::ColorBuffer) { + ClearBufferInfo clearBufferInfo; + clearBufferInfo.clearColor = cb->clearColor(); + + if (cb->clearsAllColorBuffers()) { + m_globalClearColorBuffer = clearBufferInfo; + m_clearBuffer |= QClearBuffers::ColorBuffer; + } else { + if (cb->bufferId()) { + const RenderTargetOutput *targetOutput = m_manager->attachmentManager()->lookupResource(cb->bufferId()); + if (targetOutput) { + clearBufferInfo.attchmentPoint = targetOutput->point(); + // Note: a job is later performed to find the drawIndex from the buffer attachment point + // using the AttachmentPack + m_specificClearColorBuffers.push_back(clearBufferInfo); + } + } + } + } +} + +// If we are there, we know that entity had a GeometryRenderer + Material +EntityRenderCommandData RenderView::buildDrawRenderCommands(const QVector &entities, + int offset, int count) const +{ + GLShaderManager *glShaderManager = m_renderer->glResourceManagers()->glShaderManager(); + EntityRenderCommandData commands; + + commands.reserve(count); + + for (int i = 0; i < count; ++i) { + const int idx = offset + i; + Entity *entity = entities.at(idx); + GeometryRenderer *geometryRenderer = nullptr; + HGeometryRenderer geometryRendererHandle = entity->componentHandle(); + + // There is a geometry renderer with geometry + if ((geometryRenderer = m_manager->geometryRendererManager()->data(geometryRendererHandle)) != nullptr + && geometryRenderer->isEnabled() + && !geometryRenderer->geometryId().isNull()) { + + const Qt3DCore::QNodeId materialComponentId = entity->componentUuid(); + const HMaterial materialHandle = entity->componentHandle(); + const QVector renderPassData = m_parameters.value(materialComponentId); + + HGeometry geometryHandle = m_manager->geometryManager()->lookupHandle(geometryRenderer->geometryId()); + Geometry *geometry = m_manager->geometryManager()->data(geometryHandle); + + // 1 RenderCommand per RenderPass pass on an Entity with a Mesh + for (const RenderPassParameterData &passData : renderPassData) { + // Add the RenderPass Parameters + RenderCommand command = {}; + command.m_geometryRenderer = geometryRendererHandle; + command.m_geometry = geometryHandle; + + command.m_material = materialHandle; + // For RenderPass based states we use the globally set RenderState + // if no renderstates are defined as part of the pass. That means: + // RenderPass { renderStates: [] } will use the states defined by + // StateSet in the FrameGraph + RenderPass *pass = passData.pass; + if (pass->hasRenderStates()) { + command.m_stateSet = RenderStateSetPtr::create(); + addStatesToRenderStateSet(command.m_stateSet.data(), pass->renderStates(), m_manager->renderStateManager()); + if (m_stateSet != nullptr) + command.m_stateSet->merge(m_stateSet); + command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); + } + command.m_shaderId = pass->shaderProgram(); + command.m_glShader = glShaderManager->lookupResource(command.m_shaderId); + + // It takes two frames to have a valid command as we can only + // reference a glShader at frame n if it has been loaded at frame n - 1 + if (!command.m_glShader) + continue; + + { // Scoped to show extent + + // Update the draw command with what's going to be needed for the drawing + int primitiveCount = geometryRenderer->vertexCount(); + int estimatedCount = 0; + Attribute *indexAttribute = nullptr; + Attribute *indirectAttribute = nullptr; + + const QVector attributeIds = geometry->attributes(); + for (Qt3DCore::QNodeId attributeId : attributeIds) { + Attribute *attribute = m_manager->attributeManager()->lookupResource(attributeId); + switch (attribute->attributeType()) { + case QAttribute::IndexAttribute: + indexAttribute = attribute; + break; + case QAttribute::DrawIndirectAttribute: + indirectAttribute = attribute; + break; + case QAttribute::VertexAttribute: + estimatedCount = std::max(int(attribute->count()), estimatedCount); + break; + default: + Q_UNREACHABLE(); + break; + } + } + + command.m_drawIndexed = (indexAttribute != nullptr); + command.m_drawIndirect = (indirectAttribute != nullptr); + + // Update the draw command with all the information required for the drawing + if (command.m_drawIndexed) { + command.m_indexAttributeDataType = GraphicsContext::glDataTypeFromAttributeDataType(indexAttribute->vertexBaseType()); + command.m_indexAttributeByteOffset = indexAttribute->byteOffset() + geometryRenderer->indexBufferByteOffset(); + } + + // Note: we only care about the primitiveCount when using direct draw calls + // For indirect draw calls it is assumed the buffer was properly set already + if (command.m_drawIndirect) { + command.m_indirectAttributeByteOffset = indirectAttribute->byteOffset(); + command.m_indirectDrawBuffer = m_manager->bufferManager()->lookupHandle(indirectAttribute->bufferId()); + } else { + // Use the count specified by the GeometryRender + // If not specify use the indexAttribute count if present + // Otherwise tries to use the count from the attribute with the highest count + if (primitiveCount == 0) { + if (indexAttribute) + primitiveCount = indexAttribute->count(); + else + primitiveCount = estimatedCount; + } + } + + command.m_primitiveCount = primitiveCount; + command.m_primitiveType = geometryRenderer->primitiveType(); + command.m_primitiveRestartEnabled = geometryRenderer->primitiveRestartEnabled(); + command.m_restartIndexValue = geometryRenderer->restartIndexValue(); + command.m_firstInstance = geometryRenderer->firstInstance(); + command.m_instanceCount = geometryRenderer->instanceCount(); + command.m_firstVertex = geometryRenderer->firstVertex(); + command.m_indexOffset = geometryRenderer->indexOffset(); + command.m_verticesPerPatch = geometryRenderer->verticesPerPatch(); + } // scope + + + commands.push_back(entity, + std::move(command), + std::move(passData)); + } + } + } + + return commands; +} + +EntityRenderCommandData RenderView::buildComputeRenderCommands(const QVector &entities, + int offset, int count) const +{ + // If the RenderView contains only a ComputeDispatch then it cares about + // A ComputeDispatch is also implicitely a NoDraw operation + // enabled flag + // layer component + // material/effect/technique/parameters/filters/ + EntityRenderCommandData commands; + GLShaderManager *glShaderManager = m_renderer->glResourceManagers()->glShaderManager(); + + commands.reserve(count); + + for (int i = 0; i < count; ++i) { + const int idx = offset + i; + Entity *entity = entities.at(idx); + ComputeCommand *computeJob = nullptr; + HComputeCommand computeCommandHandle = entity->componentHandle(); + if ((computeJob = nodeManagers()->computeJobManager()->data(computeCommandHandle)) != nullptr + && computeJob->isEnabled()) { + + const Qt3DCore::QNodeId materialComponentId = entity->componentUuid(); + const QVector renderPassData = m_parameters.value(materialComponentId); + + // 1 RenderCommand per RenderPass pass on an Entity with a Mesh + for (const RenderPassParameterData &passData : renderPassData) { + // Add the RenderPass Parameters + RenderCommand command = {}; + RenderPass *pass = passData.pass; + + if (pass->hasRenderStates()) { + command.m_stateSet = RenderStateSetPtr::create(); + addStatesToRenderStateSet(command.m_stateSet.data(), pass->renderStates(), m_manager->renderStateManager()); + + // Merge per pass stateset with global stateset + // so that the local stateset only overrides + if (m_stateSet != nullptr) + command.m_stateSet->merge(m_stateSet); + command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); + } + command.m_shaderId = pass->shaderProgram(); + command.m_glShader = glShaderManager->lookupResource(command.m_shaderId); + + // It takes two frames to have a valid command as we can only + // reference a glShader at frame n if it has been loaded at frame n - 1 + if (!command.m_glShader) + continue; + + command.m_computeCommand = computeCommandHandle; + command.m_type = RenderCommand::Compute; + command.m_workGroups[0] = std::max(m_workGroups[0], computeJob->x()); + command.m_workGroups[1] = std::max(m_workGroups[1], computeJob->y()); + command.m_workGroups[2] = std::max(m_workGroups[2], computeJob->z()); + + commands.push_back(entity, + std::move(command), + std::move(passData)); + } + } + } + + return commands; +} + +void RenderView::updateRenderCommand(EntityRenderCommandData *renderCommandData, + int offset, + int count) +{ + // Note: since many threads can be building render commands + // we need to ensure that the UniformBlockValueBuilder they are using + // is only accessed from the same thread + UniformBlockValueBuilder *builder = new UniformBlockValueBuilder(); + builder->shaderDataManager = m_manager->shaderDataManager(); + builder->textureManager = m_manager->textureManager(); + m_localData.setLocalData(builder); + + for (int i = 0, m = count; i < m; ++i) { + const int idx = offset + i; + Entity *entity = renderCommandData->entities.at(idx); + const RenderPassParameterData passData = renderCommandData->passesData.at(idx); + RenderCommand &command = renderCommandData->commands[idx]; + + // Pick which lights to take in to account. + // For now decide based on the distance by taking the MAX_LIGHTS closest lights. + // Replace with more sophisticated mechanisms later. + // Copy vector so that we can sort it concurrently and we only want to sort the one for the current command + QVector lightSources; + EnvironmentLight *environmentLight = nullptr; + + if (command.m_type == RenderCommand::Draw) { + // Project the camera-to-object-center vector onto the camera + // view vector. This gives a depth value suitable as the key + // for BackToFront sorting. + command.m_depth = Vector3D::dotProduct(entity->worldBoundingVolume()->center() - m_data.m_eyePos, m_data.m_eyeViewDir); + + environmentLight = m_environmentLight; + lightSources = m_lightSources; + + if (lightSources.size() > 1) { + const Vector3D entityCenter = entity->worldBoundingVolume()->center(); + std::sort(lightSources.begin(), lightSources.end(), + [&] (const LightSource &a, const LightSource &b) { + const float distA = entityCenter.distanceToPoint(a.entity->worldBoundingVolume()->center()); + const float distB = entityCenter.distanceToPoint(b.entity->worldBoundingVolume()->center()); + return distA < distB; + }); + } + lightSources = lightSources.mid(0, std::max(lightSources.size(), MAX_LIGHTS)); + } else { // Compute + // Note: if frameCount has reached 0 in the previous frame, isEnabled + // would be false + ComputeCommand *computeJob = m_manager->computeJobManager()->data(command.m_computeCommand); + if (computeJob->runType() == QComputeCommand::Manual) + computeJob->updateFrameCount(); + } + + ParameterInfoList globalParameters = passData.parameterInfo; + // setShaderAndUniforms can initialize a localData + // make sure this is cleared before we leave this function + + setShaderAndUniforms(&command, + globalParameters, + entity, + lightSources, + environmentLight); + } + + // We reset the local data once we are done with it + m_localData.setLocalData(nullptr); +} + +void RenderView::updateMatrices() +{ + if (m_data.m_renderCameraNode && m_data.m_renderCameraLens && m_data.m_renderCameraLens->isEnabled()) { + const Matrix4x4 cameraWorld = *(m_data.m_renderCameraNode->worldTransform()); + setViewMatrix(m_data.m_renderCameraLens->viewMatrix(cameraWorld)); + + setViewProjectionMatrix(m_data.m_renderCameraLens->projection() * viewMatrix()); + //To get the eyePosition of the camera, we need to use the inverse of the + //camera's worldTransform matrix. + const Matrix4x4 inverseWorldTransform = viewMatrix().inverted(); + const Vector3D eyePosition(inverseWorldTransform.column(3)); + setEyePosition(eyePosition); + + // Get the viewing direction of the camera. Use the normal matrix to + // ensure non-uniform scale works too. + const QMatrix3x3 normalMat = convertToQMatrix4x4(m_data.m_viewMatrix).normalMatrix(); + // dir = normalize(QVector3D(0, 0, -1) * normalMat) + setEyeViewDirection(Vector3D(-normalMat(2, 0), -normalMat(2, 1), -normalMat(2, 2)).normalized()); + } +} + +void RenderView::setUniformValue(ShaderParameterPack &uniformPack, int nameId, const UniformValue &value) const +{ + // At this point a uniform value can only be a scalar type + // or a Qt3DCore::QNodeId corresponding to a Texture or Image + // ShaderData/Buffers would be handled as UBO/SSBO and would therefore + // not be in the default uniform block + if (value.valueType() == UniformValue::NodeId) { + const Qt3DCore::QNodeId *nodeIds = value.constData(); + + const int uniformArraySize = value.byteSize() / sizeof(Qt3DCore::QNodeId); + UniformValue::ValueType resourceType = UniformValue::TextureValue; + + for (int i = 0; i < uniformArraySize; ++i) { + const Qt3DCore::QNodeId resourceId = nodeIds[i]; + + const Texture *tex = m_manager->textureManager()->lookupResource(resourceId); + if (tex != nullptr) { + uniformPack.setTexture(nameId, i, resourceId); + } else { + const ShaderImage *img = m_manager->shaderImageManager()->lookupResource(resourceId); + if (img != nullptr) { + resourceType = UniformValue::ShaderImageValue; + uniformPack.setImage(nameId, i, resourceId); + } + } + } + + // This uniform will be overridden in SubmissionContext::setParameters + // and -1 values will be replaced by valid Texture or Image units + UniformValue uniformValue(uniformArraySize * sizeof(int), resourceType); + std::fill(uniformValue.data(), uniformValue.data() + uniformArraySize, -1); + uniformPack.setUniform(nameId, uniformValue); + } else { + uniformPack.setUniform(nameId, value); + } +} + +void RenderView::setStandardUniformValue(ShaderParameterPack &uniformPack, + int glslNameId, + int nameId, + Entity *entity, + const Matrix4x4 &worldTransform) const +{ + uniformPack.setUniform(glslNameId, standardUniformValue(ms_standardUniformSetters[nameId], entity, worldTransform)); +} + +void RenderView::setUniformBlockValue(ShaderParameterPack &uniformPack, + GLShader *shader, + const ShaderUniformBlock &block, + const UniformValue &value) const +{ + Q_UNUSED(shader) + + if (value.valueType() == UniformValue::NodeId) { + + Buffer *buffer = nullptr; + if ((buffer = m_manager->bufferManager()->lookupResource(*value.constData())) != nullptr) { + BlockToUBO uniformBlockUBO; + uniformBlockUBO.m_blockIndex = block.m_index; + uniformBlockUBO.m_bufferID = buffer->peerId(); + uniformBlockUBO.m_needsUpdate = false; + uniformPack.setUniformBuffer(std::move(uniformBlockUBO)); + // Buffer update to GL buffer will be done at render time + } + } +} + +void RenderView::setShaderStorageValue(ShaderParameterPack &uniformPack, + GLShader *shader, + const ShaderStorageBlock &block, + const UniformValue &value) const +{ + Q_UNUSED(shader) + if (value.valueType() == UniformValue::NodeId) { + Buffer *buffer = nullptr; + if ((buffer = m_manager->bufferManager()->lookupResource(*value.constData())) != nullptr) { + BlockToSSBO shaderStorageBlock; + shaderStorageBlock.m_blockIndex = block.m_index; + shaderStorageBlock.m_bufferID = buffer->peerId(); + shaderStorageBlock.m_bindingIndex = block.m_binding; + uniformPack.setShaderStorageBuffer(shaderStorageBlock); + // Buffer update to GL buffer will be done at render time + } + } +} + +void RenderView::setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, GLShader *shader, ShaderData *shaderData, const QString &structName) const +{ + UniformBlockValueBuilder *builder = m_localData.localData(); + builder->activeUniformNamesToValue.clear(); + + // Set the view matrix to be used to transform "Transformed" properties in the ShaderData + builder->viewMatrix = m_data.m_viewMatrix; + // Force to update the whole block + builder->updatedPropertiesOnly = false; + // Retrieve names and description of each active uniforms in the uniform block + builder->uniforms = shader->activeUniformsForUniformBlock(-1); + // Build name-value map for the block + builder->buildActiveUniformNameValueMapStructHelper(shaderData, structName); + // Set uniform values for each entrie of the block name-value map + QHash::const_iterator activeValuesIt = builder->activeUniformNamesToValue.constBegin(); + const QHash::const_iterator activeValuesEnd = builder->activeUniformNamesToValue.constEnd(); + + // TO DO: Make the ShaderData store UniformValue + while (activeValuesIt != activeValuesEnd) { + setUniformValue(uniformPack, activeValuesIt.key(), UniformValue::fromVariant(activeValuesIt.value())); + ++activeValuesIt; + } +} + +void RenderView::setShaderAndUniforms(RenderCommand *command, + ParameterInfoList ¶meters, + Entity *entity, + const QVector &activeLightSources, + EnvironmentLight *environmentLight) const +{ + // The VAO Handle is set directly in the renderer thread so as to avoid having to use a mutex here + // Set shader, technique, and effect by basically doing : + // ShaderProgramManager[MaterialManager[frontentEntity->id()]->Effect->Techniques[TechniqueFilter->name]->RenderPasses[RenderPassFilter->name]]; + // The Renderer knows that if one of those is null, a default material / technique / effect as to be used + + // Find all RenderPasses (in order) matching values set in the RenderPassFilter + // Get list of parameters for the Material, Effect, and Technique + // For each ParameterBinder in the RenderPass -> create a QUniformPack + // Once that works, improve that to try and minimize QUniformPack updates + + GLShader *shader = command->m_glShader; + if (shader != nullptr && shader->isLoaded()) { + + // Builds the QUniformPack, sets shader standard uniforms and store attributes name / glname bindings + // If a parameter is defined and not found in the bindings it is assumed to be a binding of Uniform type with the glsl name + // equals to the parameter name + const QVector uniformNamesIds = shader->uniformsNamesIds(); + const QVector standardUniformNamesIds = shader->standardUniformNameIds(); + const QVector uniformBlockNamesIds = shader->uniformBlockNamesIds(); + const QVector shaderStorageBlockNamesIds = shader->storageBlockNamesIds(); + const QVector attributeNamesIds = shader->attributeNamesIds(); + + // Set fragData Name and index + // Later on we might want to relink the shader if attachments have changed + // But for now we set them once and for all + if (!m_renderTarget.isNull() && !shader->isLoaded()) { + QHash fragOutputs; + const auto atts = m_attachmentPack.attachments(); + for (const Attachment &att : atts) { + if (att.m_point <= QRenderTargetOutput::Color15) + fragOutputs.insert(att.m_name, att.m_point); + } + // Set frag outputs in the shaders if hash not empty + if (!fragOutputs.isEmpty()) + shader->setFragOutputs(fragOutputs); + } + + if (!uniformNamesIds.isEmpty() || !standardUniformNamesIds.isEmpty() || + !attributeNamesIds.isEmpty() || + !shaderStorageBlockNamesIds.isEmpty() || !attributeNamesIds.isEmpty()) { + + // Set default standard uniforms without bindings + const Matrix4x4 worldTransform = *(entity->worldTransform()); + + for (const int uniformNameId : standardUniformNamesIds) + setStandardUniformValue(command->m_parameterPack, uniformNameId, uniformNameId, entity, worldTransform); + + // Set default attributes + command->m_activeAttributes = attributeNamesIds; + + // At this point we know whether the command is a valid draw command or not + // We still need to process the uniforms as the command could be a compute command + command->m_isValid = !command->m_activeAttributes.empty(); + + // Parameters remaining could be + // -> uniform scalar / vector + // -> uniform struct / arrays + // -> uniform block / array (4.3) + // -> ssbo block / array (4.3) + + ParameterInfoList::const_iterator it = parameters.cbegin(); + const ParameterInfoList::const_iterator parametersEnd = parameters.cend(); + + while (it != parametersEnd) { + Parameter *param = m_manager->data(it->handle); + const UniformValue &uniformValue = param->uniformValue(); + if (uniformNamesIds.contains(it->nameId)) { // Parameter is a regular uniform + setUniformValue(command->m_parameterPack, it->nameId, uniformValue); + } else if (uniformBlockNamesIds.indexOf(it->nameId) != -1) { // Parameter is a uniform block + setUniformBlockValue(command->m_parameterPack, shader, shader->uniformBlockForBlockNameId(it->nameId), uniformValue); + } else if (shaderStorageBlockNamesIds.indexOf(it->nameId) != -1) { // Parameters is a SSBO + setShaderStorageValue(command->m_parameterPack, shader, shader->storageBlockForBlockNameId(it->nameId), uniformValue); + } else { // Parameter is a struct + ShaderData *shaderData = nullptr; + if (uniformValue.valueType() == UniformValue::NodeId && + (shaderData = m_manager->shaderDataManager()->lookupResource(*uniformValue.constData())) != nullptr) { + // Try to check if we have a struct or array matching a QShaderData parameter + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, StringToInt::lookupString(it->nameId)); + } + // Otherwise: param unused by current shader + } + ++it; + } + + // Lights + + int lightIdx = 0; + for (const LightSource &lightSource : activeLightSources) { + if (lightIdx == MAX_LIGHTS) + break; + Entity *lightEntity = lightSource.entity; + const Matrix4x4 lightWorldTransform = *(lightEntity->worldTransform()); + const Vector3D worldPos = lightWorldTransform * Vector3D(0.0f, 0.0f, 0.0f); + for (Light *light : lightSource.lights) { + if (!light->isEnabled()) + continue; + + ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(light->shaderData()); + if (!shaderData) + continue; + + if (lightIdx == MAX_LIGHTS) + break; + + // Note: implicit conversion of values to UniformValue + setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[lightIdx], worldPos); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[lightIdx], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[lightIdx], 0.5f); + + setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[lightIdx], worldPos); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[lightIdx], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[lightIdx], 0.5f); + + + // There is no risk in doing that even if multithreaded + // since we are sure that a shaderData is unique for a given light + // and won't ever be referenced as a Component either + Matrix4x4 *worldTransform = lightEntity->worldTransform(); + if (worldTransform) + shaderData->updateWorldTransform(*worldTransform); + + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_NAMES[lightIdx]); + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_UNROLL_NAMES[lightIdx]); + ++lightIdx; + } + } + + if (uniformNamesIds.contains(LIGHT_COUNT_NAME_ID)) + setUniformValue(command->m_parameterPack, LIGHT_COUNT_NAME_ID, UniformValue(qMax((environmentLight ? 0 : 1), lightIdx))); + + // If no active light sources and no environment light, add a default light + if (activeLightSources.isEmpty() && !environmentLight) { + // Note: implicit conversion of values to UniformValue + setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[0], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[0], 0.5f); + + setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); + setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[0], int(QAbstractLight::PointLight)); + setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); + setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[0], 0.5f); + } + + // Environment Light + int envLightCount = 0; + if (environmentLight && environmentLight->isEnabled()) { + ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(environmentLight->shaderData()); + if (shaderData) { + setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, QStringLiteral("envLight")); + envLightCount = 1; + } + } else { + // with some drivers, samplers (like the envbox sampler) need to be bound even though + // they may not be actually used, otherwise draw calls can fail + static const int irradianceId = StringToInt::lookupId(QLatin1String("envLight.irradiance")); + static const int specularId = StringToInt::lookupId(QLatin1String("envLight.specular")); + setUniformValue(command->m_parameterPack, irradianceId, m_renderer->submissionContext()->maxTextureUnitsCount()); + setUniformValue(command->m_parameterPack, specularId, m_renderer->submissionContext()->maxTextureUnitsCount()); + } + setUniformValue(command->m_parameterPack, StringToInt::lookupId(QStringLiteral("envLightCount")), envLightCount); + } + } +} + +bool RenderView::hasBlitFramebufferInfo() const +{ + return m_hasBlitFramebufferInfo; +} + +void RenderView::setHasBlitFramebufferInfo(bool hasBlitFramebufferInfo) +{ + m_hasBlitFramebufferInfo = hasBlitFramebufferInfo; +} + +BlitFramebufferInfo RenderView::blitFrameBufferInfo() const +{ + return m_blitFrameBufferInfo; +} + +void RenderView::setBlitFrameBufferInfo(const BlitFramebufferInfo &blitFrameBufferInfo) +{ + m_blitFrameBufferInfo = blitFrameBufferInfo; +} + +bool RenderView::isDownloadBuffersEnable() const +{ + return m_isDownloadBuffersEnable; +} + +void RenderView::setIsDownloadBuffersEnable(bool isDownloadBuffersEnable) +{ + m_isDownloadBuffersEnable = isDownloadBuffersEnable; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/renderview_p.h b/src/plugins/renderers/opengl/renderer/renderview_p.h new file mode 100644 index 000000000..78c40d80c --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderview_p.h @@ -0,0 +1,397 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEW_H +#define QT3DRENDER_RENDER_RENDERVIEW_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +// TODO: Move out once this is all refactored +#include + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class QRenderPass; + +namespace Render { + +class Renderer; +class NodeManagers; +class RenderCommand; +class RenderPassFilter; +class TechniqueFilter; +class ViewportNode; +class Effect; +class RenderPass; + +typedef QPair ActivePropertyContent; +typedef QPair ActiveProperty; + +struct Q_AUTOTEST_EXPORT ClearBufferInfo +{ + int drawBufferIndex = 0; + QRenderTargetOutput::AttachmentPoint attchmentPoint = QRenderTargetOutput::Color0; + QVector4D clearColor; +}; + +struct Q_AUTOTEST_EXPORT BlitFramebufferInfo +{ + Qt3DCore::QNodeId sourceRenderTargetId; + Qt3DCore::QNodeId destinationRenderTargetId; + QRect sourceRect; + QRect destinationRect; + Qt3DRender::QRenderTargetOutput::AttachmentPoint sourceAttachmentPoint; + Qt3DRender::QRenderTargetOutput::AttachmentPoint destinationAttachmentPoint; + QBlitFramebuffer::InterpolationMethod interpolationMethod; +}; + +// This class is kind of analogous to RenderBin but I want to avoid trampling +// on that until we get this working + +class Q_AUTOTEST_EXPORT RenderView +{ +public: + RenderView(); + ~RenderView(); + + QT3D_ALIGNED_MALLOC_AND_FREE() + + // TODO: Add a way to specify a sort predicate for the RenderCommands + void sort(); + + void setRenderer(Renderer *renderer); + inline void setSurfaceSize(const QSize &size) Q_DECL_NOTHROW { m_surfaceSize = size; } + inline Renderer *renderer() const Q_DECL_NOTHROW { return m_renderer; } + inline NodeManagers *nodeManagers() const Q_DECL_NOTHROW { return m_manager; } + inline const QSize &surfaceSize() const Q_DECL_NOTHROW { return m_surfaceSize; } + inline void setDevicePixelRatio(qreal r) Q_DECL_NOTHROW { m_devicePixelRatio = r; } + inline qreal devicePixelRatio() const Q_DECL_NOTHROW { return m_devicePixelRatio; } + + inline void setRenderCameraLens(CameraLens *renderCameraLens) Q_DECL_NOTHROW { m_data.m_renderCameraLens = renderCameraLens; } + inline CameraLens *renderCameraLens() const Q_DECL_NOTHROW { return m_data.m_renderCameraLens; } + + inline void setRenderCameraEntity(Entity *renderCameraNode) Q_DECL_NOTHROW { m_data.m_renderCameraNode = renderCameraNode; } + inline Entity *renderCameraEntity() const Q_DECL_NOTHROW { return m_data.m_renderCameraNode; } + + inline void setViewMatrix(const Matrix4x4 &viewMatrix) Q_DECL_NOTHROW { m_data.m_viewMatrix = viewMatrix; } + inline Matrix4x4 viewMatrix() const Q_DECL_NOTHROW { return m_data.m_viewMatrix; } + + inline void setViewProjectionMatrix(const Matrix4x4 &viewProjectionMatrix) Q_DECL_NOTHROW { m_data.m_viewProjectionMatrix = viewProjectionMatrix; } + inline Matrix4x4 viewProjectionMatrix() const Q_DECL_NOTHROW { return m_data.m_viewProjectionMatrix; } + + inline void setEyePosition(const Vector3D &eyePos) Q_DECL_NOTHROW { m_data.m_eyePos = eyePos; } + inline Vector3D eyePosition() const Q_DECL_NOTHROW { return m_data.m_eyePos; } + + inline void setEyeViewDirection(const Vector3D &dir) Q_DECL_NOTHROW { m_data.m_eyeViewDir = dir; } + inline Vector3D eyeViewDirection() const Q_DECL_NOTHROW { return m_data.m_eyeViewDir; } + + inline void appendLayerFilter(const Qt3DCore::QNodeId layerFilterId) Q_DECL_NOTHROW { m_data.m_layerFilterIds.push_back(layerFilterId); } + inline Qt3DCore::QNodeIdVector layerFilters() const Q_DECL_NOTHROW { return m_data.m_layerFilterIds; } + + inline void appendProximityFilterId(const Qt3DCore::QNodeId proximityFilterId) { m_data.m_proximityFilterIds.push_back(proximityFilterId); } + inline Qt3DCore::QNodeIdVector proximityFilterIds() const { return m_data.m_proximityFilterIds; } + + inline void appendInsertFenceId(const Qt3DCore::QNodeId setFenceId) { m_insertFenceIds.push_back(setFenceId); } + // We prefix with get to avoid confusion when it is called + inline Qt3DCore::QNodeIdVector insertFenceIds() const { return m_insertFenceIds; } + + inline void appendWaitFence(const QWaitFenceData &data) { m_waitFences.push_back(data); } + inline QVector waitFences() const { return m_waitFences; } + + inline void setRenderPassFilter(const RenderPassFilter *rpFilter) Q_DECL_NOTHROW { m_data.m_passFilter = rpFilter; } + inline const RenderPassFilter *renderPassFilter() const Q_DECL_NOTHROW { return m_data.m_passFilter; } + + inline void setTechniqueFilter(const TechniqueFilter *filter) Q_DECL_NOTHROW { m_data.m_techniqueFilter = filter; } + inline const TechniqueFilter *techniqueFilter() const Q_DECL_NOTHROW { return m_data.m_techniqueFilter; } + + inline RenderStateSet *stateSet() const Q_DECL_NOTHROW { return m_stateSet; } + void setStateSet(RenderStateSet *stateSet) Q_DECL_NOTHROW { m_stateSet = stateSet; } + + inline bool noDraw() const Q_DECL_NOTHROW { return m_noDraw; } + void setNoDraw(bool noDraw) Q_DECL_NOTHROW { m_noDraw = noDraw; } + + inline bool isCompute() const Q_DECL_NOTHROW { return m_compute; } + void setCompute(bool compute) Q_DECL_NOTHROW { m_compute = compute; } + + void setComputeWorkgroups(int x, int y, int z) Q_DECL_NOTHROW { m_workGroups[0] = x; m_workGroups[1] = y; m_workGroups[2] = z; } + const int *computeWorkGroups() const Q_DECL_NOTHROW { return m_workGroups; } + inline bool frustumCulling() const Q_DECL_NOTHROW { return m_frustumCulling; } + void setFrustumCulling(bool frustumCulling) Q_DECL_NOTHROW { m_frustumCulling = frustumCulling; } + bool showDebugOverlay() const Q_DECL_NOTHROW { return m_showDebugOverlay; } + void setShowDebugOverlay(bool showDebugOverlay) Q_DECL_NOTHROW { m_showDebugOverlay = showDebugOverlay; } + + inline void setMaterialParameterTable(const MaterialParameterGathererData ¶meters) Q_DECL_NOTHROW { m_parameters = parameters; } + + // TODO: Get rid of this overly complex memory management by splitting out the + // InnerData as a RenderViewConfig struct. This can be created by setRenderViewConfigFromFrameGraphLeafNode + // and passed along with the RenderView to the functions that populate the renderview + inline void setViewport(const QRectF &vp) Q_DECL_NOTHROW { m_viewport = vp; } + inline QRectF viewport() const Q_DECL_NOTHROW { return m_viewport; } + + inline float gamma() const Q_DECL_NOTHROW { return m_gamma; } + inline void setGamma(float gamma) Q_DECL_NOTHROW { m_gamma = gamma; } + + // depth and stencil ClearBuffers are cached locally + // color ClearBuffers are collected, as there may be multiple + // color buffers to be cleared. we need to apply all these at rendering + void addClearBuffers(const ClearBuffers *cb); + inline QVector specificClearColorBufferInfo() const { return m_specificClearColorBuffers; } + inline QVector &specificClearColorBufferInfo() { return m_specificClearColorBuffers; } + inline ClearBufferInfo globalClearColorBufferInfo() const { return m_globalClearColorBuffer; } + + inline QClearBuffers::BufferTypeFlags clearTypes() const { return m_clearBuffer; } + inline float clearDepthValue() const { return m_clearDepthValue; } + inline int clearStencilValue() const { return m_clearStencilValue; } + + RenderPassList passesAndParameters(ParameterInfoList *parameter, Entity *node, bool useDefaultMaterials = true); + + EntityRenderCommandData buildDrawRenderCommands(const QVector &entities, + int offset, int count) const; + EntityRenderCommandData buildComputeRenderCommands(const QVector &entities, + int offset, int count) const; + + + void updateRenderCommand(EntityRenderCommandData *renderCommandData, + int offset, int count); + + + void setCommands(const QVector &commands) Q_DECL_NOTHROW { m_commands = commands; } + QVector &commands() { return m_commands; } + QVector commands() const { return m_commands; } + + void setAttachmentPack(const AttachmentPack &pack) { m_attachmentPack = pack; } + const AttachmentPack &attachmentPack() const { return m_attachmentPack; } + + void setRenderTargetId(Qt3DCore::QNodeId renderTargetId) Q_DECL_NOTHROW { m_renderTarget = renderTargetId; } + Qt3DCore::QNodeId renderTargetId() const Q_DECL_NOTHROW { return m_renderTarget; } + + void addSortType(const QVector &sortTypes) { m_data.m_sortingTypes.append(sortTypes); } + + void setSurface(QSurface *surface) { m_surface = surface; } + QSurface *surface() const { return m_surface; } + + void setLightSources(const QVector &lightSources) Q_DECL_NOTHROW { m_lightSources = lightSources; } + void setEnvironmentLight(EnvironmentLight *environmentLight) Q_DECL_NOTHROW { m_environmentLight = environmentLight; } + + void updateMatrices(); + + inline void setRenderCaptureNodeId(const Qt3DCore::QNodeId nodeId) Q_DECL_NOTHROW { m_renderCaptureNodeId = nodeId; } + inline const Qt3DCore::QNodeId renderCaptureNodeId() const Q_DECL_NOTHROW { return m_renderCaptureNodeId; } + inline void setRenderCaptureRequest(const QRenderCaptureRequest& request) Q_DECL_NOTHROW { m_renderCaptureRequest = request; } + inline const QRenderCaptureRequest renderCaptureRequest() const Q_DECL_NOTHROW { return m_renderCaptureRequest; } + + void setMemoryBarrier(QMemoryBarrier::Operations barrier) Q_DECL_NOTHROW { m_memoryBarrier = barrier; } + QMemoryBarrier::Operations memoryBarrier() const Q_DECL_NOTHROW { return m_memoryBarrier; } + + // Helps making the size of RenderView smaller + // Contains all the data needed for the actual building of the RenderView + // But that aren't used later by the Renderer + struct InnerData { + InnerData() + : m_renderCameraLens(nullptr) + , m_renderCameraNode(nullptr) + , m_techniqueFilter(nullptr) + , m_passFilter(nullptr) + { + } + CameraLens *m_renderCameraLens; + Entity *m_renderCameraNode; + const TechniqueFilter *m_techniqueFilter; + const RenderPassFilter *m_passFilter; + Matrix4x4 m_viewMatrix; + Matrix4x4 m_viewProjectionMatrix; + Qt3DCore::QNodeIdVector m_layerFilterIds; + QVector m_sortingTypes; + Vector3D m_eyePos; + Vector3D m_eyeViewDir; + Qt3DCore::QNodeIdVector m_proximityFilterIds; + }; + + bool isDownloadBuffersEnable() const; + void setIsDownloadBuffersEnable(bool isDownloadBuffersEnable); + + BlitFramebufferInfo blitFrameBufferInfo() const; + void setBlitFrameBufferInfo(const BlitFramebufferInfo &blitFrameBufferInfo); + + bool hasBlitFramebufferInfo() const; + void setHasBlitFramebufferInfo(bool hasBlitFramebufferInfo); + +private: + void setShaderAndUniforms(RenderCommand *command, + ParameterInfoList ¶meters, + Entity *entity, + const QVector &activeLightSources, + EnvironmentLight *environmentLight) const; + mutable QThreadStorage m_localData; + + Qt3DCore::QNodeId m_renderCaptureNodeId; + QRenderCaptureRequest m_renderCaptureRequest; + bool m_isDownloadBuffersEnable; + + bool m_hasBlitFramebufferInfo; + BlitFramebufferInfo m_blitFrameBufferInfo; + + Renderer *m_renderer; + NodeManagers *m_manager; + QSize m_surfaceSize; + qreal m_devicePixelRatio; + + InnerData m_data; + + QRectF m_viewport; + float m_gamma; + Qt3DCore::QNodeId m_renderTarget; + QSurface *m_surface; + AttachmentPack m_attachmentPack; + QClearBuffers::BufferTypeFlags m_clearBuffer; + float m_clearDepthValue; + int m_clearStencilValue; + ClearBufferInfo m_globalClearColorBuffer; // global ClearColor + QVector m_specificClearColorBuffers; // different draw buffers with distinct colors + RenderStateSet *m_stateSet; + bool m_noDraw:1; + bool m_compute:1; + bool m_frustumCulling:1; + bool m_showDebugOverlay:1; + int m_workGroups[3]; + QMemoryBarrier::Operations m_memoryBarrier; + QVector m_insertFenceIds; + QVector m_waitFences; + + QVector m_commands; + mutable QVector m_lightSources; + EnvironmentLight *m_environmentLight; + + MaterialParameterGathererData m_parameters; + + enum StandardUniform + { + ModelMatrix, + ViewMatrix, + ProjectionMatrix, + ModelViewMatrix, + ViewProjectionMatrix, + ModelViewProjectionMatrix, + InverseModelMatrix, + InverseViewMatrix, + InverseProjectionMatrix, + InverseModelViewMatrix, + InverseViewProjectionMatrix, + InverseModelViewProjectionMatrix, + ModelNormalMatrix, + ModelViewNormalMatrix, + ViewportMatrix, + InverseViewportMatrix, + AspectRatio, + Time, + Exposure, + Gamma, + EyePosition, + SkinningPalette + }; + + typedef QHash StandardUniformsNameToTypeHash; + static StandardUniformsNameToTypeHash ms_standardUniformSetters; + static StandardUniformsNameToTypeHash initializeStandardUniformSetters(); + + UniformValue standardUniformValue(StandardUniform standardUniformType, + Entity *entity, + const Matrix4x4 &model) const; + + void setUniformValue(ShaderParameterPack &uniformPack, int nameId, const UniformValue &value) const; + void setStandardUniformValue(ShaderParameterPack &uniformPack, + int glslNameId, + int nameId, + Entity *entity, + const Matrix4x4 &worldTransform) const; + void setUniformBlockValue(ShaderParameterPack &uniformPack, + GLShader *shader, + const ShaderUniformBlock &block, + const UniformValue &value) const; + void setShaderStorageValue(ShaderParameterPack &uniformPack, + GLShader *shader, + const ShaderStorageBlock &block, + const UniformValue &value) const; + void setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, + GLShader *shader, + ShaderData *shaderData, + const QString &structName) const; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEW_H diff --git a/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp b/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp new file mode 100644 index 000000000..4034af146 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp @@ -0,0 +1,803 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderviewbuilder_p.h" + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +// In some cases having less jobs is better (especially on fast cpus where +// splitting just adds more overhead). Ideally, we should try to set the value +// depending on the platform/CPU/nbr of cores +const int RenderViewBuilder::m_optimalParallelJobCount = QThread::idealThreadCount(); + +namespace { + +int findIdealNumberOfWorkers(int elementCount, int packetSize = 100) +{ + if (elementCount == 0 || packetSize == 0) + return 0; + return std::min(std::max(elementCount / packetSize, 1), RenderViewBuilder::optimalJobCount()); +} + + +class SyncPreCommandBuilding +{ +public: + explicit SyncPreCommandBuilding(RenderViewInitializerJobPtr renderViewInitializerJob, + const QVector &renderViewCommandBuilderJobs, + Renderer *renderer, + FrameGraphNode *leafNode) + : m_renderViewInitializer(renderViewInitializerJob) + , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) + , m_renderer(renderer) + , m_leafNode(leafNode) + { + } + + void operator()() + { + // Split commands to build among jobs + QMutexLocker lock(m_renderer->cache()->mutex()); + // Rebuild RenderCommands for all entities in RV (ignoring filtering) + RendererCache *cache = m_renderer->cache(); + const RendererCache::LeafNodeData &dataCacheForLeaf = cache->leafNodeCache[m_leafNode]; + RenderView *rv = m_renderViewInitializer->renderView(); + const auto entities = !rv->isCompute() ? cache->renderableEntities : cache->computeEntities; + + rv->setMaterialParameterTable(dataCacheForLeaf.materialParameterGatherer); + + lock.unlock(); + + // Split among the ideal number of command builders + const int idealPacketSize = std::min(std::max(100, entities.size() / RenderViewBuilder::optimalJobCount()), entities.size()); + // Try to split work into an ideal number of workers + const int m = findIdealNumberOfWorkers(entities.size(), idealPacketSize); + + for (int i = 0; i < m; ++i) { + const RenderViewCommandBuilderJobPtr renderViewCommandBuilder = m_renderViewCommandBuilderJobs.at(i); + const int count = (i == m - 1) ? entities.size() - (i * idealPacketSize) : idealPacketSize; + renderViewCommandBuilder->setEntities(entities, i * idealPacketSize, count); + } + } + +private: + RenderViewInitializerJobPtr m_renderViewInitializer; + QVector m_renderViewCommandBuilderJobs; + Renderer *m_renderer; + FrameGraphNode *m_leafNode; +}; + +class SyncRenderViewPostCommandUpdate +{ +public: + explicit SyncRenderViewPostCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob, + const QVector &renderViewCommandUpdateJobs, + Renderer *renderer) + : m_renderViewJob(renderViewJob) + , m_renderViewCommandUpdaterJobs(renderViewCommandUpdateJobs) + , m_renderer(renderer) + {} + + void operator()() + { + // Append all the commands and sort them + RenderView *rv = m_renderViewJob->renderView(); + + const EntityRenderCommandDataPtr commandData = m_renderViewCommandUpdaterJobs.first()->renderables(); + + if (commandData) { + const QVector commands = std::move(commandData->commands); + rv->setCommands(commands); + + // TO DO: Find way to store commands once or at least only when required + // Sort the commands + rv->sort(); + } + + // Enqueue our fully populated RenderView with the RenderThread + m_renderer->enqueueRenderView(rv, m_renderViewJob->submitOrderIndex()); + } + +private: + RenderViewInitializerJobPtr m_renderViewJob; + QVector m_renderViewCommandUpdaterJobs; + Renderer *m_renderer; +}; + +class SyncPreFrustumCulling +{ +public: + explicit SyncPreFrustumCulling(const RenderViewInitializerJobPtr &renderViewJob, + const FrustumCullingJobPtr &frustumCulling) + : m_renderViewJob(renderViewJob) + , m_frustumCullingJob(frustumCulling) + {} + + void operator()() + { + RenderView *rv = m_renderViewJob->renderView(); + + // Update matrices now that all transforms have been updated + rv->updateMatrices(); + + // Frustum culling + m_frustumCullingJob->setViewProjection(rv->viewProjectionMatrix()); + } + +private: + RenderViewInitializerJobPtr m_renderViewJob; + FrustumCullingJobPtr m_frustumCullingJob; +}; + +class SyncRenderViewPostInitialization +{ +public: + explicit SyncRenderViewPostInitialization(const RenderViewInitializerJobPtr &renderViewJob, + const FrustumCullingJobPtr &frustumCullingJob, + const FilterLayerEntityJobPtr &filterEntityByLayerJob, + const FilterProximityDistanceJobPtr &filterProximityJob, + const QVector &materialGathererJobs, + const QVector &renderViewCommandUpdaterJobs, + const QVector &renderViewCommandBuilderJobs) + : m_renderViewJob(renderViewJob) + , m_frustumCullingJob(frustumCullingJob) + , m_filterEntityByLayerJob(filterEntityByLayerJob) + , m_filterProximityJob(filterProximityJob) + , m_materialGathererJobs(materialGathererJobs) + , m_renderViewCommandUpdaterJobs(renderViewCommandUpdaterJobs) + , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) + {} + + void operator()() + { + RenderView *rv = m_renderViewJob->renderView(); + + // Layer filtering + if (!m_filterEntityByLayerJob.isNull()) + m_filterEntityByLayerJob->setLayerFilters(rv->layerFilters()); + + // Proximity filtering + m_filterProximityJob->setProximityFilterIds(rv->proximityFilterIds()); + + // Material Parameter building + for (const auto &materialGatherer : qAsConst(m_materialGathererJobs)) { + materialGatherer->setRenderPassFilter(const_cast(rv->renderPassFilter())); + materialGatherer->setTechniqueFilter(const_cast(rv->techniqueFilter())); + } + + // Command builders and updates + for (const auto &renderViewCommandUpdater : qAsConst(m_renderViewCommandUpdaterJobs)) + renderViewCommandUpdater->setRenderView(rv); + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) + renderViewCommandBuilder->setRenderView(rv); + + // Set whether frustum culling is enabled or not + m_frustumCullingJob->setActive(rv->frustumCulling()); + } + +private: + RenderViewInitializerJobPtr m_renderViewJob; + FrustumCullingJobPtr m_frustumCullingJob; + FilterLayerEntityJobPtr m_filterEntityByLayerJob; + FilterProximityDistanceJobPtr m_filterProximityJob; + QVector m_materialGathererJobs; + QVector m_renderViewCommandUpdaterJobs; + QVector m_renderViewCommandBuilderJobs; +}; + +class SyncRenderViewPreCommandUpdate +{ +public: + explicit SyncRenderViewPreCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob, + const FrustumCullingJobPtr &frustumCullingJob, + const FilterProximityDistanceJobPtr &filterProximityJob, + const QVector &materialGathererJobs, + const QVector &renderViewCommandUpdaterJobs, + const QVector &renderViewCommandBuilderJobs, + Renderer *renderer, + FrameGraphNode *leafNode, + bool fullCommandRebuild) + : m_renderViewJob(renderViewJob) + , m_frustumCullingJob(frustumCullingJob) + , m_filterProximityJob(filterProximityJob) + , m_materialGathererJobs(materialGathererJobs) + , m_renderViewCommandUpdaterJobs(renderViewCommandUpdaterJobs) + , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) + , m_renderer(renderer) + , m_leafNode(leafNode) + , m_fullRebuild(fullCommandRebuild) + {} + + void operator()() + { + // Set the result of previous job computations + // for final RenderCommand building + RenderView *rv = m_renderViewJob->renderView(); + + if (!rv->noDraw()) { + ///////// CACHE LOCKED //////////// + // Retrieve Data from Cache + RendererCache *cache = m_renderer->cache(); + QMutexLocker lock(cache->mutex()); + Q_ASSERT(cache->leafNodeCache.contains(m_leafNode)); + + const bool isDraw = !rv->isCompute(); + const RendererCache::LeafNodeData &dataCacheForLeaf = cache->leafNodeCache[m_leafNode]; + + // Rebuild RenderCommands if required + // This should happen fairly infrequently (FrameGraph Change, Geometry/Material change) + // and allow to skip that step most of the time + if (m_fullRebuild) { + EntityRenderCommandData commandData; + // Reduction + { + int totalCommandCount = 0; + for (const RenderViewCommandBuilderJobPtr &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) + totalCommandCount += renderViewCommandBuilder->commandData().size(); + commandData.reserve(totalCommandCount); + for (const RenderViewCommandBuilderJobPtr &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) + commandData += std::move(renderViewCommandBuilder->commandData()); + } + + + // Store new cache + RendererCache::LeafNodeData &writableCacheForLeaf = cache->leafNodeCache[m_leafNode]; + writableCacheForLeaf.renderCommandData = std::move(commandData); + } + const EntityRenderCommandData commandData = dataCacheForLeaf.renderCommandData; + const QVector filteredEntities = dataCacheForLeaf.filterEntitiesByLayer; + QVector renderableEntities = isDraw ? cache->renderableEntities : cache->computeEntities; + QVector lightSources = cache->gatheredLights; + + rv->setMaterialParameterTable(dataCacheForLeaf.materialParameterGatherer); + rv->setEnvironmentLight(cache->environmentLight); + lock.unlock(); + ///////// END OF CACHE LOCKED //////////// + + // Filter out entities that weren't selected by the layer filters + // Remove all entities from the compute and renderable vectors that aren't in the filtered layer vector + renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, filteredEntities); + + // Set the light sources, with layer filters applied. + for (int i = 0; i < lightSources.count(); ++i) { + if (!filteredEntities.contains(lightSources[i].entity)) + lightSources.removeAt(i--); + } + rv->setLightSources(lightSources); + + if (isDraw) { + // Filter out frustum culled entity for drawable entities + if (rv->frustumCulling()) + renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_frustumCullingJob->visibleEntities()); + // Filter out entities which didn't satisfy proximity filtering + if (!rv->proximityFilterIds().empty()) + renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_filterProximityJob->filteredEntities()); + } + + // Early return in case we have nothing to filter + if (renderableEntities.size() == 0) + return; + + // Filter out Render commands for which the Entity wasn't selected because + // of frustum, proximity or layer filtering + EntityRenderCommandDataPtr filteredCommandData = EntityRenderCommandDataPtr::create(); + filteredCommandData->reserve(renderableEntities.size()); + // Because dataCacheForLeaf.renderableEntities or computeEntities are sorted + // What we get out of EntityRenderCommandData is also sorted by Entity + auto eIt = renderableEntities.cbegin(); + const auto eEnd = renderableEntities.cend(); + int cIt = 0; + const int cEnd = commandData.size(); + + while (eIt != eEnd) { + const Entity *targetEntity = *eIt; + // Advance until we have commands whose Entity has a lower address + // than the selected filtered entity + while (cIt != cEnd && commandData.entities.at(cIt) < targetEntity) + ++cIt; + + // Push pointers to command data for all commands that match the + // entity + while (cIt != cEnd && commandData.entities.at(cIt) == targetEntity) { + filteredCommandData->push_back(commandData.entities.at(cIt), + commandData.commands.at(cIt), + commandData.passesData.at(cIt)); + ++cIt; + } + ++eIt; + } + + // Split among the number of command builders + // The idealPacketSize is at least 100 entities per worker + const int idealPacketSize = std::min(std::max(100, filteredCommandData->size() / RenderViewBuilder::optimalJobCount()), filteredCommandData->size()); + const int m = findIdealNumberOfWorkers(filteredCommandData->size(), idealPacketSize); + + for (int i = 0; i < m; ++i) { + const RenderViewCommandUpdaterJobPtr renderViewCommandBuilder = m_renderViewCommandUpdaterJobs.at(i); + const int count = (i == m - 1) ? filteredCommandData->size() - (i * idealPacketSize) : idealPacketSize; + renderViewCommandBuilder->setRenderables(filteredCommandData, i * idealPacketSize, count); + } + } + } + +private: + RenderViewInitializerJobPtr m_renderViewJob; + FrustumCullingJobPtr m_frustumCullingJob; + FilterProximityDistanceJobPtr m_filterProximityJob; + QVector m_materialGathererJobs; + QVector m_renderViewCommandUpdaterJobs; + QVector m_renderViewCommandBuilderJobs; + Renderer *m_renderer; + FrameGraphNode *m_leafNode; + bool m_fullRebuild; +}; + +class SetClearDrawBufferIndex +{ +public: + explicit SetClearDrawBufferIndex(const RenderViewInitializerJobPtr &renderViewJob) + : m_renderViewJob(renderViewJob) + {} + + void operator()() + { + RenderView *rv = m_renderViewJob->renderView(); + QVector &clearBuffersInfo = rv->specificClearColorBufferInfo(); + const AttachmentPack &attachmentPack = rv->attachmentPack(); + for (ClearBufferInfo &clearBufferInfo : clearBuffersInfo) + clearBufferInfo.drawBufferIndex = attachmentPack.getDrawBufferIndex(clearBufferInfo.attchmentPoint); + + } + +private: + RenderViewInitializerJobPtr m_renderViewJob; +}; + +class SyncFilterEntityByLayer +{ +public: + explicit SyncFilterEntityByLayer(const FilterLayerEntityJobPtr &filterEntityByLayerJob, + Renderer *renderer, + FrameGraphNode *leafNode) + : m_filterEntityByLayerJob(filterEntityByLayerJob) + , m_renderer(renderer) + , m_leafNode(leafNode) + { + } + + void operator()() + { + QMutexLocker lock(m_renderer->cache()->mutex()); + // Save the filtered by layer subset into the cache + const QVector filteredEntities = m_filterEntityByLayerJob->filteredEntities(); + RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; + dataCacheForLeaf.filterEntitiesByLayer = filteredEntities; + } + +private: + FilterLayerEntityJobPtr m_filterEntityByLayerJob; + Renderer *m_renderer; + FrameGraphNode *m_leafNode; +}; + +class SyncMaterialParameterGatherer +{ +public: + explicit SyncMaterialParameterGatherer(const QVector &materialParameterGathererJobs, + Renderer *renderer, + FrameGraphNode *leafNode) + : m_materialParameterGathererJobs(materialParameterGathererJobs) + , m_renderer(renderer) + , m_leafNode(leafNode) + { + } + + void operator()() + { + QMutexLocker lock(m_renderer->cache()->mutex()); + RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; + dataCacheForLeaf.materialParameterGatherer.clear(); + + for (const auto &materialGatherer : qAsConst(m_materialParameterGathererJobs)) + dataCacheForLeaf.materialParameterGatherer.unite(materialGatherer->materialToPassAndParameter()); + } + +private: + QVector m_materialParameterGathererJobs; + Renderer *m_renderer; + FrameGraphNode *m_leafNode; +}; + +} // anonymous + +RenderViewBuilder::RenderViewBuilder(Render::FrameGraphNode *leafNode, int renderViewIndex, Renderer *renderer) + : m_leafNode(leafNode) + , m_renderViewIndex(renderViewIndex) + , m_renderer(renderer) + , m_layerCacheNeedsToBeRebuilt(false) + , m_materialGathererCacheNeedsToBeRebuilt(false) + , m_renderCommandCacheNeedsToBeRebuilt(false) + , m_renderViewJob(RenderViewInitializerJobPtr::create()) + , m_filterEntityByLayerJob() + , m_frustumCullingJob(new Render::FrustumCullingJob()) + , m_syncPreFrustumCullingJob(SynchronizerJobPtr::create(SyncPreFrustumCulling(m_renderViewJob, m_frustumCullingJob), JobTypes::SyncFrustumCulling)) + , m_setClearDrawBufferIndexJob(SynchronizerJobPtr::create(SetClearDrawBufferIndex(m_renderViewJob), JobTypes::ClearBufferDrawIndex)) + , m_syncFilterEntityByLayerJob() + , m_filterProximityJob(Render::FilterProximityDistanceJobPtr::create()) +{ +} + +RenderViewInitializerJobPtr RenderViewBuilder::renderViewJob() const +{ + return m_renderViewJob; +} + +FilterLayerEntityJobPtr RenderViewBuilder::filterEntityByLayerJob() const +{ + return m_filterEntityByLayerJob; +} + +FrustumCullingJobPtr RenderViewBuilder::frustumCullingJob() const +{ + return m_frustumCullingJob; +} + +QVector RenderViewBuilder::renderViewCommandUpdaterJobs() const +{ + return m_renderViewCommandUpdaterJobs; +} + +QVector RenderViewBuilder::renderViewCommandBuilderJobs() const +{ + return m_renderViewCommandBuilderJobs; +} + +QVector RenderViewBuilder::materialGathererJobs() const +{ + return m_materialGathererJobs; +} + +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostInitializationJob() const +{ + return m_syncRenderViewPostInitializationJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncPreFrustumCullingJob() const +{ + return m_syncPreFrustumCullingJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandBuildingJob() const +{ + return m_syncRenderViewPreCommandBuildingJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandUpdateJob() const +{ + return m_syncRenderViewPreCommandUpdateJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostCommandUpdateJob() const +{ + return m_syncRenderViewPostCommandUpdateJob; +} + +SynchronizerJobPtr RenderViewBuilder::setClearDrawBufferIndexJob() const +{ + return m_setClearDrawBufferIndexJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncFilterEntityByLayerJob() const +{ + return m_syncFilterEntityByLayerJob; +} + +SynchronizerJobPtr RenderViewBuilder::syncMaterialGathererJob() const +{ + return m_syncMaterialGathererJob; +} + +FilterProximityDistanceJobPtr RenderViewBuilder::filterProximityJob() const +{ + return m_filterProximityJob; +} + +void RenderViewBuilder::prepareJobs() +{ + // Init what we can here + m_filterProximityJob->setManager(m_renderer->nodeManagers()); + m_frustumCullingJob->setRoot(m_renderer->sceneRoot()); + + if (m_renderCommandCacheNeedsToBeRebuilt) { + + m_renderViewCommandBuilderJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); + for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { + auto renderViewCommandBuilder = Render::RenderViewCommandBuilderJobPtr::create(); + m_renderViewCommandBuilderJobs.push_back(renderViewCommandBuilder); + } + m_syncRenderViewPreCommandBuildingJob = SynchronizerJobPtr::create(SyncPreCommandBuilding(m_renderViewJob, + m_renderViewCommandBuilderJobs, + m_renderer, + m_leafNode), + JobTypes::SyncRenderViewPreCommandBuilding); + } + + m_renderViewJob->setRenderer(m_renderer); + m_renderViewJob->setFrameGraphLeafNode(m_leafNode); + m_renderViewJob->setSubmitOrderIndex(m_renderViewIndex); + + // RenderCommand building is the most consuming task -> split it + // Estimate the number of jobs to create based on the number of entities + m_renderViewCommandUpdaterJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); + for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { + auto renderViewCommandUpdater = Render::RenderViewCommandUpdaterJobPtr::create(); + renderViewCommandUpdater->setRenderer(m_renderer); + m_renderViewCommandUpdaterJobs.push_back(renderViewCommandUpdater); + } + + if (m_materialGathererCacheNeedsToBeRebuilt) { + // Since Material gathering is an heavy task, we split it + const QVector materialHandles = m_renderer->nodeManagers()->materialManager()->activeHandles(); + const int elementsPerJob = materialHandles.size() / RenderViewBuilder::m_optimalParallelJobCount; + const int lastRemaingElements = materialHandles.size() % RenderViewBuilder::m_optimalParallelJobCount; + m_materialGathererJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); + for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { + auto materialGatherer = Render::MaterialParameterGathererJobPtr::create(); + materialGatherer->setNodeManagers(m_renderer->nodeManagers()); + if (i == RenderViewBuilder::m_optimalParallelJobCount - 1) + materialGatherer->setHandles(materialHandles.mid(i * elementsPerJob, elementsPerJob + lastRemaingElements)); + else + materialGatherer->setHandles(materialHandles.mid(i * elementsPerJob, elementsPerJob)); + m_materialGathererJobs.push_back(materialGatherer); + } + m_syncMaterialGathererJob = SynchronizerJobPtr::create(SyncMaterialParameterGatherer(m_materialGathererJobs, + m_renderer, + m_leafNode), + JobTypes::SyncMaterialGatherer); + } + + if (m_layerCacheNeedsToBeRebuilt) { + m_filterEntityByLayerJob = Render::FilterLayerEntityJobPtr::create(); + m_filterEntityByLayerJob->setManager(m_renderer->nodeManagers()); + m_syncFilterEntityByLayerJob = SynchronizerJobPtr::create(SyncFilterEntityByLayer(m_filterEntityByLayerJob, + m_renderer, + m_leafNode), + JobTypes::SyncFilterEntityByLayer); + } + + m_syncRenderViewPreCommandUpdateJob = SynchronizerJobPtr::create(SyncRenderViewPreCommandUpdate(m_renderViewJob, + m_frustumCullingJob, + m_filterProximityJob, + m_materialGathererJobs, + m_renderViewCommandUpdaterJobs, + m_renderViewCommandBuilderJobs, + m_renderer, + m_leafNode, + m_renderCommandCacheNeedsToBeRebuilt), + JobTypes::SyncRenderViewPreCommandUpdate); + + m_syncRenderViewPostCommandUpdateJob = SynchronizerJobPtr::create(SyncRenderViewPostCommandUpdate(m_renderViewJob, + m_renderViewCommandUpdaterJobs, + m_renderer), + JobTypes::SyncRenderViewPostCommandUpdate); + + m_syncRenderViewPostInitializationJob = SynchronizerJobPtr::create(SyncRenderViewPostInitialization(m_renderViewJob, + m_frustumCullingJob, + m_filterEntityByLayerJob, + m_filterProximityJob, + m_materialGathererJobs, + m_renderViewCommandUpdaterJobs, + m_renderViewCommandBuilderJobs), + JobTypes::SyncRenderViewInitialization); +} + +QVector RenderViewBuilder::buildJobHierachy() const +{ + QVector jobs; + + jobs.reserve(m_materialGathererJobs.size() + m_renderViewCommandUpdaterJobs.size() + 11); + + // Set dependencies + + // Finish the skinning palette job before processing renderviews + // TODO: Maybe only update skinning palettes for non-culled entities + m_renderViewJob->addDependency(m_renderer->updateSkinningPaletteJob()); + + m_syncPreFrustumCullingJob->addDependency(m_renderer->updateWorldTransformJob()); + m_syncPreFrustumCullingJob->addDependency(m_renderer->updateShaderDataTransformJob()); + m_syncPreFrustumCullingJob->addDependency(m_syncRenderViewPostInitializationJob); + + m_frustumCullingJob->addDependency(m_renderer->expandBoundingVolumeJob()); + m_frustumCullingJob->addDependency(m_syncPreFrustumCullingJob); + + m_setClearDrawBufferIndexJob->addDependency(m_syncRenderViewPostInitializationJob); + + m_syncRenderViewPostInitializationJob->addDependency(m_renderViewJob); + + m_filterProximityJob->addDependency(m_renderer->expandBoundingVolumeJob()); + m_filterProximityJob->addDependency(m_syncRenderViewPostInitializationJob); + + m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncRenderViewPostInitializationJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_filterProximityJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_frustumCullingJob); + + // Ensure the RenderThread won't be able to process dirtyResources + // before they have been completely gathered + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->introspectShadersJob()); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->bufferGathererJob()); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->textureGathererJob()); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->cacheLightJob()); + + for (const auto &renderViewCommandUpdater : qAsConst(m_renderViewCommandUpdaterJobs)) { + renderViewCommandUpdater->addDependency(m_syncRenderViewPreCommandUpdateJob); + m_syncRenderViewPostCommandUpdateJob->addDependency(renderViewCommandUpdater); + } + + m_renderer->frameCleanupJob()->addDependency(m_syncRenderViewPostCommandUpdateJob); + m_renderer->frameCleanupJob()->addDependency(m_setClearDrawBufferIndexJob); + + // Add jobs + jobs.push_back(m_renderViewJob); // Step 1 + + jobs.push_back(m_syncRenderViewPostInitializationJob); // Step 2 + + if (m_renderCommandCacheNeedsToBeRebuilt) { // Step 3 + m_syncRenderViewPreCommandBuildingJob->addDependency(m_renderer->cacheComputableEntitiesJob()); + m_syncRenderViewPreCommandBuildingJob->addDependency(m_renderer->cacheRenderableEntitiesJob()); + m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncRenderViewPostInitializationJob); + + if (m_materialGathererCacheNeedsToBeRebuilt) + m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncMaterialGathererJob); + + jobs.push_back(m_syncRenderViewPreCommandBuildingJob); + + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) { + renderViewCommandBuilder->addDependency(m_syncRenderViewPreCommandBuildingJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(renderViewCommandBuilder); + jobs.push_back(renderViewCommandBuilder); + } + } + + if (m_layerCacheNeedsToBeRebuilt) { + m_filterEntityByLayerJob->addDependency(m_renderer->updateEntityLayersJob()); + m_filterEntityByLayerJob->addDependency(m_syncRenderViewPostInitializationJob); + m_filterEntityByLayerJob->addDependency(m_renderer->updateTreeEnabledJob()); + + m_syncFilterEntityByLayerJob->addDependency(m_filterEntityByLayerJob); + m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncFilterEntityByLayerJob); + + jobs.push_back(m_filterEntityByLayerJob); // Step 3 + jobs.push_back(m_syncFilterEntityByLayerJob); // Step 4 + } + jobs.push_back(m_syncPreFrustumCullingJob); // Step 3 + jobs.push_back(m_filterProximityJob); // Step 3 + jobs.push_back(m_setClearDrawBufferIndexJob); // Step 3 + + if (m_materialGathererCacheNeedsToBeRebuilt) { + for (const auto &materialGatherer : qAsConst(m_materialGathererJobs)) { + materialGatherer->addDependency(m_syncRenderViewPostInitializationJob); + materialGatherer->addDependency(m_renderer->introspectShadersJob()); + materialGatherer->addDependency(m_renderer->filterCompatibleTechniqueJob()); + jobs.push_back(materialGatherer); // Step3 + m_syncMaterialGathererJob->addDependency(materialGatherer); + } + m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncMaterialGathererJob); + + jobs.push_back(m_syncMaterialGathererJob); // Step 3 + } + + jobs.push_back(m_frustumCullingJob); // Step 4 + jobs.push_back(m_syncRenderViewPreCommandUpdateJob); // Step 5 + + // Build RenderCommands or Update RenderCommand Uniforms + for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandUpdaterJobs)) // Step 6 + jobs.push_back(renderViewCommandBuilder); + + jobs.push_back(m_syncRenderViewPostCommandUpdateJob); // Step 7 + + return jobs; +} + +Renderer *RenderViewBuilder::renderer() const +{ + return m_renderer; +} + +int RenderViewBuilder::renderViewIndex() const +{ + return m_renderViewIndex; +} + +void RenderViewBuilder::setLayerCacheNeedsToBeRebuilt(bool needsToBeRebuilt) +{ + m_layerCacheNeedsToBeRebuilt = needsToBeRebuilt; +} + +bool RenderViewBuilder::layerCacheNeedsToBeRebuilt() const +{ + return m_layerCacheNeedsToBeRebuilt; +} + +void RenderViewBuilder::setMaterialGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt) +{ + m_materialGathererCacheNeedsToBeRebuilt = needsToBeRebuilt; +} + +bool RenderViewBuilder::materialGathererCacheNeedsToBeRebuilt() const +{ + return m_materialGathererCacheNeedsToBeRebuilt; +} + +void RenderViewBuilder::setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt) +{ + m_renderCommandCacheNeedsToBeRebuilt = needsToBeRebuilt; +} + +bool RenderViewBuilder::renderCommandCacheNeedsToBeRebuilt() const +{ + return m_renderCommandCacheNeedsToBeRebuilt; +} + +int RenderViewBuilder::optimalJobCount() +{ + return RenderViewBuilder::m_optimalParallelJobCount; +} + +QVector RenderViewBuilder::entitiesInSubset(const QVector &entities, const QVector &subset) +{ + QVector intersection; + intersection.reserve(qMin(entities.size(), subset.size())); + std::set_intersection(entities.begin(), entities.end(), + subset.begin(), subset.end(), + std::back_inserter(intersection)); + + return intersection; +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h b/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h new file mode 100644 index 000000000..71719abee --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h @@ -0,0 +1,148 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERVIEWBUILDER_H +#define QT3DRENDER_RENDER_RENDERVIEWBUILDER_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class Renderer; + +using SynchronizerJobPtr = GenericLambdaJobPtr>; + +class Q_AUTOTEST_EXPORT RenderViewBuilder +{ +public: + explicit RenderViewBuilder(Render::FrameGraphNode *leafNode, int renderViewIndex, Renderer *renderer); + + RenderViewInitializerJobPtr renderViewJob() const; + FilterLayerEntityJobPtr filterEntityByLayerJob() const; + FrustumCullingJobPtr frustumCullingJob() const; + QVector renderViewCommandBuilderJobs() const; + QVector renderViewCommandUpdaterJobs() const; + QVector materialGathererJobs() const; + SynchronizerJobPtr syncRenderViewPostInitializationJob() const; + SynchronizerJobPtr syncPreFrustumCullingJob() const; + SynchronizerJobPtr syncRenderViewPreCommandBuildingJob() const; + SynchronizerJobPtr syncRenderViewPreCommandUpdateJob() const; + SynchronizerJobPtr syncRenderViewPostCommandUpdateJob() const; + SynchronizerJobPtr setClearDrawBufferIndexJob() const; + SynchronizerJobPtr syncFilterEntityByLayerJob() const; + FilterProximityDistanceJobPtr filterProximityJob() const; + SynchronizerJobPtr syncMaterialGathererJob() const; + + void prepareJobs(); + QVector buildJobHierachy() const; + + Renderer *renderer() const; + int renderViewIndex() const; + + void setLayerCacheNeedsToBeRebuilt(bool needsToBeRebuilt); + bool layerCacheNeedsToBeRebuilt() const; + void setMaterialGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt); + bool materialGathererCacheNeedsToBeRebuilt() const; + void setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt); + bool renderCommandCacheNeedsToBeRebuilt() const; + + static int optimalJobCount(); + static QVector entitiesInSubset(const QVector &entities, const QVector &subset); + +private: + Render::FrameGraphNode *m_leafNode; + const int m_renderViewIndex; + Renderer *m_renderer; + bool m_layerCacheNeedsToBeRebuilt; + bool m_materialGathererCacheNeedsToBeRebuilt; + bool m_renderCommandCacheNeedsToBeRebuilt; + + RenderViewInitializerJobPtr m_renderViewJob; + FilterLayerEntityJobPtr m_filterEntityByLayerJob; + FrustumCullingJobPtr m_frustumCullingJob; + QVector m_renderViewCommandBuilderJobs; + QVector m_renderViewCommandUpdaterJobs; + QVector m_materialGathererJobs; + + SynchronizerJobPtr m_syncRenderViewPostInitializationJob; + SynchronizerJobPtr m_syncPreFrustumCullingJob; + SynchronizerJobPtr m_syncRenderViewPreCommandBuildingJob; + SynchronizerJobPtr m_syncRenderViewPreCommandUpdateJob; + SynchronizerJobPtr m_syncRenderViewPostCommandUpdateJob; + SynchronizerJobPtr m_setClearDrawBufferIndexJob; + SynchronizerJobPtr m_syncFilterEntityByLayerJob; + SynchronizerJobPtr m_syncMaterialGathererJob; + FilterProximityDistanceJobPtr m_filterProximityJob; + + static const int m_optimalParallelJobCount; +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERVIEWBUILDER_H diff --git a/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp b/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp new file mode 100644 index 000000000..e3cc7baf7 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp @@ -0,0 +1,112 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "shaderparameterpack_p.h" + +#include +#include + +#include + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +ShaderParameterPack::~ShaderParameterPack() +{ +} + +void ShaderParameterPack::setUniform(const int glslNameId, const UniformValue &val) +{ + m_uniforms.insert(glslNameId, val); +} + +void ShaderParameterPack::setTexture(const int glslNameId, int uniformArrayIndex, Qt3DCore::QNodeId texId) +{ + for (int t=0; t +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLShaderProgram; + +namespace Qt3DCore { +class QFrameAllocator; +} + +namespace Qt3DRender { +namespace Render { + +class GraphicsContext; + +struct BlockToUBO { + int m_blockIndex; + Qt3DCore::QNodeId m_bufferID; + bool m_needsUpdate; + QHash m_updatedProperties; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, BlockToUBO, Q_MOVABLE_TYPE) + +struct BlockToSSBO { + int m_blockIndex; + int m_bindingIndex; + Qt3DCore::QNodeId m_bufferID; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, BlockToSSBO, Q_PRIMITIVE_TYPE) + + +struct PackUniformHash +{ + QVector keys; + QVector values; + + PackUniformHash() + { + keys.reserve(10); + values.reserve(10); + } + + void insert(int key, const UniformValue &value) + { + const int idx = keys.indexOf(key); + if (idx != -1) { + values[idx] = value; + } else { + keys.push_back(key); + values.push_back(value); + } + } + + UniformValue value(int key) const + { + const int idx = keys.indexOf(key); + if (idx != -1) + return values.at(idx); + return UniformValue(); + } + + UniformValue& value(int key) + { + const int idx = keys.indexOf(key); + if (idx != -1) + return values[idx]; + insert(key, UniformValue()); + return value(key); + } + + void erase(int idx) + { + keys.removeAt(idx); + values.removeAt(idx); + } + + bool contains(int key) const + { + return keys.contains(key); + } +}; + +class Q_AUTOTEST_EXPORT ShaderParameterPack +{ +public: + ~ShaderParameterPack(); + + void setUniform(const int glslNameId, const UniformValue &val); + void setTexture(const int glslNameId, int uniformArrayIndex, Qt3DCore::QNodeId id); + void setImage(const int glslNameId, int uniformArrayIndex, Qt3DCore::QNodeId id); + + void setUniformBuffer(BlockToUBO blockToUBO); + void setShaderStorageBuffer(BlockToSSBO blockToSSBO); + void setSubmissionUniform(const ShaderUniform &uniform); + + inline PackUniformHash &uniforms() { return m_uniforms; } + inline const PackUniformHash &uniforms() const { return m_uniforms; } + UniformValue uniform(const int glslNameId) const { return m_uniforms.value(glslNameId); } + + + struct NamedResource + { + enum Type { + Texture = 0, + Image + }; + + NamedResource() {} + NamedResource(const int glslNameId, Qt3DCore::QNodeId texId, + int uniformArrayIndex, Type type) + : glslNameId(glslNameId) + , nodeId(texId) + , uniformArrayIndex(uniformArrayIndex) + , type(type) + { } + + int glslNameId; + Qt3DCore::QNodeId nodeId; + int uniformArrayIndex; + Type type; + + bool operator==(const NamedResource &other) const + { + return glslNameId == other.glslNameId && + nodeId == other.nodeId && + uniformArrayIndex == other.uniformArrayIndex && + type == other.type; + } + + bool operator!=(const NamedResource &other) const + { + return !(*this == other); + } + }; + + inline QVector textures() const { return m_textures; } + inline QVector images() const { return m_images; } + inline QVector uniformBuffers() const { return m_uniformBuffers; } + inline QVector shaderStorageBuffers() const { return m_shaderStorageBuffers; } + inline QVector submissionUniforms() const { return m_submissionUniforms; } +private: + PackUniformHash m_uniforms; + + QVector m_textures; + QVector m_images; + QVector m_uniformBuffers; + QVector m_shaderStorageBuffers; + QVector m_submissionUniforms; + + friend class RenderView; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderParameterPack::NamedResource, Q_PRIMITIVE_TYPE) + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +Q_DECLARE_METATYPE(Qt3DRender::Render::ShaderParameterPack) + +#endif // QT3DRENDER_RENDER_SHADERPARAMETERPACK_P_H diff --git a/src/plugins/renderers/opengl/renderer/shadervariables_p.h b/src/plugins/renderers/opengl/renderer/shadervariables_p.h new file mode 100644 index 000000000..98b98ae5c --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/shadervariables_p.h @@ -0,0 +1,152 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_SHADERVARIABLES_P_H +#define QT3DRENDER_RENDER_SHADERVARIABLES_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +struct ShaderAttribute +{ + ShaderAttribute() + : m_nameId(-1) + , m_type(0) + , m_size(0) + , m_location(-1) + {} + + QString m_name; + int m_nameId; + GLenum m_type; + int m_size; + int m_location; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderAttribute, Q_MOVABLE_TYPE) + +struct Q_AUTOTEST_EXPORT ShaderUniform +{ + ShaderUniform() + : m_nameId(-1) + , m_type(GL_NONE) + , m_size(0) + , m_offset(-1) + , m_location(-1) + , m_blockIndex(-1) + , m_arrayStride(-1) + , m_matrixStride(-1) + , m_rawByteSize(0) + {} + + QString m_name; + int m_nameId; + GLenum m_type; + int m_size; + int m_offset; // -1 default, >= 0 if uniform defined in uniform block + int m_location; // -1 if uniform defined in a uniform block + int m_blockIndex; // -1 is the default, >= 0 if uniform defined in uniform block + int m_arrayStride; // -1 is the default, >= 0 if uniform defined in uniform block and if it's an array + int m_matrixStride; // -1 is the default, >= 0 uniform defined in uniform block and is a matrix + uint m_rawByteSize; // contains byte size (size / type / strides) + // size, offset and strides are in bytes +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderUniform, Q_MOVABLE_TYPE) + +struct Q_AUTOTEST_EXPORT ShaderUniformBlock +{ + ShaderUniformBlock() + : m_nameId(-1) + , m_index(-1) + , m_binding(-1) + , m_activeUniformsCount(0) + , m_size(0) + {} + + QString m_name; + int m_nameId; + int m_index; + int m_binding; + int m_activeUniformsCount; + int m_size; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderUniformBlock, Q_MOVABLE_TYPE) + +struct Q_AUTOTEST_EXPORT ShaderStorageBlock +{ + ShaderStorageBlock() + : m_nameId(-1) + , m_index(-1) + , m_binding(-1) + , m_size(0) + , m_activeVariablesCount(0) + {} + + QString m_name; + int m_nameId; + int m_index; + int m_binding; + int m_size; + int m_activeVariablesCount; +}; +QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderStorageBlock, Q_MOVABLE_TYPE) + +} // namespace Render + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_SHADERVARIABLES_P_H diff --git a/src/plugins/renderers/opengl/textures/gltexture.cpp b/src/plugins/renderers/opengl/textures/gltexture.cpp new file mode 100644 index 000000000..c79961d78 --- /dev/null +++ b/src/plugins/renderers/opengl/textures/gltexture.cpp @@ -0,0 +1,772 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "gltexture_p.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(QT_OPENGL_ES_2) +#include +#include +#endif + +QT_BEGIN_NAMESPACE + +using namespace Qt3DCore; + +namespace Qt3DRender { +namespace Render { + +namespace { + +// This uploadGLData where the data is a fullsize subimage +// as QOpenGLTexture doesn't allow partial subimage uploads +void uploadGLData(QOpenGLTexture *glTex, + int level, int layer, QOpenGLTexture::CubeMapFace face, + const QByteArray &bytes, const QTextureImageDataPtr &data) +{ + if (data->isCompressed()) { + glTex->setCompressedData(level, layer, face, bytes.size(), bytes.constData()); + } else { + QOpenGLPixelTransferOptions uploadOptions; + uploadOptions.setAlignment(1); + glTex->setData(level, layer, face, data->pixelFormat(), data->pixelType(), bytes.constData(), &uploadOptions); + } +} + +// For partial sub image uploads +void uploadGLData(QOpenGLTexture *glTex, + int mipLevel, int layer, QOpenGLTexture::CubeMapFace cubeFace, + int xOffset, int yOffset, int zOffset, + const QByteArray &bytes, const QTextureImageDataPtr &data) +{ + if (data->isCompressed()) { + qWarning() << Q_FUNC_INFO << "Uploading non full sized Compressed Data not supported yet"; + } else { + QOpenGLPixelTransferOptions uploadOptions; + uploadOptions.setAlignment(1); + glTex->setData(xOffset, yOffset, zOffset, + data->width(), data->height(), data->depth(), + mipLevel, layer, cubeFace, data->layers(), + data->pixelFormat(), data->pixelType(), + bytes.constData(), &uploadOptions); + } +} + +} // anonymous + + +GLTexture::GLTexture() + : m_dirtyFlags(None) + , m_gl(nullptr) + , m_renderBuffer(nullptr) + , m_dataFunctor() + , m_pendingDataFunctor(nullptr) + , m_sharedTextureId(-1) + , m_externalRendering(false) + , m_wasTextureRecreated(false) +{ +} + +GLTexture::~GLTexture() +{ +} + +// Must be called from RenderThread with active GL context +void GLTexture::destroy() +{ + delete m_gl; + m_gl = nullptr; + delete m_renderBuffer; + m_renderBuffer = nullptr; + + m_dirtyFlags = None; + m_sharedTextureId = -1; + m_externalRendering = false; + m_wasTextureRecreated = false; + m_dataFunctor.reset(); + m_pendingDataFunctor = nullptr; + + m_properties = {}; + m_parameters = {}; + m_textureData.reset(); + m_images.clear(); + m_imageData.clear(); + m_pendingTextureDataUpdates.clear(); +} + +bool GLTexture::loadTextureDataFromGenerator() +{ + m_textureData = m_dataFunctor->operator()(); + // if there is a texture generator, most properties will be defined by it + if (m_textureData) { + const QAbstractTexture::Target target = m_textureData->target(); + + // If both target and functor return Automatic we are still + // probably loading the texture, return false + if (m_properties.target == QAbstractTexture::TargetAutomatic && + target == QAbstractTexture::TargetAutomatic) { + m_textureData.reset(); + return false; + } + + if (m_properties.target != QAbstractTexture::TargetAutomatic && + target != QAbstractTexture::TargetAutomatic && + m_properties.target != target) { + qWarning() << Q_FUNC_INFO << "Generator and Properties not requesting the same texture target"; + m_textureData.reset(); + return false; + } + + // We take target type from generator if it wasn't explicitly set by the user + if (m_properties.target == QAbstractTexture::TargetAutomatic) + m_properties.target = target; + m_properties.width = m_textureData->width(); + m_properties.height = m_textureData->height(); + m_properties.depth = m_textureData->depth(); + m_properties.layers = m_textureData->layers(); + m_properties.format = m_textureData->format(); + + const QVector imageData = m_textureData->imageData(); + + if (imageData.size() > 0) { + // Set the mips level based on the first image if autoMipMapGeneration is disabled + if (!m_properties.generateMipMaps) + m_properties.mipLevels = imageData.first()->mipLevels(); + } + } + return !m_textureData.isNull(); +} + +void GLTexture::loadTextureDataFromImages() +{ + int maxMipLevel = 0; + for (const Image &img : qAsConst(m_images)) { + const QTextureImageDataPtr imgData = img.generator->operator()(); + // imgData may be null in the following cases: + // - Texture is created with TextureImages which have yet to be + // loaded (skybox where you don't yet know the path, source set by + // a property binding, queued connection ...) + // - TextureImage whose generator failed to return a valid data + // (invalid url, error opening file...) + if (imgData.isNull()) + continue; + + m_imageData.push_back(imgData); + maxMipLevel = qMax(maxMipLevel, img.mipLevel); + + // If the texture doesn't have a texture generator, we will + // derive some properties from the first TextureImage (layer=0, miplvl=0, face=0) + if (!m_textureData && img.layer == 0 && img.mipLevel == 0 && img.face == QAbstractTexture::CubeMapPositiveX) { + if (imgData->width() != -1 && imgData->height() != -1 && imgData->depth() != -1) { + m_properties.width = imgData->width(); + m_properties.height = imgData->height(); + m_properties.depth = imgData->depth(); + } + // Set the format of the texture if the texture format is set to Automatic + if (m_properties.format == QAbstractTexture::Automatic) { + m_properties.format = static_cast(imgData->format()); + } + setDirtyFlag(Properties, true); + } + } + + // make sure the number of mip levels is set when there is no texture data generator + if (!m_dataFunctor) { + m_properties.mipLevels = maxMipLevel + 1; + setDirtyFlag(Properties, true); + } +} + +// Called from RenderThread +GLTexture::TextureUpdateInfo GLTexture::createOrUpdateGLTexture() +{ + TextureUpdateInfo textureInfo; + m_wasTextureRecreated = false; + + const bool hasSharedTextureId = m_sharedTextureId > 0; + // Only load texture data if we are not using a sharedTextureId + // Check if dataFunctor or images have changed + if (!hasSharedTextureId) { + // If dataFunctor exists and we have no data and it hasn´t run yet + if (m_dataFunctor && !m_textureData && m_dataFunctor.get() != m_pendingDataFunctor ) { + const bool successfullyLoadedTextureData = loadTextureDataFromGenerator(); + // If successful, m_textureData has content + if (successfullyLoadedTextureData) { + setDirtyFlag(Properties, true); + setDirtyFlag(TextureData, true); + } else { + if (m_pendingDataFunctor != m_dataFunctor.get()) { + qWarning() << "[Qt3DRender::GLTexture] No QTextureData generated from Texture Generator yet. Texture will be invalid for this frame"; + m_pendingDataFunctor = m_dataFunctor.get(); + } + textureInfo.properties.status = QAbstractTexture::Loading; + return textureInfo; + } + } + + // If images have changed, clear previous images data + // and regenerate m_imageData for the images + if (testDirtyFlag(TextureImageData)) { + m_imageData.clear(); + loadTextureDataFromImages(); + // Mark for upload if we actually have something to upload + if (!m_imageData.empty()) { + setDirtyFlag(TextureData, true); + } + // Reset image flag + setDirtyFlag(TextureImageData, false); + } + + // Don't try to create the texture if the target or format was still not set + // Format should either be set by user or if Automatic + // by either the dataGenerator of the texture or the first Image + // Target should explicitly be set by the user or the dataGenerator + if (m_properties.target == QAbstractTexture::TargetAutomatic || + m_properties.format == QAbstractTexture::Automatic || + m_properties.format == QAbstractTexture::NoFormat) { + textureInfo.properties.status = QAbstractTexture::Error; + return textureInfo; + } + } + + // If the properties changed or texture has become a shared texture from a + // 3rd party engine, we need to destroy and maybe re-allocate the texture + if (testDirtyFlag(Properties) || testDirtyFlag(SharedTextureId)) { + delete m_gl; + m_gl = nullptr; + textureInfo.wasUpdated = true; + // If we are destroyed because of some property change but still have (some) of + // our content data make sure we are marked for upload + // TO DO: We should actually check if the textureData is still correct + // in regard to the size, target and format of the texture though. + if (!testDirtyFlag(SharedTextureId) && + (m_textureData || !m_imageData.empty() || !m_pendingTextureDataUpdates.empty())) + setDirtyFlag(TextureData, true); + } + + m_properties.status = QAbstractTexture::Ready; + + if (testDirtyFlag(SharedTextureId) || hasSharedTextureId) { + // Update m_properties by doing introspection on the texture + if (hasSharedTextureId) + introspectPropertiesFromSharedTextureId(); + setDirtyFlag(SharedTextureId, false); + } else { + // We only build a QOpenGLTexture if we have no shared textureId set + if (!m_gl) { + m_gl = buildGLTexture(); + if (!m_gl) { + qWarning() << "[Qt3DRender::GLTexture] failed to create texture"; + textureInfo.properties.status = QAbstractTexture::Error; + return textureInfo; + } + + m_gl->allocateStorage(); + if (!m_gl->isStorageAllocated()) { + qWarning() << "[Qt3DRender::GLTexture] failed to allocate texture"; + textureInfo.properties.status = QAbstractTexture::Error; + return textureInfo; + } + m_wasTextureRecreated = true; + } + + textureInfo.texture = m_gl; + + // need to (re-)upload texture data? + const bool needsUpload = testDirtyFlag(TextureData); + if (needsUpload) { + uploadGLTextureData(); + setDirtyFlag(TextureData, false); + } + + // need to set texture parameters? + if (testDirtyFlag(Properties) || testDirtyFlag(Parameters)) { + updateGLTextureParameters(); + setDirtyFlag(Properties, false); + setDirtyFlag(Parameters, false); + } + } + + textureInfo.properties = m_properties; + + return textureInfo; +} + +RenderBuffer *GLTexture::getOrCreateRenderBuffer() +{ + if (m_dataFunctor && !m_textureData) { + m_textureData = m_dataFunctor->operator()(); + if (m_textureData) { + if (m_properties.target != QAbstractTexture::TargetAutomatic) + qWarning() << "[Qt3DRender::GLTexture] [renderbuffer] When a texture provides a generator, it's target is expected to be TargetAutomatic"; + + m_properties.width = m_textureData->width(); + m_properties.height = m_textureData->height(); + m_properties.format = m_textureData->format(); + + setDirtyFlag(Properties); + } else { + if (m_pendingDataFunctor != m_dataFunctor.get()) { + qWarning() << "[Qt3DRender::GLTexture] [renderbuffer] No QTextureData generated from Texture Generator yet. Texture will be invalid for this frame"; + m_pendingDataFunctor = m_dataFunctor.get(); + } + return nullptr; + } + } + + if (testDirtyFlag(Properties)) { + delete m_renderBuffer; + m_renderBuffer = nullptr; + } + + if (!m_renderBuffer) + m_renderBuffer = new RenderBuffer(m_properties.width, m_properties.height, m_properties.format); + + setDirtyFlag(Properties, false); + setDirtyFlag(Parameters, false); + + return m_renderBuffer; +} + +// This must be called from the RenderThread +// So GLTexture release from the manager can only be done from that thread +void GLTexture::cleanup() +{ + destroy(); +} + +void GLTexture::setParameters(const TextureParameters ¶ms) +{ + if (m_parameters != params) { + m_parameters = params; + setDirtyFlag(Parameters); + } +} + +void GLTexture::setProperties(const TextureProperties &props) +{ + if (m_properties != props) { + m_properties = props; + setDirtyFlag(Properties); + } +} + +void GLTexture::setImages(const QVector &images) +{ + // check if something has changed at all + bool same = (images.size() == m_images.size()); + if (same) { + for (int i = 0; i < images.size(); i++) { + if (images[i] != m_images[i]) { + same = false; + break; + } + } + } + + + if (!same) { + m_images = images; + requestImageUpload(); + } +} + +void GLTexture::setGenerator(const QTextureGeneratorPtr &generator) +{ + m_textureData.reset(); + m_dataFunctor = generator; + m_pendingDataFunctor = nullptr; + requestUpload(); +} + +void GLTexture::setSharedTextureId(int textureId) +{ + if (m_sharedTextureId != textureId) { + m_sharedTextureId = textureId; + setDirtyFlag(SharedTextureId); + } +} + +void GLTexture::addTextureDataUpdates(const QVector &updates) +{ + m_pendingTextureDataUpdates += updates; + requestUpload(); +} + +// Return nullptr if +// - context cannot be obtained +// - texture hasn't yet been loaded +QOpenGLTexture *GLTexture::buildGLTexture() +{ + QOpenGLContext *ctx = QOpenGLContext::currentContext(); + if (!ctx) { + qWarning() << Q_FUNC_INFO << "requires an OpenGL context"; + return nullptr; + } + + const QAbstractTexture::Target actualTarget = m_properties.target; + if (actualTarget == QAbstractTexture::TargetAutomatic) { + // If the target is automatic at this point, it means that the texture + // hasn't been loaded yet (case of remote urls) and that loading failed + // and that target format couldn't be deduced + return nullptr; + } + + QOpenGLTexture* glTex = new QOpenGLTexture(static_cast(actualTarget)); + + // m_format may not be ES2 compatible. Now it's time to convert it, if necessary. + QAbstractTexture::TextureFormat format = m_properties.format; + if (ctx->isOpenGLES() && ctx->format().majorVersion() < 3) { + switch (m_properties.format) { + case QAbstractTexture::RGBA8_UNorm: + case QAbstractTexture::RGBAFormat: + format = QAbstractTexture::RGBAFormat; + break; + case QAbstractTexture::RGB8_UNorm: + case QAbstractTexture::RGBFormat: + format = QAbstractTexture::RGBFormat; + break; + case QAbstractTexture::DepthFormat: + format = QAbstractTexture::DepthFormat; + break; + default: + auto warning = qWarning(); + warning << "Could not find a matching OpenGL ES 2.0 texture format:"; + QtDebugUtils::formatQEnum(warning, m_properties.format); + break; + } + } + + // Map ETC1 to ETC2 when supported. This allows using features like + // immutable storage as ETC2 is standard in GLES 3.0, while the ETC1 extension + // is written against GLES 1.0. + if (m_properties.format == QAbstractTexture::RGB8_ETC1) { + if ((ctx->isOpenGLES() && ctx->format().majorVersion() >= 3) + || ctx->hasExtension(QByteArrayLiteral("GL_OES_compressed_ETC2_RGB8_texture")) + || ctx->hasExtension(QByteArrayLiteral("GL_ARB_ES3_compatibility"))) + format = m_properties.format = QAbstractTexture::RGB8_ETC2; + } + + glTex->setFormat(m_properties.format == QAbstractTexture::Automatic ? + QOpenGLTexture::NoFormat : + static_cast(format)); + glTex->setSize(m_properties.width, m_properties.height, m_properties.depth); + // Set layers count if texture array + if (actualTarget == QAbstractTexture::Target1DArray || + actualTarget == QAbstractTexture::Target2DArray || + actualTarget == QAbstractTexture::Target2DMultisampleArray || + actualTarget == QAbstractTexture::TargetCubeMapArray) { + glTex->setLayers(m_properties.layers); + } + + if (actualTarget == QAbstractTexture::Target2DMultisample || + actualTarget == QAbstractTexture::Target2DMultisampleArray) { + // Set samples count if multisampled texture + // (multisampled textures don't have mipmaps) + glTex->setSamples(m_properties.samples); + } else if (m_properties.generateMipMaps) { + glTex->setMipLevels(glTex->maximumMipLevels()); + } else { + glTex->setAutoMipMapGenerationEnabled(false); + if (glTex->hasFeature(QOpenGLTexture::TextureMipMapLevel)) { + glTex->setMipBaseLevel(0); + glTex->setMipMaxLevel(m_properties.mipLevels - 1); + } + glTex->setMipLevels(m_properties.mipLevels); + } + + if (!glTex->create()) { + qWarning() << Q_FUNC_INFO << "creating QOpenGLTexture failed"; + return nullptr; + } + + return glTex; +} + +void GLTexture::uploadGLTextureData() +{ + // Upload all QTexImageData set by the QTextureGenerator + if (m_textureData) { + const QVector imgData = m_textureData->imageData(); + + for (const QTextureImageDataPtr &data : imgData) { + const int mipLevels = m_properties.generateMipMaps ? 1 : data->mipLevels(); + + for (int layer = 0; layer < data->layers(); layer++) { + for (int face = 0; face < data->faces(); face++) { + for (int level = 0; level < mipLevels; level++) { + // ensure we don't accidentally cause a detach / copy of the raw bytes + const QByteArray bytes(data->data(layer, face, level)); + uploadGLData(m_gl, level, layer, + static_cast(QOpenGLTexture::CubeMapPositiveX + face), + bytes, data); + } + } + } + } + } + + // Upload all QTexImageData references by the TextureImages + for (int i = 0; i < std::min(m_images.size(), m_imageData.size()); i++) { + const QTextureImageDataPtr &imgData = m_imageData.at(i); + // Here the bytes in the QTextureImageData contain data for a single + // layer, face or mip level, unlike the QTextureGenerator case where + // they are in a single blob. Hence QTextureImageData::data() is not suitable. + const QByteArray bytes(QTextureImageDataPrivate::get(imgData.get())->m_data); + uploadGLData(m_gl, m_images[i].mipLevel, m_images[i].layer, + static_cast(m_images[i].face), + bytes, imgData); + } + // Free up image data once content has been uploaded + // Note: if data functor stores the data, this won't really free anything though + m_imageData.clear(); + + // Update data from TextureUpdates + const QVector textureDataUpdates = std::move(m_pendingTextureDataUpdates); + for (const QTextureDataUpdate &update : textureDataUpdates) { + const QTextureImageDataPtr imgData = update.data(); + + if (!imgData) { + qWarning() << Q_FUNC_INFO << "QTextureDataUpdate no QTextureImageData set"; + continue; + } + + const int xOffset = update.x(); + const int yOffset = update.y(); + const int zOffset = update.z(); + const int xExtent = xOffset + imgData->width(); + const int yExtent = yOffset + imgData->height(); + const int zExtent = zOffset + imgData->depth(); + + // Check update is compatible with our texture + if (xOffset >= m_gl->width() || + yOffset >= m_gl->height() || + zOffset >= m_gl->depth() || + xExtent > m_gl->width() || + yExtent > m_gl->height() || + zExtent > m_gl->depth() || + update.mipLevel() >= m_gl->mipLevels() || + update.layer() >= m_gl->layers()) { + qWarning() << Q_FUNC_INFO << "QTextureDataUpdate incompatible with texture"; + continue; + } + + const QByteArray bytes = (QTextureImageDataPrivate::get(imgData.get())->m_data); + // Here the bytes in the QTextureImageData contain data for a single + // layer, face or mip level, unlike the QTextureGenerator case where + // they are in a single blob. Hence QTextureImageData::data() is not suitable. + + uploadGLData(m_gl, + update.mipLevel(), update.layer(), + static_cast(update.face()), + xOffset, yOffset, zOffset, + bytes, imgData); + } +} + +void GLTexture::updateGLTextureParameters() +{ + const QAbstractTexture::Target actualTarget = m_properties.target; + const bool isMultisampledTexture = (actualTarget == QAbstractTexture::Target2DMultisample || + actualTarget == QAbstractTexture::Target2DMultisampleArray); + // Multisampled textures can only be accessed by texelFetch in shaders + // and don't support wrap modes and mig/mag filtes + if (isMultisampledTexture) + return; + + m_gl->setWrapMode(QOpenGLTexture::DirectionS, static_cast(m_parameters.wrapModeX)); + if (actualTarget != QAbstractTexture::Target1D && + actualTarget != QAbstractTexture::Target1DArray && + actualTarget != QAbstractTexture::TargetBuffer) + m_gl->setWrapMode(QOpenGLTexture::DirectionT, static_cast(m_parameters.wrapModeY)); + if (actualTarget == QAbstractTexture::Target3D) + m_gl->setWrapMode(QOpenGLTexture::DirectionR, static_cast(m_parameters.wrapModeZ)); + m_gl->setMinMagFilters(static_cast(m_parameters.minificationFilter), + static_cast(m_parameters.magnificationFilter)); + if (m_gl->hasFeature(QOpenGLTexture::AnisotropicFiltering)) + m_gl->setMaximumAnisotropy(m_parameters.maximumAnisotropy); + if (m_gl->hasFeature(QOpenGLTexture::TextureComparisonOperators)) { + m_gl->setComparisonFunction(static_cast(m_parameters.comparisonFunction)); + m_gl->setComparisonMode(static_cast(m_parameters.comparisonMode)); + } +} + +void GLTexture::introspectPropertiesFromSharedTextureId() +{ + // We know that the context is active when this function is called + QOpenGLContext *ctx = QOpenGLContext::currentContext(); + if (!ctx) { + qWarning() << Q_FUNC_INFO << "requires an OpenGL context"; + return; + } + QOpenGLFunctions *gl = ctx->functions(); + + // If the user has set the target format himself, we won't try to deduce it + if (m_properties.target != QAbstractTexture::TargetAutomatic) + return; + + const QAbstractTexture::Target targets[] = { + QAbstractTexture::Target2D, + QAbstractTexture::TargetCubeMap, +#ifndef QT_OPENGL_ES_2 + QAbstractTexture::Target1D, + QAbstractTexture::Target1DArray, + QAbstractTexture::Target3D, + QAbstractTexture::Target2DArray, + QAbstractTexture::TargetCubeMapArray, + QAbstractTexture::Target2DMultisample, + QAbstractTexture::Target2DMultisampleArray, + QAbstractTexture::TargetRectangle, + QAbstractTexture::TargetBuffer, +#endif + }; + +#ifndef QT_OPENGL_ES_2 + // Try to find texture target with GL 4.5 functions + const QPair ctxGLVersion = ctx->format().version(); + if (ctxGLVersion.first > 4 || (ctxGLVersion.first == 4 && ctxGLVersion.second >= 5)) { + // Only for GL 4.5+ +#ifdef GL_TEXTURE_TARGET + QOpenGLFunctions_4_5_Core *gl5 = ctx->versionFunctions(); + if (gl5 != nullptr) + gl5->glGetTextureParameteriv(m_sharedTextureId, GL_TEXTURE_TARGET, reinterpret_cast(&m_properties.target)); +#endif + } +#endif + + // If GL 4.5 function unavailable or not working, try a slower way + if (m_properties.target == QAbstractTexture::TargetAutomatic) { + // // OpenGL offers no proper way of querying for the target of a texture given its id + gl->glActiveTexture(GL_TEXTURE0); + + const GLenum targetBindings[] = { + GL_TEXTURE_BINDING_2D, + GL_TEXTURE_BINDING_CUBE_MAP, +#ifndef QT_OPENGL_ES_2 + GL_TEXTURE_BINDING_1D, + GL_TEXTURE_BINDING_1D_ARRAY, + GL_TEXTURE_BINDING_3D, + GL_TEXTURE_BINDING_2D_ARRAY, + GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, + GL_TEXTURE_BINDING_2D_MULTISAMPLE, + GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY, + GL_TEXTURE_BINDING_RECTANGLE, + GL_TEXTURE_BINDING_BUFFER +#endif + }; + + Q_ASSERT(sizeof(targetBindings) / sizeof(targetBindings[0] == sizeof(targets) / sizeof(targets[0]))); + + for (uint i = 0; i < sizeof(targetBindings) / sizeof(targetBindings[0]); ++i) { + const int target = targets[i]; + gl->glBindTexture(target, m_sharedTextureId); + int boundId = 0; + gl->glGetIntegerv(targetBindings[i], &boundId); + gl->glBindTexture(target, 0); + if (boundId == m_sharedTextureId) { + m_properties.target = static_cast(target); + break; + } + } + } + + // Return early if we weren't able to find texture target + if (std::find(std::begin(targets), std::end(targets), m_properties.target) == std::end(targets)) { + qWarning() << "Unable to determine texture target for shared GL texture"; + return; + } + + // Bind texture once we know its target + gl->glBindTexture(m_properties.target, m_sharedTextureId); + + // TO DO: Improve by using glGetTextureParameters when available which + // support direct state access +#ifndef GL_TEXTURE_MAX_LEVEL +#define GL_TEXTURE_MAX_LEVEL 0x813D +#endif + +#ifndef GL_TEXTURE_WRAP_R +#define GL_TEXTURE_WRAP_R 0x8072 +#endif + + gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_MAX_LEVEL, reinterpret_cast(&m_properties.mipLevels)); + gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_MIN_FILTER, reinterpret_cast(&m_parameters.minificationFilter)); + gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_MAG_FILTER, reinterpret_cast(&m_parameters.magnificationFilter)); + gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_WRAP_R, reinterpret_cast(&m_parameters.wrapModeX)); + gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_WRAP_S, reinterpret_cast(&m_parameters.wrapModeY)); + gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_WRAP_T, reinterpret_cast(&m_parameters.wrapModeZ)); + +#ifndef QT_OPENGL_ES_2 + // Try to retrieve dimensions (not available on ES 2.0) + if (!ctx->isOpenGLES()) { + QOpenGLFunctions_3_1 *gl3 = ctx->versionFunctions(); + if (!gl3) { + qWarning() << "Failed to retrieve shared texture dimensions"; + return; + } + + gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_WIDTH, reinterpret_cast(&m_properties.width)); + gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_HEIGHT, reinterpret_cast(&m_properties.height)); + gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_DEPTH, reinterpret_cast(&m_properties.depth)); + gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_INTERNAL_FORMAT, reinterpret_cast(&m_properties.format)); + } +#endif + + gl->glBindTexture(m_properties.target, 0); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/textures/gltexture_p.h b/src/plugins/renderers/opengl/textures/gltexture_p.h new file mode 100644 index 000000000..ca851712d --- /dev/null +++ b/src/plugins/renderers/opengl/textures/gltexture_p.h @@ -0,0 +1,266 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_GLTEXTURE_H +#define QT3DRENDER_RENDER_GLTEXTURE_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLTexture; + +namespace Qt3DRender { +namespace Render { + +class TextureImageManager; +class TextureDataManager; +class TextureImageDataManager; +class RenderBuffer; + +/** + * @brief + * Actual implementation of the OpenGL texture object. Makes sure the + * QOpenGLTexture is up-to-date with the generators, properties and parameters + * that were set for this GLTexture. + * + * Can be shared among multiple QTexture backend nodes through the + * GLTextureManager, which will make sure that there are no two GLTextures + * sharing the same texture data. + * + * A GLTexture can be unique though. In that case, it will not be shared + * between QTextures, but private to one QTexture only. + * + * A GLTexture can also represent an OpenGL renderbuffer object. This is used + * only in certain special cases, mainly to provide a packed depth-stencil + * renderbuffer suitable as an FBO attachment with OpenGL ES 3.1 and earlier. + * Such a GLTexture will have no texture object under the hood, and therefore + * the only valid operation is getOrCreateRenderBuffer(). + */ +class Q_AUTOTEST_EXPORT GLTexture +{ +public: + GLTexture(); + ~GLTexture(); + + enum DirtyFlag { + None = 0, + TextureData = (1 << 0), // texture data needs uploading to GPU + Properties = (1 << 1), // texture needs to be (re-)created + Parameters = (1 << 2), // texture parameters need to be (re-)set + SharedTextureId = (1 << 3), // texture id from shared context + TextureImageData = (1 << 4) // texture image data needs uploading + }; + + /** + * Helper class to hold the defining properties of TextureImages + */ + struct Image { + QTextureImageDataGeneratorPtr generator; + int layer; + int mipLevel; + QAbstractTexture::CubeMapFace face; + + inline bool operator==(const Image &o) const { + bool sameGenerators = (generator == o.generator) + || (!generator.isNull() && !o.generator.isNull() && *generator == *o.generator); + return sameGenerators && layer == o.layer && mipLevel == o.mipLevel && face == o.face; + } + inline bool operator!=(const Image &o) const { return !(*this == o); } + }; + + inline TextureProperties properties() const { return m_properties; } + inline TextureParameters parameters() const { return m_parameters; } + inline QTextureGeneratorPtr textureGenerator() const { return m_dataFunctor; } + inline int sharedTextureId() const { return m_sharedTextureId; } + inline QVector images() const { return m_images; } + + inline QSize size() const { return QSize(m_properties.width, m_properties.height); } + inline QOpenGLTexture *getGLTexture() const { return m_gl; } + + /** + * @brief + * Returns the QOpenGLTexture for this GLTexture. If necessary, + * the GL texture will be created from the TextureImageDatas associated + * with the texture and image functors. If no functors are provided, + * the texture will be created without images. + * + * If the texture properties or parameters have changed, these changes + * will be applied to the resulting OpenGL texture. + */ + struct TextureUpdateInfo + { + QOpenGLTexture *texture = nullptr; + bool wasUpdated = false; + TextureProperties properties; + }; + + TextureUpdateInfo createOrUpdateGLTexture(); + + /** + * @brief + * Returns the RenderBuffer for this GLTexture. If this is the first + * call, the OpenGL renderbuffer object will be created. + */ + RenderBuffer *getOrCreateRenderBuffer(); + + + void destroy(); + + void cleanup(); + + bool isDirty() const + { + return m_dirtyFlags != None; + } + + bool hasTextureData() const { return !m_textureData.isNull(); } + bool hasImagesData() const { return !m_imageData.isEmpty(); } + + QFlags dirtyFlags() const { return m_dirtyFlags; } + + QMutex *externalRenderingLock() + { + return &m_externalRenderingMutex; + } + + void setExternalRenderingEnabled(bool enable) + { + m_externalRendering = enable; + } + + bool isExternalRenderingEnabled() const + { + return m_externalRendering; + } + + // Purely for unit testing purposes + bool wasTextureRecreated() const + { + return m_wasTextureRecreated; + } + + void setParameters(const TextureParameters ¶ms); + void setProperties(const TextureProperties &props); + void setImages(const QVector &images); + void setGenerator(const QTextureGeneratorPtr &generator); + void setSharedTextureId(int textureId); + void addTextureDataUpdates(const QVector &updates); + + QVector textureDataUpdates() const { return m_pendingTextureDataUpdates; } + QTextureGeneratorPtr dataGenerator() const { return m_dataFunctor; } + +private: + void requestImageUpload() + { + m_dirtyFlags |= TextureImageData; + } + + void requestUpload() + { + m_dirtyFlags |= TextureData; + } + + bool testDirtyFlag(DirtyFlag flag) + { + return m_dirtyFlags.testFlag(flag); + } + + void setDirtyFlag(DirtyFlag flag, bool value = true) + { + m_dirtyFlags.setFlag(flag, value); + } + + QOpenGLTexture *buildGLTexture(); + bool loadTextureDataFromGenerator(); + void loadTextureDataFromImages(); + void uploadGLTextureData(); + void updateGLTextureParameters(); + void introspectPropertiesFromSharedTextureId(); + void destroyResources(); + + QFlags m_dirtyFlags; + QMutex m_externalRenderingMutex; + QOpenGLTexture *m_gl; + RenderBuffer *m_renderBuffer; + + // target which is actually used for GL texture + TextureProperties m_properties; + TextureParameters m_parameters; + + QTextureGeneratorPtr m_dataFunctor; + QTextureGenerator *m_pendingDataFunctor; + QVector m_images; + + // cache actual image data generated by the functors + QTextureDataPtr m_textureData; + QVector m_imageData; + QVector m_pendingTextureDataUpdates; + + int m_sharedTextureId; + bool m_externalRendering; + bool m_wasTextureRecreated; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_GLTEXTURE_H diff --git a/src/plugins/renderers/opengl/textures/renderbuffer.cpp b/src/plugins/renderers/opengl/textures/renderbuffer.cpp new file mode 100644 index 000000000..bc5050f73 --- /dev/null +++ b/src/plugins/renderers/opengl/textures/renderbuffer.cpp @@ -0,0 +1,112 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderbuffer_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +RenderBuffer::RenderBuffer(int width, int height, QAbstractTexture::TextureFormat format) + : m_size(width, height), + m_format(format), + m_renderBuffer(0), + m_context(nullptr) +{ + QOpenGLContext *ctx = QOpenGLContext::currentContext(); + if (!ctx) { + qWarning("Renderbuffer requires an OpenGL context"); + return; + } + + m_context = ctx; + QOpenGLFunctions *f = ctx->functions(); + f->glGenRenderbuffers(1, &m_renderBuffer); + if (!m_renderBuffer) + return; + + f->glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer); + while (f->glGetError() != GL_NO_ERROR) { } + f->glRenderbufferStorage(GL_RENDERBUFFER, format, width, height); + GLint err = f->glGetError(); + if (err != GL_NO_ERROR) + qWarning("Failed to set renderbuffer storage: error 0x%x", err); + f->glBindRenderbuffer(GL_RENDERBUFFER, 0); +} + +RenderBuffer::~RenderBuffer() +{ + if (m_renderBuffer) { + QOpenGLContext *ctx = QOpenGLContext::currentContext(); + + // Ignore the fact that renderbuffers are sharable resources and let's + // just expect that the context is the same as when the resource was + // created. QOpenGLTexture suffers from the same limitation anyway, and + // this is unlikely to become an issue within Qt 3D. + if (ctx == m_context) { + ctx->functions()->glDeleteRenderbuffers(1, &m_renderBuffer); + } else { + qWarning("Wrong current context; renderbuffer not destroyed"); + } + } +} + +void RenderBuffer::bind() +{ + if (!m_renderBuffer) + return; + + m_context->functions()->glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer); +} + +void RenderBuffer::release() +{ + if (!m_context) + return; + + m_context->functions()->glBindRenderbuffer(GL_RENDERBUFFER, 0); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/plugins/renderers/opengl/textures/renderbuffer_p.h b/src/plugins/renderers/opengl/textures/renderbuffer_p.h new file mode 100644 index 000000000..7dc62492a --- /dev/null +++ b/src/plugins/renderers/opengl/textures/renderbuffer_p.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERBUFFER_P_H +#define QT3DRENDER_RENDER_RENDERBUFFER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +class QOpenGLContext; + +namespace Qt3DRender { +namespace Render { + +class Q_AUTOTEST_EXPORT RenderBuffer +{ +public: + RenderBuffer(int width, int height, QAbstractTexture::TextureFormat format); + ~RenderBuffer(); + + int width() const { return m_size.width(); } + int height() const { return m_size.height(); } + QSize size() const { return m_size; } + QAbstractTexture::TextureFormat format() const { return m_format; } + GLuint renderBufferId() const { return m_renderBuffer; } + + void bind(); + void release(); + +private: + QSize m_size; + QAbstractTexture::TextureFormat m_format; + GLuint m_renderBuffer; + QOpenGLContext *m_context; +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERBUFFER_P_H diff --git a/src/plugins/renderers/opengl/textures/textures.pri b/src/plugins/renderers/opengl/textures/textures.pri new file mode 100644 index 000000000..e17abfbb3 --- /dev/null +++ b/src/plugins/renderers/opengl/textures/textures.pri @@ -0,0 +1,9 @@ +INCLUDEPATH += $$PWD + +SOURCES += \ + $$PWD/gltexture.cpp \ + $$PWD/renderbuffer.cpp + +HEADERS += \ + $$PWD/gltexture_p.h \ + $$PWD/renderbuffer_p.h diff --git a/src/plugins/renderers/renderers.pro b/src/plugins/renderers/renderers.pro new file mode 100644 index 000000000..dc58bf7fc --- /dev/null +++ b/src/plugins/renderers/renderers.pro @@ -0,0 +1,9 @@ +TEMPLATE = subdirs + +# OpenGL renderer +include($$OUT_PWD/../../render/qt3drender-config.pri) +QT_FOR_CONFIG += 3drender-private + +#SUBDIRS += dummy + +qtConfig(qt3d-opengl-renderer): SUBDIRS += opengl diff --git a/src/quick3d/quick3dscene2d/items/scene2d.cpp b/src/quick3d/quick3dscene2d/items/scene2d.cpp index a2247705e..063464b95 100644 --- a/src/quick3d/quick3dscene2d/items/scene2d.cpp +++ b/src/quick3d/quick3dscene2d/items/scene2d.cpp @@ -45,12 +45,12 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include diff --git a/src/render/backend/apishadermanager_p.h b/src/render/backend/apishadermanager_p.h index ec17b2196..9ebf49710 100644 --- a/src/render/backend/apishadermanager_p.h +++ b/src/render/backend/apishadermanager_p.h @@ -169,7 +169,7 @@ public: return std::move(m_updatedShaders); } - QVector shaderIdsForProgram(GLShader *glShader) const + QVector shaderIdsForProgram(APIShader *glShader) const { QReadLocker lock(&m_readWriteLock); return m_apiShaders.value(glShader); diff --git a/src/render/backend/attachmentpack_p.h b/src/render/backend/attachmentpack_p.h index a3a2586dd..32ea774b6 100644 --- a/src/render/backend/attachmentpack_p.h +++ b/src/render/backend/attachmentpack_p.h @@ -52,6 +52,7 @@ // #include +#include #include QT_BEGIN_NAMESPACE @@ -59,7 +60,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { -struct Attachment +struct Q_3DRENDERSHARED_PRIVATE_EXPORT Attachment { Attachment() : m_mipLevel(0) @@ -80,7 +81,7 @@ class RenderTarget; class RenderTargetSelector; class AttachmentManager; -class AttachmentPack +class Q_3DRENDERSHARED_PRIVATE_EXPORT AttachmentPack { public: AttachmentPack(); diff --git a/src/render/backend/backendnode.cpp b/src/render/backend/backendnode.cpp index f85ece1b9..18e7af256 100644 --- a/src/render/backend/backendnode.cpp +++ b/src/render/backend/backendnode.cpp @@ -38,10 +38,11 @@ ****************************************************************************/ #include -#include +#include #include #include #include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/backend/cameralens.cpp b/src/render/backend/cameralens.cpp index e1d72efda..ab74e8b56 100644 --- a/src/render/backend/cameralens.cpp +++ b/src/render/backend/cameralens.cpp @@ -39,10 +39,11 @@ #include "cameralens_p.h" #include +#include #include #include #include -#include +#include #include #include #include diff --git a/src/render/backend/commandexecuter.cpp b/src/render/backend/commandexecuter.cpp deleted file mode 100644 index 8e45fb924..000000000 --- a/src/render/backend/commandexecuter.cpp +++ /dev/null @@ -1,391 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL3$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see http://www.qt.io/terms-conditions. For further -** information use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPLv3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or later as published by the Free -** Software Foundation and appearing in the file LICENSE.GPL included in -** the packaging of this file. Please review the following information to -** ensure the GNU General Public License version 2.0 requirements will be -** met: http://www.gnu.org/licenses/gpl-2.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "commandexecuter_p.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Debug { - -namespace { - -template -QJsonObject typeToJsonObj(const Type &) -{ - return QJsonObject(); -} - -template -QJsonValue typeToJsonValue(const Type &t) -{ - Q_UNUSED(t); - return QJsonValue(); -} - -template<> -QJsonObject typeToJsonObj(const QRectF &rect) -{ - QJsonObject obj; - - obj.insert(QLatin1String("x"), rect.x()); - obj.insert(QLatin1String("y"), rect.y()); - obj.insert(QLatin1String("width"), rect.width()); - obj.insert(QLatin1String("height"), rect.height()); - - return obj; -} - -template<> -QJsonValue typeToJsonValue(const QRectF &rect) -{ - QJsonArray value; - - value.push_back(rect.x()); - value.push_back(rect.y()); - value.push_back(rect.width()); - value.push_back(rect.height()); - - return value; -} - -template<> -QJsonObject typeToJsonObj(const QSize &s) -{ - QJsonObject obj; - - obj.insert(QLatin1String("width"), s.width()); - obj.insert(QLatin1String("height"), s.height()); - - return obj; -} - -template<> -QJsonValue typeToJsonValue(const QSize &s) -{ - QJsonArray value; - - value.push_back(s.width()); - value.push_back(s.height()); - - return value; -} - -template<> -QJsonObject typeToJsonObj(const QVector3D &v) -{ - QJsonObject obj; - - obj.insert(QLatin1String("x"), v.x()); - obj.insert(QLatin1String("y"), v.y()); - obj.insert(QLatin1String("z"), v.z()); - - return obj; -} - -template<> -QJsonValue typeToJsonValue(const QVector3D &v) -{ - QJsonArray value; - - value.push_back(v.x()); - value.push_back(v.y()); - value.push_back(v.z()); - - return value; -} - -template<> -QJsonObject typeToJsonObj(const Qt3DCore::QNodeId &v) -{ - QJsonObject obj; - obj.insert(QLatin1String("id"), qint64(v.id())); - return obj; -} - -template<> -QJsonValue typeToJsonValue(const Qt3DCore::QNodeId &v) -{ - QJsonValue value(qint64(v.id())); - return value; -} - -template<> -QJsonObject typeToJsonObj(const QVector4D &v) -{ - QJsonObject obj; - - obj.insert(QLatin1String("x"), v.x()); - obj.insert(QLatin1String("y"), v.y()); - obj.insert(QLatin1String("z"), v.z()); - obj.insert(QLatin1String("w"), v.w()); - - return obj; -} - -template<> -QJsonValue typeToJsonValue(const QVector4D &v) -{ - QJsonArray value; - - value.push_back(v.x()); - value.push_back(v.y()); - value.push_back(v.z()); - value.push_back(v.w()); - - return value; -} - -template<> -QJsonObject typeToJsonObj(const QMatrix4x4 &v) -{ - QJsonObject obj; - - obj.insert(QLatin1String("row 0"), typeToJsonObj(v.row(0))); - obj.insert(QLatin1String("row 1"), typeToJsonObj(v.row(0))); - obj.insert(QLatin1String("row 2"), typeToJsonObj(v.row(0))); - obj.insert(QLatin1String("row 3"), typeToJsonObj(v.row(0))); - - return obj; -} - -template<> -QJsonValue typeToJsonValue(const QMatrix4x4 &v) -{ - QJsonArray value; - - value.push_back(typeToJsonValue(v.row(0))); - value.push_back(typeToJsonValue(v.row(1))); - value.push_back(typeToJsonValue(v.row(2))); - value.push_back(typeToJsonValue(v.row(3))); - - return value; -} - -template<> -QJsonValue typeToJsonValue(const QVariant &v) -{ - const int nodeTypeId = qMetaTypeId(); - - if (v.userType() == nodeTypeId) - return typeToJsonValue(v.value()); - - switch (v.userType()) { - case QMetaType::QVector3D: - return typeToJsonValue(v.value()); - case QMetaType::QVector4D: - return typeToJsonValue(v.value()); - case QMetaType::QMatrix4x4: - return typeToJsonValue(v.value()); - default: - return QJsonValue::fromVariant(v); - } -} - -template -QJsonObject backendNodeToJSon(Handle handle, Manager *manager) -{ - Qt3DCore::QBackendNode *node = manager->data(handle); - QJsonObject obj; - Qt3DCore::QNodeId id; - if (node != nullptr) - id = node->peerId(); - obj.insert(QLatin1String("id"), qint64(id.id())); - return obj; -} - -QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) -{ - QJsonObject obj; - - const Render::PackUniformHash &uniforms = pack.uniforms(); - QJsonArray uniformsArray; - for (int i = 0, m = uniforms.keys.size(); i < m; ++i) { - QJsonObject uniformObj; - uniformObj.insert(QLatin1String("name"), Render::StringToInt::lookupString(uniforms.keys.at(i))); - const Render::UniformValue::ValueType type = uniforms.values.at(i).valueType(); - uniformObj.insert(QLatin1String("type"), - type == Render::UniformValue::ScalarValue - ? QLatin1String("value") - : QLatin1String("texture")); - uniformsArray.push_back(uniformObj); - } - obj.insert(QLatin1String("uniforms"), uniformsArray); - - QJsonArray texturesArray; - const QVector &textures = pack.textures(); - for (const auto & texture : textures) { - QJsonObject textureObj; - textureObj.insert(QLatin1String("name"), Render::StringToInt::lookupString(texture.glslNameId)); - textureObj.insert(QLatin1String("id"), qint64(texture.nodeId.id())); - texturesArray.push_back(textureObj); - } - obj.insert(QLatin1String("textures"), texturesArray); - - const QVector &ubos = pack.uniformBuffers(); - QJsonArray ubosArray; - for (const auto &ubo : ubos) { - QJsonObject uboObj; - uboObj.insert(QLatin1String("index"), ubo.m_blockIndex); - uboObj.insert(QLatin1String("bufferId"), qint64(ubo.m_bufferID.id())); - ubosArray.push_back(uboObj); - - } - obj.insert(QLatin1String("ubos"), ubosArray); - - const QVector &ssbos = pack.shaderStorageBuffers(); - QJsonArray ssbosArray; - for (const auto &ssbo : ssbos) { - QJsonObject ssboObj; - ssboObj.insert(QLatin1String("index"), ssbo.m_blockIndex); - ssboObj.insert(QLatin1String("bufferId"), qint64(ssbo.m_bufferID.id())); - ssbosArray.push_back(ssboObj); - } - obj.insert(QLatin1String("ssbos"), ssbosArray); - - return obj; -} - -} // anonymous - -CommandExecuter::CommandExecuter(Render::Renderer *renderer) - : m_renderer(renderer) -{ -} - -// Render thread -void CommandExecuter::performAsynchronousCommandExecution(const QVector &views) -{ - QMutexLocker lock(&m_pendingCommandsMutex); - const QVector shellCommands = std::move(m_pendingCommands); - lock.unlock(); - - for (auto *reply : shellCommands) { - if (reply->commandName() == QLatin1String("glinfo")) { - QJsonObject replyObj; - const GraphicsApiFilterData *contextInfo = m_renderer->submissionContext()->contextInfo(); - if (contextInfo != nullptr) { - replyObj.insert(QLatin1String("api"), - contextInfo->m_api == QGraphicsApiFilter::OpenGL - ? QLatin1String("OpenGL") - : QLatin1String("OpenGLES")); - const QString versionString = - QString::number(contextInfo->m_major) - + QStringLiteral(".") - + QString::number(contextInfo->m_minor); - replyObj.insert(QLatin1String("version"), versionString); - replyObj.insert(QLatin1String("profile"), - contextInfo->m_profile == QGraphicsApiFilter::CoreProfile - ? QLatin1String("Core") - : contextInfo->m_profile == QGraphicsApiFilter::CompatibilityProfile - ? QLatin1String("Compatibility") - : QLatin1String("None")); - } - reply->setData(QJsonDocument(replyObj).toJson()); - } else if (reply->commandName() == QLatin1String("rendercommands")) { - QJsonObject replyObj; - - QJsonArray viewArray; - for (Render::RenderView *v : views) { - QJsonObject viewObj; - viewObj.insert(QLatin1String("viewport"), typeToJsonValue(v->viewport())); - viewObj.insert(QLatin1String("surfaceSize"), typeToJsonValue(v->surfaceSize())); - viewObj.insert(QLatin1String("devicePixelRatio"), v->devicePixelRatio()); - viewObj.insert(QLatin1String("noDraw"), v->noDraw()); - viewObj.insert(QLatin1String("frustumCulling"), v->frustumCulling()); - viewObj.insert(QLatin1String("compute"), v->isCompute()); - viewObj.insert(QLatin1String("clearDepthValue"), v->clearDepthValue()); - viewObj.insert(QLatin1String("clearStencilValue"), v->clearStencilValue()); - - QJsonArray renderCommandsArray; - for (const Render::RenderCommand &c : v->commands()) { - QJsonObject commandObj; - Render::NodeManagers *nodeManagers = m_renderer->nodeManagers(); - commandObj.insert(QLatin1String("shader"), int(c.m_shaderId.id())); - commandObj.insert(QLatin1String("vao"), double(c.m_vao.handle())); - commandObj.insert(QLatin1String("instanceCount"), c.m_instanceCount); - commandObj.insert(QLatin1String("geometry"), backendNodeToJSon(c.m_geometry, nodeManagers->geometryManager())); - commandObj.insert(QLatin1String("geometryRenderer"), backendNodeToJSon(c.m_geometryRenderer, nodeManagers->geometryRendererManager())); - commandObj.insert(QLatin1String("shaderParameterPack"), parameterPackToJson(c.m_parameterPack)); - - renderCommandsArray.push_back(commandObj); - } - viewObj.insert(QLatin1String("commands"), renderCommandsArray); - viewArray.push_back(viewObj); - } - - replyObj.insert(QLatin1String("renderViews"), viewArray); - reply->setData(QJsonDocument(replyObj).toJson()); - } - reply->setFinished(true); - } -} - -// Main thread -QVariant CommandExecuter::executeCommand(const QStringList &args) -{ - // Note: The replies will be deleted by the AspectCommandDebugger - if (args.length() > 0 && - (args.first() == QLatin1String("glinfo") || - args.first() == QLatin1String("rendercommands"))) { - auto reply = new Qt3DCore::Debug::AsynchronousCommandReply(args.first()); - QMutexLocker lock(&m_pendingCommandsMutex); - m_pendingCommands.push_back(reply); - return QVariant::fromValue(reply); - } - return QVariant(); -} - -} // Debug - -} // Qt3DRenderer - -QT_END_NAMESPACE diff --git a/src/render/backend/commandexecuter_p.h b/src/render/backend/commandexecuter_p.h deleted file mode 100644 index 2d90bf4d6..000000000 --- a/src/render/backend/commandexecuter_p.h +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL3$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see http://www.qt.io/terms-conditions. For further -** information use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPLv3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or later as published by the Free -** Software Foundation and appearing in the file LICENSE.GPL included in -** the packaging of this file. Please review the following information to -** ensure the GNU General Public License version 2.0 requirements will be -** met: http://www.gnu.org/licenses/gpl-2.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_DEBUG_COMMANDEXECUTER_H -#define QT3DRENDER_DEBUG_COMMANDEXECUTER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DCore { - -namespace Debug { -class AsynchronousCommandReply; -} // Debug - -} // Qt3DCore - -namespace Qt3DRender { - -namespace Render { -class Renderer; -class RenderView; -} // Render - -namespace Debug { - -class CommandExecuter -{ -public: - explicit CommandExecuter(Render::Renderer *renderer); - - void performAsynchronousCommandExecution(const QVector &views); - - QVariant executeCommand(const QStringList &args); - -private: - Render::Renderer *m_renderer; - QVector m_pendingCommands; - QMutex m_pendingCommandsMutex; -}; - -} // Debug - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_DEBUG_COMMANDEXECUTER_H diff --git a/src/render/backend/computecommand_p.h b/src/render/backend/computecommand_p.h index 5012930ae..00e238474 100644 --- a/src/render/backend/computecommand_p.h +++ b/src/render/backend/computecommand_p.h @@ -62,7 +62,7 @@ namespace Render { class ComputeJobPrivate; -class Q_AUTOTEST_EXPORT ComputeCommand : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT ComputeCommand : public BackendNode { public: ComputeCommand(); diff --git a/src/render/backend/entity_p.h b/src/render/backend/entity_p.h index d13d96784..8ac10454e 100644 --- a/src/render/backend/entity_p.h +++ b/src/render/backend/entity_p.h @@ -53,7 +53,7 @@ // #include -#include +#include #include #include #include @@ -81,7 +81,7 @@ class Renderer; class NodeManagers; class EntityPrivate; -class Q_AUTOTEST_EXPORT Entity : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Entity : public BackendNode { public: Entity(); diff --git a/src/render/backend/levelofdetail_p.h b/src/render/backend/levelofdetail_p.h index 8399e19b7..b559b3114 100644 --- a/src/render/backend/levelofdetail_p.h +++ b/src/render/backend/levelofdetail_p.h @@ -67,7 +67,7 @@ namespace Render { class LevelOfDetailManager; -class Q_AUTOTEST_EXPORT LevelOfDetail : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT LevelOfDetail : public BackendNode { public: LevelOfDetail(); diff --git a/src/render/backend/managers_p.h b/src/render/backend/managers_p.h index 24b161b6e..db12a8a7b 100644 --- a/src/render/backend/managers_p.h +++ b/src/render/backend/managers_p.h @@ -91,7 +91,7 @@ namespace Qt3DRender { namespace Render { -class AttachmentManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT AttachmentManager : public Qt3DCore::QResourceManager< RenderTargetOutput, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -100,7 +100,7 @@ public: AttachmentManager() {} }; -class CameraManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT CameraManager : public Qt3DCore::QResourceManager< CameraLens, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -109,7 +109,7 @@ public: CameraManager() {} }; -class FilterKeyManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT FilterKeyManager : public Qt3DCore::QResourceManager< FilterKey, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -119,7 +119,7 @@ public: FilterKeyManager() {} }; -class EffectManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT EffectManager : public Qt3DCore::QResourceManager< Effect, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -128,7 +128,7 @@ public: EffectManager() {} }; -class Q_AUTOTEST_EXPORT EntityManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT EntityManager : public Qt3DCore::QResourceManager< Entity, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -146,7 +146,7 @@ public: class FrameGraphNode; -class Q_AUTOTEST_EXPORT FrameGraphManager +class Q_3DRENDERSHARED_PRIVATE_EXPORT FrameGraphManager { public: FrameGraphManager() {} @@ -161,7 +161,7 @@ private: QHash m_nodes; }; -class LayerManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT LayerManager : public Qt3DCore::QResourceManager< Layer, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -170,7 +170,7 @@ public: LayerManager() {} }; -class LevelOfDetailManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT LevelOfDetailManager : public Qt3DCore::QResourceManager< LevelOfDetail, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -179,7 +179,7 @@ public: LevelOfDetailManager() {} }; -class MaterialManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT MaterialManager : public Qt3DCore::QResourceManager< Material, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -188,7 +188,7 @@ public: MaterialManager() {} }; -class MatrixManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT MatrixManager : public Qt3DCore::QResourceManager< Matrix4x4, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -197,7 +197,7 @@ public: MatrixManager() {} }; -class ShaderManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderManager : public Qt3DCore::QResourceManager< Shader, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -221,7 +221,7 @@ private: QVector m_shaderIdsToCleanup; }; -class ShaderBuilderManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderBuilderManager : public Qt3DCore::QResourceManager< ShaderBuilder, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -230,7 +230,7 @@ public: ShaderBuilderManager() {} }; -class TextureManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT TextureManager : public Qt3DCore::QResourceManager< Texture, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -269,7 +269,7 @@ private: QVector m_textureIdsToCleanup; }; -class TransformManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT TransformManager : public Qt3DCore::QResourceManager< Transform, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -278,7 +278,7 @@ public: TransformManager() {} }; -class RenderTargetManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderTargetManager : public Qt3DCore::QResourceManager< RenderTarget, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -287,7 +287,7 @@ public: RenderTargetManager() {} }; -class RenderPassManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderPassManager : public Qt3DCore::QResourceManager< RenderPass, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -297,7 +297,7 @@ public: }; -class ParameterManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ParameterManager : public Qt3DCore::QResourceManager< Parameter, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -306,7 +306,7 @@ public: ParameterManager() {} }; -class ShaderImageManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderImageManager : public Qt3DCore::QResourceManager< ShaderImage, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -315,7 +315,7 @@ public: ShaderImageManager() {} }; -class ShaderDataManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderDataManager : public Qt3DCore::QResourceManager< ShaderData, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -324,35 +324,35 @@ public: ShaderDataManager() {} }; -class TextureImageManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT TextureImageManager : public Qt3DCore::QResourceManager< TextureImage, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> { }; -class AttributeManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT AttributeManager : public Qt3DCore::QResourceManager< Attribute, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> { }; -class GeometryManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT GeometryManager : public Qt3DCore::QResourceManager< Geometry, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> { }; -class ObjectPickerManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ObjectPickerManager : public Qt3DCore::QResourceManager< ObjectPicker, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> { }; -class RayCasterManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT RayCasterManager : public Qt3DCore::QResourceManager< RayCaster, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -368,7 +368,7 @@ class BoundingVolumeDebugManager : public Qt3DCore::QResourceManager< }; #endif -class LightManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT LightManager : public Qt3DCore::QResourceManager< Light, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -377,7 +377,7 @@ public: LightManager() {} }; -class EnvironmentLightManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT EnvironmentLightManager : public Qt3DCore::QResourceManager< EnvironmentLight, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -386,7 +386,7 @@ public: EnvironmentLightManager() {} }; -class ComputeCommandManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ComputeCommandManager : public Qt3DCore::QResourceManager< ComputeCommand, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -395,21 +395,21 @@ public: ComputeCommandManager() {} }; -class RenderStateManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderStateManager : public Qt3DCore::QResourceManager< RenderStateNode, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> { }; -class ArmatureManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT ArmatureManager : public Qt3DCore::QResourceManager< Armature, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> { }; -class SkeletonManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT SkeletonManager : public Qt3DCore::QResourceManager< Skeleton, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> @@ -428,7 +428,7 @@ private: QVector m_dirtyTransformSkeletons; }; -class JointManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT JointManager : public Qt3DCore::QResourceManager< Joint, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> diff --git a/src/render/backend/offscreensurfacehelper_p.h b/src/render/backend/offscreensurfacehelper_p.h index 8dc86d9a4..6ec82db2f 100644 --- a/src/render/backend/offscreensurfacehelper_p.h +++ b/src/render/backend/offscreensurfacehelper_p.h @@ -52,6 +52,7 @@ // #include +#include QT_BEGIN_NAMESPACE @@ -62,7 +63,7 @@ namespace Render { class AbstractRenderer; -class Q_AUTOTEST_EXPORT OffscreenSurfaceHelper : public QObject +class Q_3DRENDERSHARED_PRIVATE_EXPORT OffscreenSurfaceHelper : public QObject { Q_OBJECT public: diff --git a/src/render/backend/platformsurfacefilter.cpp b/src/render/backend/platformsurfacefilter.cpp index 891e30c44..115fb637f 100644 --- a/src/render/backend/platformsurfacefilter.cpp +++ b/src/render/backend/platformsurfacefilter.cpp @@ -39,7 +39,7 @@ #include "platformsurfacefilter_p.h" -#include +#include #include #include diff --git a/src/render/backend/platformsurfacefilter_p.h b/src/render/backend/platformsurfacefilter_p.h index 4fb43bae1..0bb425989 100644 --- a/src/render/backend/platformsurfacefilter_p.h +++ b/src/render/backend/platformsurfacefilter_p.h @@ -67,7 +67,7 @@ namespace Render { class AbstractRenderer; -class PlatformSurfaceFilter : public QObject +class Q_3DRENDERSHARED_PRIVATE_EXPORT PlatformSurfaceFilter : public QObject { Q_OBJECT diff --git a/src/render/backend/qgraphicsutils_p.h b/src/render/backend/qgraphicsutils_p.h deleted file mode 100644 index 40ff99f0e..000000000 --- a/src/render/backend/qgraphicsutils_p.h +++ /dev/null @@ -1,410 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H -#define QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -namespace { - -const int QMatrix2x2Type = qMetaTypeId(); -const int QMatrix2x3Type = qMetaTypeId(); -const int QMatrix2x4Type = qMetaTypeId(); -const int QMatrix3x2Type = qMetaTypeId(); -const int QMatrix3x3Type = qMetaTypeId(); -const int QMatrix3x4Type = qMetaTypeId(); -const int QMatrix4x2Type = qMetaTypeId(); -const int QMatrix4x3Type = qMetaTypeId(); - -} - -class QGraphicsUtils -{ - -public: - - template - static const char *bytesFromVariant(const QVariant &v) - { - uint byteSize = sizeof(T); - // Max 16 float that we may want as doubles - // 64 should be best for most cases - static QVarLengthArray array(16 * byteSize); - memset(array.data(), 0, array.size()); - - switch (static_cast(v.type())) { - - // 1 byte - case QMetaType::Bool: { - T data = v.value(); - memcpy(array.data(), &data, byteSize); - break; - } - case QMetaType::Char: { - T data = v.value(); - memcpy(array.data(), &data, byteSize); - break; - } - - // 4 bytes - case QMetaType::Float: { - T data = v.value(); - memcpy(array.data(), &data, byteSize); - break; - } - case QMetaType::Int: { - T data = v.value(); - memcpy(array.data(), &data, byteSize); - break; - - } - case QMetaType::UInt: { - qDebug() << "UINT"; - T data = v.value(); - memcpy(array.data(), &data, byteSize); - break; - } - - // 8 bytes - case QMetaType::Double: { - T data = v.value(); - memcpy(array.data(), &data, byteSize); - break; - } - - // 2 floats - case QMetaType::QPointF: { - QPointF vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - break; - } - case QMetaType::QSizeF: { - QSizeF vv = v.value(); - T data = vv.width(); - memcpy(array.data(), &data, byteSize); - data = vv.height(); - memcpy(array.data() + byteSize, &data, byteSize); - break; - } - - case QMetaType::QVector2D: { - QVector2D vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - break; - } - - // 2 ints - case QMetaType::QPoint: { - QPointF vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - break; - } - - case QMetaType::QSize: { - QSize vv = v.value(); - T data = vv.width(); - memcpy(array.data(), &data, byteSize); - data = vv.height(); - memcpy(array.data() + byteSize, &data, byteSize); - break; - } - - // 3 floats - case QMetaType::QVector3D: { - QVector3D vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - data = vv.z(); - memcpy(array.data() + 2 * byteSize, &data, byteSize); - break; - } - - // 4 floats - case QMetaType::QVector4D: { - QVector4D vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - data = vv.z(); - memcpy(array.data() + 2 * byteSize, &data, byteSize); - data = vv.w(); - memcpy(array.data() + 3 * byteSize, &data, byteSize); - break; - } - - case QMetaType::QQuaternion: { - - break; - } - - case QMetaType::QRectF: { - QRectF vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - data = vv.width(); - memcpy(array.data() + 2 * byteSize, &data, byteSize); - data = vv.height(); - memcpy(array.data() + 3 * byteSize, &data, byteSize); - break; - } - - case QMetaType::QColor: { - QColor vv = v.value(); - T data = vv.redF(); - memcpy(array.data(), &data, byteSize); - data = vv.greenF(); - memcpy(array.data() + byteSize, &data, byteSize); - data = vv.blueF(); - memcpy(array.data() + 2 * byteSize, &data, byteSize); - data = vv.alphaF(); - memcpy(array.data() + 3 * byteSize, &data, byteSize); - break; - } - - // 4 ints - case QMetaType::QRect: { - QRectF vv = v.value(); - T data = vv.x(); - memcpy(array.data(), &data, byteSize); - data = vv.y(); - memcpy(array.data() + byteSize, &data, byteSize); - data = vv.width(); - memcpy(array.data() + 2 * byteSize, &data, byteSize); - data = vv.height(); - memcpy(array.data() + 3 * byteSize, &data, byteSize); - break; - } - - // 16 floats - case QMetaType::QMatrix4x4: { - QMatrix4x4 mat = v.value(); - float *data = mat.data(); - for (int i = 0; i < 16; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - break; - } - - default: { - - float *data = nullptr; - if (v.userType() == QMatrix3x3Type) { - QMatrix3x3 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 9; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix2x2Type) { - QMatrix2x2 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 4; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix2x3Type) { - QMatrix2x3 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 6; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix3x2Type) { - QMatrix3x2 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 6; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix2x4Type) { - QMatrix2x4 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 8; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix4x2Type) { - QMatrix4x2 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 8; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix3x4Type) { - QMatrix3x4 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 12; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else if (v.userType() == QMatrix4x3Type) { - QMatrix4x3 mat = v.value(); - data = mat.data(); - for (int i = 0; i < 12; i++) { - T d = data[i]; - memcpy(array.data() + i * byteSize, &d, byteSize); - } - } - else - qWarning() << Q_FUNC_INFO << "QVariant type conversion not handled for " << v.type(); - break; - } - - } - return array.constData(); - } - - - template - static const T *valueArrayFromVariant(const QVariant &v, int count, int tupleSize) - { - uint byteSize = sizeof(T); - uint offset = byteSize * tupleSize; - static QVarLengthArray uniformValuesArray(1024); - uniformValuesArray.resize(count * offset); - char *data = uniformValuesArray.data(); - memset(data, 0, uniformValuesArray.size()); - - QVariantList vList = v.toList(); - // Handles list of QVariant: usually arrays of float - if (!vList.isEmpty()) { - for (int i = 0; i < vList.length() && uint(i) * offset < uint(uniformValuesArray.size()); i++) { - const char *subBuffer = QGraphicsUtils::bytesFromVariant(vList.at(i)); - memcpy(data + i * offset, subBuffer, offset); - } - } - else { - memcpy(data, QGraphicsUtils::bytesFromVariant(v), offset); - } - return reinterpret_cast(uniformValuesArray.constData()); - } - - template - static void fillDataArray(void *buffer, const T *data, const ShaderUniform &description, int tupleSize) - { - uint offset = description.m_offset / sizeof(T); - uint stride = description.m_arrayStride / sizeof(T); - T *bufferData = (T*)buffer; - - for (int i = 0; i < description.m_size; ++i) { - for (int j = 0; j < tupleSize; j++) { - int idx = i * tupleSize + j; - bufferData[offset + j] = data[idx]; - } - offset += stride; - } - } - - template - static void fillDataMatrixArray(void *buffer, const T *data, const ShaderUniform &description, int cols, int rows) - { - uint offset = description.m_offset / sizeof(T); - uint arrayStride = description.m_arrayStride / sizeof(T); - uint matrixStride = description.m_matrixStride / sizeof(T); - T *bufferData = (T*)buffer; - - for (int i = 0; i < description.m_size; ++i) { - for (int col = 0; col < cols; ++col) { - for (int row = 0; row < rows; ++row) { - int idx = i * cols * rows + rows * col + row; - bufferData[offset + row] = data[idx]; - } - offset += matrixStride; - } - offset += arrayStride; - } - } - -}; - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H diff --git a/src/render/backend/render-backend.pri b/src/render/backend/render-backend.pri index 87083312f..2815ee0ab 100644 --- a/src/render/backend/render-backend.pri +++ b/src/render/backend/render-backend.pri @@ -5,7 +5,6 @@ HEADERS += \ $$PWD/parameterpack_p.h \ $$PWD/rendertarget_p.h \ $$PWD/attachmentpack_p.h \ - $$PWD/qgraphicsutils_p.h \ $$PWD/managers_p.h \ $$PWD/handle_types_p.h \ $$PWD/platformsurfacefilter_p.h \ @@ -38,7 +37,6 @@ HEADERS += \ $$PWD/visitorutils_p.h \ $$PWD/segmentsvisitor_p.h \ $$PWD/pointsvisitor_p.h \ - $$PWD/commandexecuter_p.h \ $$PWD/apishadermanager_p.h SOURCES += \ @@ -69,5 +67,4 @@ SOURCES += \ $$PWD/offscreensurfacehelper.cpp \ $$PWD/resourceaccessor.cpp \ $$PWD/segmentsvisitor.cpp \ - $$PWD/pointsvisitor.cpp \ - $$PWD/commandexecuter.cpp + $$PWD/pointsvisitor.cpp diff --git a/src/render/backend/rendersettings_p.h b/src/render/backend/rendersettings_p.h index 317fca957..af1ee58ec 100644 --- a/src/render/backend/rendersettings_p.h +++ b/src/render/backend/rendersettings_p.h @@ -62,7 +62,7 @@ namespace Render { class AbstractRenderer; -class Q_AUTOTEST_EXPORT RenderSettings : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderSettings : public BackendNode { public: RenderSettings(); diff --git a/src/render/backend/rendertarget_p.h b/src/render/backend/rendertarget_p.h index 30769dcfc..eeaf94940 100644 --- a/src/render/backend/rendertarget_p.h +++ b/src/render/backend/rendertarget_p.h @@ -65,7 +65,7 @@ namespace Render { class RenderTargetManager; -class Q_AUTOTEST_EXPORT RenderTarget : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderTarget : public BackendNode { public: RenderTarget(); diff --git a/src/render/backend/rendertargetoutput_p.h b/src/render/backend/rendertargetoutput_p.h index d72f6d231..3a8828eeb 100644 --- a/src/render/backend/rendertargetoutput_p.h +++ b/src/render/backend/rendertargetoutput_p.h @@ -65,7 +65,7 @@ namespace Render { class AttachmentManager; -class RenderTargetOutput : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderTargetOutput : public BackendNode { public: RenderTargetOutput(); diff --git a/src/render/backend/renderthread_p.h b/src/render/backend/renderthread_p.h index 56a7ec3bc..cdbb4f8c5 100644 --- a/src/render/backend/renderthread_p.h +++ b/src/render/backend/renderthread_p.h @@ -52,7 +52,7 @@ // #include - +#include #include QT_BEGIN_NAMESPACE @@ -63,7 +63,7 @@ namespace Render { class AbstractRenderer; -class Q_AUTOTEST_EXPORT RenderThread : public QThread +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderThread : public QThread { Q_OBJECT public: diff --git a/src/render/backend/resourceaccessor.cpp b/src/render/backend/resourceaccessor.cpp index 846caca58..ebc55c7ca 100644 --- a/src/render/backend/resourceaccessor.cpp +++ b/src/render/backend/resourceaccessor.cpp @@ -40,7 +40,6 @@ #include #include -#include #include #include diff --git a/src/render/backend/stringtoint_p.h b/src/render/backend/stringtoint_p.h index 996cecf33..1aa6f0b08 100644 --- a/src/render/backend/stringtoint_p.h +++ b/src/render/backend/stringtoint_p.h @@ -54,6 +54,7 @@ #include #include +#include QT_BEGIN_NAMESPACE @@ -61,7 +62,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT StringToInt +class Q_3DRENDERSHARED_PRIVATE_EXPORT StringToInt { public: static int lookupId(const QString &str); diff --git a/src/render/backend/transform_p.h b/src/render/backend/transform_p.h index 8c0cd826a..3023a19d1 100644 --- a/src/render/backend/transform_p.h +++ b/src/render/backend/transform_p.h @@ -65,7 +65,7 @@ namespace Render { class Renderer; class TransformManager; -class Q_AUTOTEST_EXPORT Transform : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Transform : public BackendNode { public: Transform(); diff --git a/src/render/backend/uniform_p.h b/src/render/backend/uniform_p.h index c8731637c..eb959923a 100644 --- a/src/render/backend/uniform_p.h +++ b/src/render/backend/uniform_p.h @@ -56,7 +56,7 @@ #include #include #include - +#include #include #include #include @@ -105,7 +105,7 @@ enum UniformType { Unknown }; -class Q_AUTOTEST_EXPORT UniformValue +class Q_3DRENDERSHARED_PRIVATE_EXPORT UniformValue { public: enum ValueType { @@ -238,7 +238,7 @@ private: }; template<> -Q_AUTOTEST_EXPORT void UniformValue::setData(const QVector &v); +Q_3DRENDERSHARED_PRIVATE_EXPORT void UniformValue::setData(const QVector &v); } // namespace Render } // namespace Qt3DRender diff --git a/src/render/framegraph/blitframebuffer_p.h b/src/render/framegraph/blitframebuffer_p.h index fa9ddacd9..773833eb5 100644 --- a/src/render/framegraph/blitframebuffer_p.h +++ b/src/render/framegraph/blitframebuffer_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT BlitFramebuffer : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT BlitFramebuffer : public FrameGraphNode { public: BlitFramebuffer(); diff --git a/src/render/framegraph/buffercapture_p.h b/src/render/framegraph/buffercapture_p.h index d638f35d5..dfade50eb 100644 --- a/src/render/framegraph/buffercapture_p.h +++ b/src/render/framegraph/buffercapture_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT BufferCapture : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT BufferCapture : public FrameGraphNode { public: BufferCapture(); diff --git a/src/render/framegraph/cameraselectornode.cpp b/src/render/framegraph/cameraselectornode.cpp index 3beb0ef71..00772c502 100644 --- a/src/render/framegraph/cameraselectornode.cpp +++ b/src/render/framegraph/cameraselectornode.cpp @@ -39,7 +39,8 @@ #include "cameraselectornode_p.h" #include -#include +#include +#include #include #include diff --git a/src/render/framegraph/cameraselectornode_p.h b/src/render/framegraph/cameraselectornode_p.h index dd7e050d0..24590f960 100644 --- a/src/render/framegraph/cameraselectornode_p.h +++ b/src/render/framegraph/cameraselectornode_p.h @@ -64,7 +64,7 @@ namespace Render { class Renderer; -class CameraSelector : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT CameraSelector : public FrameGraphNode { public: CameraSelector(); diff --git a/src/render/framegraph/clearbuffers_p.h b/src/render/framegraph/clearbuffers_p.h index ca55d2a98..746d58da7 100644 --- a/src/render/framegraph/clearbuffers_p.h +++ b/src/render/framegraph/clearbuffers_p.h @@ -62,7 +62,7 @@ namespace Render { class FrameGraphManager; -class ClearBuffers : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT ClearBuffers : public FrameGraphNode { public: ClearBuffers(); diff --git a/src/render/framegraph/dispatchcompute_p.h b/src/render/framegraph/dispatchcompute_p.h index 24a641938..7df8db1da 100644 --- a/src/render/framegraph/dispatchcompute_p.h +++ b/src/render/framegraph/dispatchcompute_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class DispatchCompute : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT DispatchCompute : public FrameGraphNode { public: DispatchCompute(); diff --git a/src/render/framegraph/framegraphnode.cpp b/src/render/framegraph/framegraphnode.cpp index 40d8fca3d..92116af7d 100644 --- a/src/render/framegraph/framegraphnode.cpp +++ b/src/render/framegraph/framegraphnode.cpp @@ -38,7 +38,7 @@ ****************************************************************************/ #include "framegraphnode_p.h" -#include +#include #include #include diff --git a/src/render/framegraph/framegraphnode_p.h b/src/render/framegraph/framegraphnode_p.h index 55bede5fd..92d7ae2f1 100644 --- a/src/render/framegraph/framegraphnode_p.h +++ b/src/render/framegraph/framegraphnode_p.h @@ -74,7 +74,7 @@ namespace Render { class FrameGraphManager; -class Q_AUTOTEST_EXPORT FrameGraphNode : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT FrameGraphNode : public BackendNode { public: FrameGraphNode(); diff --git a/src/render/framegraph/framegraphvisitor.cpp b/src/render/framegraph/framegraphvisitor.cpp index 9af0297a0..b0eb1ac00 100644 --- a/src/render/framegraph/framegraphvisitor.cpp +++ b/src/render/framegraph/framegraphvisitor.cpp @@ -42,7 +42,7 @@ #include "framegraphnode_p.h" #include "subtreeenabler_p.h" -#include +#include #include #include diff --git a/src/render/framegraph/framegraphvisitor_p.h b/src/render/framegraph/framegraphvisitor_p.h index 5706a169d..0bb6cf0d4 100644 --- a/src/render/framegraph/framegraphvisitor_p.h +++ b/src/render/framegraph/framegraphvisitor_p.h @@ -54,6 +54,7 @@ #include #include +#include #include @@ -66,7 +67,7 @@ class FrameGraphNode; class Renderer; class FrameGraphManager; -class Q_AUTOTEST_EXPORT FrameGraphVisitor +class Q_3DRENDERSHARED_PRIVATE_EXPORT FrameGraphVisitor { public: explicit FrameGraphVisitor(const FrameGraphManager *nodeManager); diff --git a/src/render/framegraph/frustumculling_p.h b/src/render/framegraph/frustumculling_p.h index 7f9959c6e..ac11b7306 100644 --- a/src/render/framegraph/frustumculling_p.h +++ b/src/render/framegraph/frustumculling_p.h @@ -59,7 +59,7 @@ namespace Qt3DRender { namespace Render { -class FrustumCulling : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT FrustumCulling : public FrameGraphNode { public: FrustumCulling(); diff --git a/src/render/framegraph/layerfilternode_p.h b/src/render/framegraph/layerfilternode_p.h index 27cdc49d3..f075d5ec4 100644 --- a/src/render/framegraph/layerfilternode_p.h +++ b/src/render/framegraph/layerfilternode_p.h @@ -64,7 +64,7 @@ namespace Render { class Renderer; -class LayerFilterNode : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT LayerFilterNode : public FrameGraphNode { public: LayerFilterNode(); diff --git a/src/render/framegraph/memorybarrier_p.h b/src/render/framegraph/memorybarrier_p.h index ce545cd09..78bb91c40 100644 --- a/src/render/framegraph/memorybarrier_p.h +++ b/src/render/framegraph/memorybarrier_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT MemoryBarrier : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT MemoryBarrier : public FrameGraphNode { public: MemoryBarrier(); diff --git a/src/render/framegraph/nodraw_p.h b/src/render/framegraph/nodraw_p.h index ae9fa6713..ace625250 100644 --- a/src/render/framegraph/nodraw_p.h +++ b/src/render/framegraph/nodraw_p.h @@ -59,7 +59,7 @@ namespace Qt3DRender { namespace Render { -class NoDraw : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT NoDraw : public FrameGraphNode { public: NoDraw(); diff --git a/src/render/framegraph/proximityfilter_p.h b/src/render/framegraph/proximityfilter_p.h index 5c2f7ad66..27d89f76d 100644 --- a/src/render/framegraph/proximityfilter_p.h +++ b/src/render/framegraph/proximityfilter_p.h @@ -59,7 +59,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT ProximityFilter : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT ProximityFilter : public FrameGraphNode { public: ProximityFilter(); diff --git a/src/render/framegraph/rendercapture_p.h b/src/render/framegraph/rendercapture_p.h index 5714fb44d..f2a2a55b7 100644 --- a/src/render/framegraph/rendercapture_p.h +++ b/src/render/framegraph/rendercapture_p.h @@ -57,7 +57,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT RenderCapture : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderCapture : public FrameGraphNode { public: RenderCapture(); diff --git a/src/render/framegraph/renderpassfilternode_p.h b/src/render/framegraph/renderpassfilternode_p.h index 157a162bb..c9084573e 100644 --- a/src/render/framegraph/renderpassfilternode_p.h +++ b/src/render/framegraph/renderpassfilternode_p.h @@ -67,7 +67,7 @@ class QHandle; namespace Render { -class RenderPassFilter : public Render::FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderPassFilter : public Render::FrameGraphNode { public: RenderPassFilter(); diff --git a/src/render/framegraph/rendersurfaceselector.cpp b/src/render/framegraph/rendersurfaceselector.cpp index a1e639df5..c7e46efa7 100644 --- a/src/render/framegraph/rendersurfaceselector.cpp +++ b/src/render/framegraph/rendersurfaceselector.cpp @@ -40,7 +40,6 @@ #include "rendersurfaceselector_p.h" #include #include - #include #include #include diff --git a/src/render/framegraph/rendersurfaceselector_p.h b/src/render/framegraph/rendersurfaceselector_p.h index f1a139e84..3378ececa 100644 --- a/src/render/framegraph/rendersurfaceselector_p.h +++ b/src/render/framegraph/rendersurfaceselector_p.h @@ -60,7 +60,7 @@ class QSurface; namespace Qt3DRender { namespace Render { -class RenderSurfaceSelector : public Qt3DRender::Render::FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderSurfaceSelector : public Qt3DRender::Render::FrameGraphNode { public: RenderSurfaceSelector(); diff --git a/src/render/framegraph/rendertargetselectornode.cpp b/src/render/framegraph/rendertargetselectornode.cpp index 614a749a5..f32b8c7d9 100644 --- a/src/render/framegraph/rendertargetselectornode.cpp +++ b/src/render/framegraph/rendertargetselectornode.cpp @@ -38,7 +38,6 @@ ****************************************************************************/ #include "rendertargetselectornode_p.h" -#include #include #include #include diff --git a/src/render/framegraph/rendertargetselectornode_p.h b/src/render/framegraph/rendertargetselectornode_p.h index 232ee9ecc..04032045a 100644 --- a/src/render/framegraph/rendertargetselectornode_p.h +++ b/src/render/framegraph/rendertargetselectornode_p.h @@ -61,7 +61,7 @@ class QRenderTargetSelector; namespace Render { -class RenderTargetSelector : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderTargetSelector : public FrameGraphNode { public: RenderTargetSelector(); diff --git a/src/render/framegraph/setfence_p.h b/src/render/framegraph/setfence_p.h index 31072581c..0f54d65ee 100644 --- a/src/render/framegraph/setfence_p.h +++ b/src/render/framegraph/setfence_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT SetFence : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT SetFence : public FrameGraphNode { public: SetFence(); diff --git a/src/render/framegraph/sortpolicy_p.h b/src/render/framegraph/sortpolicy_p.h index 8d572ead7..2015adf87 100644 --- a/src/render/framegraph/sortpolicy_p.h +++ b/src/render/framegraph/sortpolicy_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT SortPolicy : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT SortPolicy : public FrameGraphNode { public: SortPolicy(); diff --git a/src/render/framegraph/statesetnode_p.h b/src/render/framegraph/statesetnode_p.h index 5081f3215..618b52338 100644 --- a/src/render/framegraph/statesetnode_p.h +++ b/src/render/framegraph/statesetnode_p.h @@ -59,7 +59,7 @@ namespace Qt3DRender { namespace Render { -class StateSetNode : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT StateSetNode : public FrameGraphNode { public: StateSetNode(); diff --git a/src/render/framegraph/subtreeenabler.cpp b/src/render/framegraph/subtreeenabler.cpp index 4d912dc1d..37989df1a 100644 --- a/src/render/framegraph/subtreeenabler.cpp +++ b/src/render/framegraph/subtreeenabler.cpp @@ -39,7 +39,6 @@ #include "subtreeenabler_p.h" #include -#include QT_BEGIN_NAMESPACE diff --git a/src/render/framegraph/techniquefilternode_p.h b/src/render/framegraph/techniquefilternode_p.h index e424e37e5..2e71e31d4 100644 --- a/src/render/framegraph/techniquefilternode_p.h +++ b/src/render/framegraph/techniquefilternode_p.h @@ -70,7 +70,7 @@ class QHandle; namespace Render { -class TechniqueFilter +class Q_3DRENDERSHARED_PRIVATE_EXPORT TechniqueFilter : public FrameGraphNode { public: diff --git a/src/render/framegraph/viewportnode_p.h b/src/render/framegraph/viewportnode_p.h index 3e291a9da..f673b1e21 100644 --- a/src/render/framegraph/viewportnode_p.h +++ b/src/render/framegraph/viewportnode_p.h @@ -64,7 +64,7 @@ namespace Render { class Renderer; -class Q_AUTOTEST_EXPORT ViewportNode : public FrameGraphNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT ViewportNode : public FrameGraphNode { public: ViewportNode(); diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index d8551fd1b..da5abe4ac 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -41,7 +41,7 @@ #include "qrenderaspect_p.h" #include -#include +#include #include #include @@ -56,8 +56,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -103,7 +105,7 @@ #include #include #include -#include +#include #include #include #include @@ -165,6 +167,8 @@ #include #include +#include + #include #include @@ -599,8 +603,9 @@ void QRenderAspect::onRegistered() Q_D(QRenderAspect); d->m_nodeManagers = new Render::NodeManagers(); - // TO DO: Load proper Renderer class based on Qt configuration preferences - d->m_renderer = new Render::Renderer(d->m_renderType); + // Load proper Renderer class based on Qt configuration preferences + d->m_renderer = d->loadRendererPlugin(); + Q_ASSERT(d->m_renderer); d->m_renderer->setScreen(d->m_screen); d->m_renderer->setNodeManagers(d->m_nodeManagers); @@ -689,6 +694,20 @@ void QRenderAspectPrivate::loadSceneParsers() } } +Render::AbstractRenderer *QRenderAspectPrivate::loadRendererPlugin() +{ + // Note: for now we load the first renderer plugin that is successfully loaded + // In the future we might want to offer the user a way to hint at which renderer + // plugin would best be loaded + const QStringList keys = Render::QRendererPluginFactory::keys(); + for (const QString &key : keys) { + Render::AbstractRenderer *renderer = Render::QRendererPluginFactory::create(key, m_renderType); + if (renderer) + return renderer; + } + return nullptr; +} + void QRenderAspectPrivate::loadRenderPlugin(const QString &pluginName) { Q_Q(QRenderAspect); diff --git a/src/render/frontend/qrenderaspect_p.h b/src/render/frontend/qrenderaspect_p.h index 0a9f4ec46..0eb04cee9 100644 --- a/src/render/frontend/qrenderaspect_p.h +++ b/src/render/frontend/qrenderaspect_p.h @@ -99,6 +99,7 @@ public: void renderShutdown(); void registerBackendType(const QMetaObject &, const Qt3DCore::QBackendNodeMapperPtr &functor); QVector createGeometryRendererJobs(); + Render::AbstractRenderer *loadRendererPlugin(); Render::NodeManagers *m_nodeManagers; Render::AbstractRenderer *m_renderer; diff --git a/src/render/frontend/sphere_p.h b/src/render/frontend/sphere_p.h index b7585f85a..448704cf4 100644 --- a/src/render/frontend/sphere_p.h +++ b/src/render/frontend/sphere_p.h @@ -56,8 +56,6 @@ #include #include -#include - QT_BEGIN_NAMESPACE namespace Qt3DRender { diff --git a/src/render/geometry/armature_p.h b/src/render/geometry/armature_p.h index 39baa4a79..db9d28bd6 100644 --- a/src/render/geometry/armature_p.h +++ b/src/render/geometry/armature_p.h @@ -58,7 +58,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT Armature : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Armature : public BackendNode { public: Armature(); diff --git a/src/render/geometry/attribute_p.h b/src/render/geometry/attribute_p.h index 4b47146e1..87b3cbb4f 100644 --- a/src/render/geometry/attribute_p.h +++ b/src/render/geometry/attribute_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT Attribute : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Attribute : public BackendNode { public: Attribute(); diff --git a/src/render/geometry/buffer_p.h b/src/render/geometry/buffer_p.h index a3f52d1b3..3490b7bc9 100644 --- a/src/render/geometry/buffer_p.h +++ b/src/render/geometry/buffer_p.h @@ -66,7 +66,7 @@ namespace Render { class BufferManager; -class Q_AUTOTEST_EXPORT Buffer : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Buffer : public BackendNode { public: Buffer(); diff --git a/src/render/geometry/buffermanager_p.h b/src/render/geometry/buffermanager_p.h index df97a5193..bafcf8812 100644 --- a/src/render/geometry/buffermanager_p.h +++ b/src/render/geometry/buffermanager_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT BufferManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT BufferManager : public Qt3DCore::QResourceManager< Buffer, Qt3DCore::QNodeId, Qt3DCore::ObjectLevelLockingPolicy> diff --git a/src/render/geometry/geometry_p.h b/src/render/geometry/geometry_p.h index 429a577b0..fdad63286 100644 --- a/src/render/geometry/geometry_p.h +++ b/src/render/geometry/geometry_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT Geometry : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Geometry : public BackendNode { public: Geometry(); diff --git a/src/render/geometry/geometryrenderer_p.h b/src/render/geometry/geometryrenderer_p.h index d2ddad4bb..a38233d6c 100644 --- a/src/render/geometry/geometryrenderer_p.h +++ b/src/render/geometry/geometryrenderer_p.h @@ -73,7 +73,7 @@ struct GeometryFunctorResult QMesh::Status status; }; -class Q_AUTOTEST_EXPORT GeometryRenderer : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT GeometryRenderer : public BackendNode { public: GeometryRenderer(); diff --git a/src/render/geometry/geometryrenderermanager_p.h b/src/render/geometry/geometryrenderermanager_p.h index becf1bcc1..7b7b629bd 100644 --- a/src/render/geometry/geometryrenderermanager_p.h +++ b/src/render/geometry/geometryrenderermanager_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT GeometryRendererManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT GeometryRendererManager : public Qt3DCore::QResourceManager< GeometryRenderer, Qt3DCore::QNodeId, Qt3DCore::ObjectLevelLockingPolicy> diff --git a/src/render/geometry/joint_p.h b/src/render/geometry/joint_p.h index de875459e..c178fdcf8 100644 --- a/src/render/geometry/joint_p.h +++ b/src/render/geometry/joint_p.h @@ -63,7 +63,7 @@ namespace Render { class JointManager; class SkeletonManager; -class Q_AUTOTEST_EXPORT Joint : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Joint : public BackendNode { public: Joint(); diff --git a/src/render/geometry/skeleton_p.h b/src/render/geometry/skeleton_p.h index 7a5299944..ac475a3c0 100644 --- a/src/render/geometry/skeleton_p.h +++ b/src/render/geometry/skeleton_p.h @@ -72,7 +72,7 @@ namespace Render { class JointManager; class SkeletonManager; -class Q_AUTOTEST_EXPORT Skeleton : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Skeleton : public BackendNode { public: enum SkeletonDataType { diff --git a/src/render/io/scene_p.h b/src/render/io/scene_p.h index bf625b369..cf927bc23 100644 --- a/src/render/io/scene_p.h +++ b/src/render/io/scene_p.h @@ -67,7 +67,7 @@ namespace Render { class SceneManager; -class Q_AUTOTEST_EXPORT Scene : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Scene : public BackendNode { public: Scene(); diff --git a/src/render/io/scenemanager_p.h b/src/render/io/scenemanager_p.h index 470846b83..badef2bf9 100644 --- a/src/render/io/scenemanager_p.h +++ b/src/render/io/scenemanager_p.h @@ -82,7 +82,7 @@ private: typedef QSharedPointer SceneDownloaderPtr; -class Q_AUTOTEST_EXPORT SceneManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT SceneManager : public Qt3DCore::QResourceManager< Scene, Qt3DCore::QNodeId, Qt3DCore::ObjectLevelLockingPolicy> diff --git a/src/render/jobs/abstractpickingjob.cpp b/src/render/jobs/abstractpickingjob.cpp index 092ab7d3b..ea2916006 100644 --- a/src/render/jobs/abstractpickingjob.cpp +++ b/src/render/jobs/abstractpickingjob.cpp @@ -39,7 +39,6 @@ #include "abstractpickingjob_p.h" #include -#include #include #include #include diff --git a/src/render/jobs/abstractpickingjob_p.h b/src/render/jobs/abstractpickingjob_p.h index c0c6ed7e9..f53805ac5 100644 --- a/src/render/jobs/abstractpickingjob_p.h +++ b/src/render/jobs/abstractpickingjob_p.h @@ -57,6 +57,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -72,7 +73,7 @@ class Renderer; class NodeManagers; class RenderSettings; -class Q_AUTOTEST_EXPORT AbstractPickingJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT AbstractPickingJob : public Qt3DCore::QAspectJob { public: AbstractPickingJob(); diff --git a/src/render/jobs/computefilteredboundingvolumejob.cpp b/src/render/jobs/computefilteredboundingvolumejob.cpp index 0cdbc8b6d..0be3cb489 100644 --- a/src/render/jobs/computefilteredboundingvolumejob.cpp +++ b/src/render/jobs/computefilteredboundingvolumejob.cpp @@ -39,7 +39,6 @@ #include "computefilteredboundingvolumejob_p.h" -#include #include #include #include diff --git a/src/render/jobs/expandboundingvolumejob.cpp b/src/render/jobs/expandboundingvolumejob.cpp index 8587634cb..ec783e5e0 100644 --- a/src/render/jobs/expandboundingvolumejob.cpp +++ b/src/render/jobs/expandboundingvolumejob.cpp @@ -39,7 +39,6 @@ #include "expandboundingvolumejob_p.h" -#include #include #include #include diff --git a/src/render/jobs/filterproximitydistancejob_p.h b/src/render/jobs/filterproximitydistancejob_p.h index 935d4036f..e058f011a 100644 --- a/src/render/jobs/filterproximitydistancejob_p.h +++ b/src/render/jobs/filterproximitydistancejob_p.h @@ -42,6 +42,7 @@ #include #include +#include QT_BEGIN_NAMESPACE @@ -52,7 +53,7 @@ namespace Render { class Entity; class NodeManagers; -class Q_AUTOTEST_EXPORT FilterProximityDistanceJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT FilterProximityDistanceJob : public Qt3DCore::QAspectJob { public: FilterProximityDistanceJob(); diff --git a/src/render/jobs/framecleanupjob.cpp b/src/render/jobs/framecleanupjob.cpp index fb63f005b..eddea12e8 100644 --- a/src/render/jobs/framecleanupjob.cpp +++ b/src/render/jobs/framecleanupjob.cpp @@ -38,7 +38,6 @@ ****************************************************************************/ #include "framecleanupjob_p.h" -#include #include #include #include @@ -69,9 +68,6 @@ void FrameCleanupJob::setRoot(Entity *root) void FrameCleanupJob::run() { - // mark each ShaderData clean - ShaderData::cleanup(m_managers); - // Debug bounding volume debug updateBoundingVolumesDebug(m_root); } diff --git a/src/render/jobs/frustumcullingjob.cpp b/src/render/jobs/frustumcullingjob.cpp index e22d625df..aa1a57a31 100644 --- a/src/render/jobs/frustumcullingjob.cpp +++ b/src/render/jobs/frustumcullingjob.cpp @@ -41,7 +41,6 @@ #include #include #include -#include #include #include #include diff --git a/src/render/jobs/frustumcullingjob_p.h b/src/render/jobs/frustumcullingjob_p.h index cddbbd409..636585c2f 100644 --- a/src/render/jobs/frustumcullingjob_p.h +++ b/src/render/jobs/frustumcullingjob_p.h @@ -42,7 +42,10 @@ #include #include +#include +#include #include +#include // // W A R N I N G @@ -66,7 +69,7 @@ class EntityManager; class NodeManagers; struct Plane; -class FrustumCullingJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT FrustumCullingJob : public Qt3DCore::QAspectJob { public: FrustumCullingJob(); @@ -85,6 +88,19 @@ public: void run() final; private: + struct Q_AUTOTEST_EXPORT Plane + { + explicit Plane(const Vector4D &planeEquation) + : planeEquation(planeEquation) + , normal(Vector3D(planeEquation).normalized()) + , d(planeEquation.w() / Vector3D(planeEquation).length()) + {} + + const Vector4D planeEquation; + const Vector3D normal; + const float d; + }; + void cullScene(Entity *e, const Plane *planes); Matrix4x4 m_viewProjection; Entity *m_root; diff --git a/src/render/jobs/lightgatherer.cpp b/src/render/jobs/lightgatherer.cpp index b79976aef..b878b0a78 100644 --- a/src/render/jobs/lightgatherer.cpp +++ b/src/render/jobs/lightgatherer.cpp @@ -41,6 +41,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/jobs/lightgatherer_p.h b/src/render/jobs/lightgatherer_p.h index d0090ccd0..59e64ad74 100644 --- a/src/render/jobs/lightgatherer_p.h +++ b/src/render/jobs/lightgatherer_p.h @@ -53,6 +53,7 @@ #include #include +#include QT_BEGIN_NAMESPACE @@ -63,7 +64,7 @@ namespace Render { class EntityManager; class EnvironmentLight; -class Q_AUTOTEST_EXPORT LightGatherer : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT LightGatherer : public Qt3DCore::QAspectJob { public: LightGatherer(); diff --git a/src/render/jobs/loadbufferjob.cpp b/src/render/jobs/loadbufferjob.cpp index 0f4feb5d4..fd57248e1 100644 --- a/src/render/jobs/loadbufferjob.cpp +++ b/src/render/jobs/loadbufferjob.cpp @@ -41,9 +41,9 @@ #include #include #include -#include #include #include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/jobs/loadbufferjob_p.h b/src/render/jobs/loadbufferjob_p.h index e86e4f835..5f20bfb00 100644 --- a/src/render/jobs/loadbufferjob_p.h +++ b/src/render/jobs/loadbufferjob_p.h @@ -65,7 +65,7 @@ namespace Render { class NodeManagers; class LoadBufferJobPrivate; -class Q_AUTOTEST_EXPORT LoadBufferJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT LoadBufferJob : public Qt3DCore::QAspectJob { public: explicit LoadBufferJob(const HBuffer &handle); diff --git a/src/render/jobs/loadgeometryjob_p.h b/src/render/jobs/loadgeometryjob_p.h index 998d543ac..e5edf0100 100644 --- a/src/render/jobs/loadgeometryjob_p.h +++ b/src/render/jobs/loadgeometryjob_p.h @@ -54,6 +54,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -64,7 +65,7 @@ namespace Render { class NodeManagers; class LoadGeometryJobPrivate; -class Q_AUTOTEST_EXPORT LoadGeometryJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT LoadGeometryJob : public Qt3DCore::QAspectJob { public: explicit LoadGeometryJob(const HGeometryRenderer &handle); diff --git a/src/render/jobs/loadscenejob.cpp b/src/render/jobs/loadscenejob.cpp index be855c608..959cbe3eb 100644 --- a/src/render/jobs/loadscenejob.cpp +++ b/src/render/jobs/loadscenejob.cpp @@ -38,9 +38,9 @@ ****************************************************************************/ #include "loadscenejob_p.h" -#include #include #include +#include #include #include #include diff --git a/src/render/jobs/loadscenejob_p.h b/src/render/jobs/loadscenejob_p.h index 3675d94c1..39d2d8d6e 100644 --- a/src/render/jobs/loadscenejob_p.h +++ b/src/render/jobs/loadscenejob_p.h @@ -58,6 +58,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -88,7 +89,7 @@ private: LoadSceneJob *q_ptr; }; -class Q_AUTOTEST_EXPORT LoadSceneJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT LoadSceneJob : public Qt3DCore::QAspectJob { public: explicit LoadSceneJob(const QUrl &source, Qt3DCore::QNodeId sceneComponent); diff --git a/src/render/jobs/loadskeletonjob.cpp b/src/render/jobs/loadskeletonjob.cpp index e696cc434..de12b7e39 100644 --- a/src/render/jobs/loadskeletonjob.cpp +++ b/src/render/jobs/loadskeletonjob.cpp @@ -47,6 +47,9 @@ #include #include #include +#include +#include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/jobs/pickboundingvolumejob.cpp b/src/render/jobs/pickboundingvolumejob.cpp index 2973ee100..dce184f46 100644 --- a/src/render/jobs/pickboundingvolumejob.cpp +++ b/src/render/jobs/pickboundingvolumejob.cpp @@ -46,7 +46,6 @@ #include #include #include -#include #include #include #include diff --git a/src/render/jobs/pickboundingvolumejob_p.h b/src/render/jobs/pickboundingvolumejob_p.h index 49b11b775..4f2c4340e 100644 --- a/src/render/jobs/pickboundingvolumejob_p.h +++ b/src/render/jobs/pickboundingvolumejob_p.h @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include @@ -76,7 +77,7 @@ namespace PickingUtils { typedef QVector HitList; } -class Q_AUTOTEST_EXPORT PickBoundingVolumeJob : public AbstractPickingJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT PickBoundingVolumeJob : public AbstractPickingJob { public: PickBoundingVolumeJob(); diff --git a/src/render/jobs/raycastingjob.cpp b/src/render/jobs/raycastingjob.cpp index 380447873..50dcaecde 100644 --- a/src/render/jobs/raycastingjob.cpp +++ b/src/render/jobs/raycastingjob.cpp @@ -48,7 +48,6 @@ #include #include #include -#include #include #include #include diff --git a/src/render/jobs/raycastingjob_p.h b/src/render/jobs/raycastingjob_p.h index 4b8b91ad5..0a8b7aa3a 100644 --- a/src/render/jobs/raycastingjob_p.h +++ b/src/render/jobs/raycastingjob_p.h @@ -55,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -70,7 +71,7 @@ typedef QVector HitList; class RayCastingJobPrivate; -class Q_AUTOTEST_EXPORT RayCastingJob : public AbstractPickingJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT RayCastingJob : public AbstractPickingJob { public: RayCastingJob(); diff --git a/src/render/jobs/updateskinningpalettejob_p.h b/src/render/jobs/updateskinningpalettejob_p.h index c52e0841c..f74cf6a73 100644 --- a/src/render/jobs/updateskinningpalettejob_p.h +++ b/src/render/jobs/updateskinningpalettejob_p.h @@ -53,6 +53,7 @@ #include #include +#include QT_BEGIN_NAMESPACE @@ -61,7 +62,7 @@ namespace Render { class NodeManagers; -class UpdateSkinningPaletteJob : public Qt3DCore::QAspectJob +class Q_3DRENDERSHARED_PRIVATE_EXPORT UpdateSkinningPaletteJob : public Qt3DCore::QAspectJob { public: explicit UpdateSkinningPaletteJob(); diff --git a/src/render/jobs/updateworldtransformjob.cpp b/src/render/jobs/updateworldtransformjob.cpp index e3c8077f4..12582c297 100644 --- a/src/render/jobs/updateworldtransformjob.cpp +++ b/src/render/jobs/updateworldtransformjob.cpp @@ -42,7 +42,6 @@ #include #include #include -#include #include #include #include diff --git a/src/render/lights/environmentlight_p.h b/src/render/lights/environmentlight_p.h index 92f6ce100..7a631ed28 100644 --- a/src/render/lights/environmentlight_p.h +++ b/src/render/lights/environmentlight_p.h @@ -59,7 +59,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT EnvironmentLight : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT EnvironmentLight : public BackendNode { public: Qt3DCore::QNodeId shaderData() const; diff --git a/src/render/lights/light_p.h b/src/render/lights/light_p.h index 5f5f8140e..d1497fddd 100644 --- a/src/render/lights/light_p.h +++ b/src/render/lights/light_p.h @@ -61,7 +61,7 @@ namespace Render { class NodeManagers; -class Q_AUTOTEST_EXPORT Light : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Light : public BackendNode { public: Qt3DCore::QNodeId shaderData() const; diff --git a/src/render/lights/lightsource_p.h b/src/render/lights/lightsource_p.h index 9e56dc70e..bfa2b81f9 100644 --- a/src/render/lights/lightsource_p.h +++ b/src/render/lights/lightsource_p.h @@ -51,7 +51,7 @@ // We mean it. // -#include +#include #include QT_BEGIN_NAMESPACE @@ -63,7 +63,7 @@ namespace Render { class Entity; class Light; -struct LightSource { +struct Q_3DRENDERSHARED_PRIVATE_EXPORT LightSource { LightSource(); LightSource(Entity *entity, const QVector &lights); diff --git a/src/render/materialsystem/effect.cpp b/src/render/materialsystem/effect.cpp index 035cf4746..9b787b7e2 100644 --- a/src/render/materialsystem/effect.cpp +++ b/src/render/materialsystem/effect.cpp @@ -38,9 +38,9 @@ ****************************************************************************/ #include -#include #include #include +#include #include #include diff --git a/src/render/materialsystem/effect_p.h b/src/render/materialsystem/effect_p.h index e81be2b8d..e8f79120b 100644 --- a/src/render/materialsystem/effect_p.h +++ b/src/render/materialsystem/effect_p.h @@ -63,7 +63,7 @@ class QTechnique; namespace Render { -class Q_AUTOTEST_EXPORT Effect : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Effect : public BackendNode { public: Effect(); diff --git a/src/render/materialsystem/filterkey_p.h b/src/render/materialsystem/filterkey_p.h index f4fb2c3d0..91d0ba1f0 100644 --- a/src/render/materialsystem/filterkey_p.h +++ b/src/render/materialsystem/filterkey_p.h @@ -62,7 +62,7 @@ class QFilterKey; namespace Render { -class Q_AUTOTEST_EXPORT FilterKey : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT FilterKey : public BackendNode { public: FilterKey(); diff --git a/src/render/materialsystem/material_p.h b/src/render/materialsystem/material_p.h index 7a02c6691..b13f49b81 100644 --- a/src/render/materialsystem/material_p.h +++ b/src/render/materialsystem/material_p.h @@ -54,7 +54,6 @@ #include #include -#include #include QT_BEGIN_NAMESPACE @@ -72,7 +71,7 @@ class Technique; class Effect; class MaterialManager; -class Q_AUTOTEST_EXPORT Material : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Material : public BackendNode { public: Material(); diff --git a/src/render/materialsystem/parameter_p.h b/src/render/materialsystem/parameter_p.h index 258834ff3..8a30d6657 100644 --- a/src/render/materialsystem/parameter_p.h +++ b/src/render/materialsystem/parameter_p.h @@ -64,7 +64,7 @@ namespace Render { class ParameterManager; class ShaderDataManager; -class Q_AUTOTEST_EXPORT Parameter : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Parameter : public BackendNode { public: Parameter(); diff --git a/src/render/materialsystem/qshaderprogram_p.h b/src/render/materialsystem/qshaderprogram_p.h index d377ef039..8a14255a8 100644 --- a/src/render/materialsystem/qshaderprogram_p.h +++ b/src/render/materialsystem/qshaderprogram_p.h @@ -51,14 +51,15 @@ // We mean it. // -#include +#include #include +#include QT_BEGIN_NAMESPACE namespace Qt3DRender { -class QShaderProgramPrivate : public Qt3DCore::QNodePrivate +class Q_3DRENDERSHARED_PRIVATE_EXPORT QShaderProgramPrivate : public Qt3DCore::QNodePrivate { public: QShaderProgramPrivate(); diff --git a/src/render/materialsystem/renderpass.cpp b/src/render/materialsystem/renderpass.cpp index 19e2a427e..a9e8c9b1d 100644 --- a/src/render/materialsystem/renderpass.cpp +++ b/src/render/materialsystem/renderpass.cpp @@ -46,7 +46,6 @@ #include #include -#include #include diff --git a/src/render/materialsystem/renderpass_p.h b/src/render/materialsystem/renderpass_p.h index 314386ad1..03c5c5f19 100644 --- a/src/render/materialsystem/renderpass_p.h +++ b/src/render/materialsystem/renderpass_p.h @@ -71,7 +71,7 @@ namespace Render { class RenderPassManager; class RenderState; -class Q_AUTOTEST_EXPORT RenderPass : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderPass : public BackendNode { public: RenderPass(); diff --git a/src/render/materialsystem/shader.cpp b/src/render/materialsystem/shader.cpp index d0069bb4a..f3570f78d 100644 --- a/src/render/materialsystem/shader.cpp +++ b/src/render/materialsystem/shader.cpp @@ -46,7 +46,6 @@ #include #include #include -#include #include #include #include diff --git a/src/render/materialsystem/shader_p.h b/src/render/materialsystem/shader_p.h index 23d57f25d..0814989ea 100644 --- a/src/render/materialsystem/shader_p.h +++ b/src/render/materialsystem/shader_p.h @@ -66,7 +66,7 @@ namespace Render { class ShaderManager; class AttachmentPack; -class Q_AUTOTEST_EXPORT Shader : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Shader : public BackendNode { public: static const int modelMatrixNameId; diff --git a/src/render/materialsystem/shaderdata.cpp b/src/render/materialsystem/shaderdata.cpp index 34d4641e9..67c8f35f7 100644 --- a/src/render/materialsystem/shaderdata.cpp +++ b/src/render/materialsystem/shaderdata.cpp @@ -44,12 +44,9 @@ #include #include #include -#include #include -#include #include #include -#include QT_BEGIN_NAMESPACE @@ -164,11 +161,6 @@ ShaderData *ShaderData::lookupResource(QNodeId id) return ShaderData::lookupResource(m_managers, id); } -void ShaderData::cleanup(NodeManagers *managers) -{ - Q_UNUSED(managers) -} - // RenderCommand updater jobs QVariant ShaderData::getTransformedProperty(const QString &name, const Matrix4x4 &viewMatrix) { diff --git a/src/render/materialsystem/shaderdata_p.h b/src/render/materialsystem/shaderdata_p.h index c9cc22939..5c6352eba 100644 --- a/src/render/materialsystem/shaderdata_p.h +++ b/src/render/materialsystem/shaderdata_p.h @@ -52,7 +52,6 @@ // #include -#include #include #include #include @@ -67,7 +66,7 @@ class GraphicsContext; class GLBuffer; class NodeManagers; -class Q_AUTOTEST_EXPORT ShaderData : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderData : public BackendNode { public: enum TransformType { @@ -95,13 +94,15 @@ public: // Unit tests purposes only TransformType propertyTransformType(const QString &name) const; - // Called by FrameCleanupJob - static void cleanup(NodeManagers *managers); - void setManagers(NodeManagers *managers); void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) override; +#ifdef Q_OS_WIN + // To get MSVC to compile even though we don't need any cleanup + void cleanup() {} +#endif + protected: PropertyReaderInterfacePtr m_propertyReader; diff --git a/src/render/materialsystem/technique.cpp b/src/render/materialsystem/technique.cpp index 10e9af990..440d7e49c 100644 --- a/src/render/materialsystem/technique.cpp +++ b/src/render/materialsystem/technique.cpp @@ -43,7 +43,6 @@ #include #include #include -#include #include #include #include diff --git a/src/render/materialsystem/techniquemanager_p.h b/src/render/materialsystem/techniquemanager_p.h index 8108d5f5b..205dbc191 100644 --- a/src/render/materialsystem/techniquemanager_p.h +++ b/src/render/materialsystem/techniquemanager_p.h @@ -60,7 +60,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT TechniqueManager : public Qt3DCore::QResourceManager< +class Q_3DRENDERSHARED_PRIVATE_EXPORT TechniqueManager : public Qt3DCore::QResourceManager< Technique, Qt3DCore::QNodeId, Qt3DCore::NonLockingPolicy> diff --git a/src/render/picking/objectpicker_p.h b/src/render/picking/objectpicker_p.h index 49c8de770..d2ccf1c6a 100644 --- a/src/render/picking/objectpicker_p.h +++ b/src/render/picking/objectpicker_p.h @@ -62,7 +62,7 @@ typedef QSharedPointer QPickEventPtr; namespace Render { -class Q_AUTOTEST_EXPORT ObjectPicker : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT ObjectPicker : public BackendNode { public: ObjectPicker(); diff --git a/src/render/picking/pickeventfilter_p.h b/src/render/picking/pickeventfilter_p.h index dfd8c1b99..81ba6a9f4 100644 --- a/src/render/picking/pickeventfilter_p.h +++ b/src/render/picking/pickeventfilter_p.h @@ -55,6 +55,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -62,7 +63,7 @@ namespace Qt3DRender { namespace Render { -class PickEventFilter : public QObject +class Q_3DRENDERSHARED_PRIVATE_EXPORT PickEventFilter : public QObject { Q_OBJECT public: diff --git a/src/render/picking/raycaster_p.h b/src/render/picking/raycaster_p.h index 865d40365..e7d12af56 100644 --- a/src/render/picking/raycaster_p.h +++ b/src/render/picking/raycaster_p.h @@ -64,7 +64,7 @@ namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT RayCaster : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RayCaster : public BackendNode { public: RayCaster(); diff --git a/src/render/qrendererplugin.cpp b/src/render/qrendererplugin.cpp new file mode 100644 index 000000000..eb54a0ead --- /dev/null +++ b/src/render/qrendererplugin.cpp @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qrendererplugin_p.h" + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +QRendererPlugin::QRendererPlugin(QObject *parent) + : QObject(parent) +{ +} + +QRendererPlugin::~QRendererPlugin() +{ +} + +AbstractRenderer *QRendererPlugin::create(const QString &key, QRenderAspect::RenderType renderMode) +{ + Q_UNUSED(key) + Q_UNUSED(renderMode) + return nullptr; +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/qrendererplugin_p.h b/src/render/qrendererplugin_p.h new file mode 100644 index 000000000..d4daeeda2 --- /dev/null +++ b/src/render/qrendererplugin_p.h @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_QRENDERERPLUGIN_P_H +#define QT3DRENDER_RENDER_QRENDERERPLUGIN_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +#define QRendererPluginFactoryInterface_iid "org.qt-project.Qt3DRender.QRendererFactoryInterface 5.11" + +class AbstractRenderer; + +class Q_3DRENDERSHARED_PRIVATE_EXPORT QRendererPlugin : public QObject +{ + Q_OBJECT +public: + explicit QRendererPlugin(QObject *parent = nullptr); + ~QRendererPlugin(); + + virtual AbstractRenderer *create(const QString &key, QRenderAspect::RenderType renderMode); +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_QRENDERERPLUGIN_P_H diff --git a/src/render/qrendererpluginfactory.cpp b/src/render/qrendererpluginfactory.cpp new file mode 100644 index 000000000..3cd41daed --- /dev/null +++ b/src/render/qrendererpluginfactory.cpp @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qrendererpluginfactory_p.h" + +#include +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QRendererPluginFactoryInterface_iid, QLatin1String("/renderers"), Qt::CaseInsensitive)) +#ifndef QT_NO_LIBRARY +Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, directLoader, (QRendererPluginFactoryInterface_iid, QLatin1String(""), Qt::CaseInsensitive)) +#endif + +QStringList QRendererPluginFactory::keys(const QString &pluginPath) +{ + QStringList list; + if (!pluginPath.isEmpty()) { +#if QT_CONFIG(library) + QCoreApplication::addLibraryPath(pluginPath); + list = directLoader()->keyMap().values(); + if (!list.isEmpty()) { + const QString postFix = QLatin1String(" (from ") + + QDir::toNativeSeparators(pluginPath) + + QLatin1Char(')'); + const QStringList::iterator end = list.end(); + for (QStringList::iterator it = list.begin(); it != end; ++it) + (*it).append(postFix); + } +#else + qWarning() << QObject::tr("Cannot query QRendererPlugin plugins at %1. " + "Library loading is disabled.").arg(pluginPath); +#endif + } + list.append(loader()->keyMap().values()); + return list; +} + +AbstractRenderer *QRendererPluginFactory::create(const QString &name, QRenderAspect::RenderType renderMode, const QString &pluginPath) +{ + if (!pluginPath.isEmpty()) { +#if QT_CONFIG(library) + QCoreApplication::addLibraryPath(pluginPath); + if (AbstractRenderer *ret = qLoadPlugin(directLoader(), name, renderMode)) + return ret; +#else + qWarning() << QObject::tr("Cannot load QRendererPlugin plugin from %1. " + "Library loading is disabled.").arg(pluginPath); +#endif + } + return qLoadPlugin(loader(), name, renderMode); +} + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/qrendererpluginfactory_p.h b/src/render/qrendererpluginfactory_p.h new file mode 100644 index 000000000..f73cc8929 --- /dev/null +++ b/src/render/qrendererpluginfactory_p.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_QRENDERERPLUGINFACTORY_P_H +#define QT3DRENDER_RENDER_QRENDERERPLUGINFACTORY_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +class AbstractRenderer; + +class Q_3DRENDERSHARED_PRIVATE_EXPORT QRendererPluginFactory +{ +public: + static QStringList keys(const QString &pluginPath = QString()); + static AbstractRenderer *create(const QString &name, QRenderAspect::RenderType renderMode, const QString &pluginPath = QString()); +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_QRENDERERPLUGINFACTORY_P_H diff --git a/src/render/render.pro b/src/render/render.pro index f8d44151f..bf7ef072f 100644 --- a/src/render/render.pro +++ b/src/render/render.pro @@ -1,8 +1,7 @@ TARGET = Qt3DRender MODULE = 3drender -QT = core-private gui-private 3dcore-private -QT_PRIVATE = openglextensions +QT = core-private 3dcore-private QT_FOR_PRIVATE = concurrent DEFINES += BUILD_QT3D_MODULE @@ -19,7 +18,6 @@ include (picking/picking.pri) include (raycasting/raycasting.pri) include (services/services.pri) include (texture/texture.pri) -include (renderers/renderers.pri) gcov { QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage @@ -40,14 +38,19 @@ HEADERS += \ renderlogging_p.h \ qt3drender_global.h \ qt3drender_global_p.h \ - aligned_malloc_p.h + aligned_malloc_p.h \ + qrendererplugin_p.h \ + qrendererpluginfactory_p.h SOURCES += \ - renderlogging.cpp + renderlogging.cpp \ + qrendererplugin.cpp \ + qrendererpluginfactory.cpp MODULE_PLUGIN_TYPES = \ sceneparsers \ geometryloaders \ - renderplugins + renderplugins \ + renderers load(qt_module) diff --git a/src/render/renderers/opengl/debug/debug.pri b/src/render/renderers/opengl/debug/debug.pri deleted file mode 100644 index c5153bbf7..000000000 --- a/src/render/renderers/opengl/debug/debug.pri +++ /dev/null @@ -1,10 +0,0 @@ -INCLUDEPATH += $$PWD - -include($$QT3D_ROOT/src/3rdparty/imgui/imgui.pri) - -HEADERS += \ - $$PWD/imguirenderer_p.h \ - $$PWD/imconfig.h - -SOURCES += \ - $$PWD/imguirenderer.cpp diff --git a/src/render/renderers/opengl/debug/imguirenderer.cpp b/src/render/renderers/opengl/debug/imguirenderer.cpp deleted file mode 100644 index 8abe1b8c0..000000000 --- a/src/render/renderers/opengl/debug/imguirenderer.cpp +++ /dev/null @@ -1,705 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - * Based on https://github.com/seanchas116/qtimgui/ - * - * MIT License https://github.com/seanchas116/qtimgui/blob/master/LICENSE - * - */ - -#include "imguirenderer_p.h" -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "imgui.h" - -#ifndef GL_VERTEX_ARRAY_BINDING -// just for building on some platforms, won't run anyway as this requires GL/ES > 2 -#define GL_VERTEX_ARRAY_BINDING 0x85B5 -#endif - -QT_BEGIN_NAMESPACE - -using namespace Qt3DRender; -using namespace Render; -using namespace Render::Debug; - -namespace { - - const QHash keyMap = { - { Qt::Key_Tab, ImGuiKey_Tab }, - { Qt::Key_Left, ImGuiKey_LeftArrow }, - { Qt::Key_Right, ImGuiKey_RightArrow }, - { Qt::Key_Up, ImGuiKey_UpArrow }, - { Qt::Key_Down, ImGuiKey_DownArrow }, - { Qt::Key_PageUp, ImGuiKey_PageUp }, - { Qt::Key_PageDown, ImGuiKey_PageDown }, - { Qt::Key_Home, ImGuiKey_Home }, - { Qt::Key_End, ImGuiKey_End }, - { Qt::Key_Delete, ImGuiKey_Delete }, - { Qt::Key_Backspace, ImGuiKey_Backspace }, - { Qt::Key_Enter, ImGuiKey_Enter }, - { Qt::Key_Escape, ImGuiKey_Escape }, - { Qt::Key_A, ImGuiKey_A }, - { Qt::Key_C, ImGuiKey_C }, - { Qt::Key_V, ImGuiKey_V }, - { Qt::Key_X, ImGuiKey_X }, - { Qt::Key_Y, ImGuiKey_Y }, - { Qt::Key_Z, ImGuiKey_Z }, - }; - - QByteArray g_currentClipboardText; - - // doesn't handle primitive restart when using indexes - int vertexToPrimitiveCount(Qt3DRender::QGeometryRenderer::PrimitiveType primitiveType, int numVertices) { - int nPrimitives = 0; - switch (primitiveType) { - case QGeometryRenderer::Points: - case QGeometryRenderer::LineLoop: nPrimitives += numVertices; break; - case QGeometryRenderer::Triangles: nPrimitives += numVertices / 3; break; - case QGeometryRenderer::Lines: nPrimitives += numVertices / 2; break; - case QGeometryRenderer::TriangleFan: - case QGeometryRenderer::TriangleStrip: - case QGeometryRenderer::LineStrip: nPrimitives += numVertices - 1; break; - case QGeometryRenderer::TrianglesAdjacency: nPrimitives += numVertices / 6; break; - case QGeometryRenderer::TriangleStripAdjacency: - case QGeometryRenderer::LineStripAdjacency: nPrimitives += numVertices / 2 - 1; break; - case QGeometryRenderer::LinesAdjacency: nPrimitives += numVertices / 4; break; - case QGeometryRenderer::Patches: nPrimitives += 1; - } - return nPrimitives; - } - - const char *primitiveTypeName(Qt3DRender::QGeometryRenderer::PrimitiveType primitiveType) { - switch (primitiveType) { - case QGeometryRenderer::Points: return "Points"; - case QGeometryRenderer::LineLoop: return "LineLoop"; - case QGeometryRenderer::Triangles: return "Triangles"; - case QGeometryRenderer::TrianglesAdjacency: return "TriangleAdjacency"; - case QGeometryRenderer::TriangleFan: return "TriangleFan"; - case QGeometryRenderer::TriangleStrip: return "TriangleStrip"; - case QGeometryRenderer::TriangleStripAdjacency: return "TriangleStringAdjacency"; - case QGeometryRenderer::LineStrip: return "LineStrip"; - case QGeometryRenderer::LineStripAdjacency: return "LineStripAdjacency"; - case QGeometryRenderer::Lines: return "Lines"; - case QGeometryRenderer::LinesAdjacency: return "LinesAdjacency"; - case QGeometryRenderer::Patches: return "Patches"; - } - return ""; - } -} - -ImGuiRenderer::ImGuiRenderer(Renderer *renderer) - : m_renderer(renderer) -{ - ImGui::CreateContext(); - - ImGuiIO &io = ImGui::GetIO(); - for (ImGuiKey key : keyMap.values()) - io.KeyMap[key] = key; - -#ifndef QT_NO_CLIPBOARD - io.SetClipboardTextFn = [](void *user_data, const char *text) { - Q_UNUSED(user_data) - QGuiApplication::clipboard()->setText(QString::fromLatin1(text)); - }; - io.GetClipboardTextFn = [](void *user_data) { - Q_UNUSED(user_data) - g_currentClipboardText = QGuiApplication::clipboard()->text().toUtf8(); - return static_cast(g_currentClipboardText.data()); - }; -#endif - - std::fill(std::begin(m_fpsLog), std::end(m_fpsLog), 0.f); - std::fill(std::begin(m_jobsLog), std::end(m_jobsLog), 0.f); - m_fpsRange.first = m_fpsRange.second = 0.f; - m_jobsRange.first = m_jobsRange.second = 0.f; -} - -void ImGuiRenderer::renderDebugOverlay(const QVector &renderViews, const RenderView *renderView, int jobsInLastFrame) -{ - if (!newFrame(renderView)) - return; - - const int renderViewsCount = renderViews.size(); - - int logIndex = qMin(IMGUI_PERF_LOG_SIZE - 1, ImGui::GetFrameCount()); - if (logIndex == IMGUI_PERF_LOG_SIZE - 1) { - std::rotate(std::begin(m_fpsLog), std::begin(m_fpsLog) + 1, std::end(m_fpsLog)); - std::rotate(std::begin(m_jobsLog), std::begin(m_jobsLog) + 1, std::end(m_jobsLog)); - } - m_fpsLog[logIndex] = ImGui::GetIO().Framerate; - m_fpsRange.first = m_fpsRange.second = 0.f; - for (float v: m_fpsLog) { - m_fpsRange.first = qMin(m_fpsRange.first, qMax(v - 5.f, 0.f)); - m_fpsRange.second = qMax(m_fpsRange.second, v + 2.f); - } - m_jobsLog[logIndex] = jobsInLastFrame; - m_jobsRange.first = m_jobsRange.second = 0.f; - for (float v: m_jobsLog) { - m_jobsRange.first = qMin(m_jobsRange.first, qMax(v - 5.f, 0.f)); - m_jobsRange.second = qMax(m_jobsRange.second, v + 2.f); - } - - { - bool pj = m_renderer->services()->systemInformation()->isTraceEnabled(); - bool pg = m_renderer->services()->systemInformation()->isGraphicsTraceEnabled(); - - ImGui::Begin("Qt3D Profiling"); - char caption[50]; - sprintf(caption, "Avg %.3f ms/frame (%.1f FPS)", static_cast(1000.0f / ImGui::GetIO().Framerate), static_cast(ImGui::GetIO().Framerate)); - ImGui::PlotLines("FPS", m_fpsLog, logIndex + 1, 0, caption, m_fpsRange.first, m_fpsRange.second, ImVec2(0, 80)); - ImGui::PlotHistogram("Jobs", m_jobsLog, logIndex + 1, 0, nullptr, m_jobsRange.first, m_jobsRange.second, ImVec2(0, 80)); - ImGui::Text("Profiling: "); - ImGui::SameLine(); - if (ImGui::Checkbox("Jobs", &pj)) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "setTraceEnabled", Qt::QueuedConnection, Q_ARG(bool, pj)); - ImGui::SameLine(); - if (ImGui::Checkbox("GL", &pg)) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "setGraphicsTraceEnabled", Qt::QueuedConnection, Q_ARG(bool, pg)); - ImGui::SameLine(); - if (ImGui::Button("Reveal")) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "revealLogFolder", Qt::QueuedConnection); - - int nCommands = 0; - int nVertices = 0; - int nPrimitives = 0; - QSet inUseGeometries; - QSet inUseTextures; - for (int j=0; jcommands(); - nCommands += commands.size(); - for (int k=0; knodeManagers()->renderNodesManager()->count()); - column2Numbers(inUseGeometries.size(), m_renderer->nodeManagers()->geometryRendererManager()->count()); - column2Numbers(inUseTextures.size(), m_renderer->nodeManagers()->textureManager()->count()); - - ImGui::Columns(1); - ImGui::Separator(); - - ImGui::AlignTextToFramePadding(); - ImGui::Text("Show:"); - ImGui::SameLine(); - if (ImGui::Button("GL Info")) - m_showGLInfoWindow = !m_showGLInfoWindow; - ImGui::SameLine(); - if (ImGui::Button("Render Views")) - m_showRenderDetailsWindow = !m_showRenderDetailsWindow; - - ImGui::AlignTextToFramePadding(); - ImGui::Text("Dump:"); - ImGui::SameLine(); - if (ImGui::Button("SceneGraph##1")) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", - Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render scenegraph"))); - ImGui::SameLine(); - if (ImGui::Button("FrameGraph##1")) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", - Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render framegraph"))); - ImGui::SameLine(); - if (ImGui::Button("FrameGraph Paths##1")) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", - Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render framepaths"))); - - ImGui::End(); - - if (m_showGLInfoWindow) - showGLInfo(); - if (m_showRenderDetailsWindow) - showRenderDetails(renderViews); - } - - ImGui::Render(); - renderDrawList(ImGui::GetDrawData()); -} - -void ImGuiRenderer::setCapabilities(const QString &capabilities) -{ - m_capabilities = capabilities.toLatin1(); -} - -void ImGuiRenderer::showGLInfo() -{ - ImGui::Begin("Open GL Details", &m_showGLInfoWindow); - ImGui::Text("%s", m_capabilities.data()); - ImGui::End(); -} - -void ImGuiRenderer::showRenderDetails(const QVector &renderViews) -{ - ImGui::Begin("Render Views", &m_showRenderDetailsWindow); - - int i = 1; - for (const RenderView *view: renderViews) { - QString label(QLatin1String("View ") + QString::number(i++)); - if (ImGui::TreeNode(label.toLatin1().data())) { - ImGui::Text("Viewport: (%.1f, %.1f, %.1f, %.1f)", view->viewport().x(), view->viewport().y(), - view->viewport().width(), view->viewport().height()); - ImGui::Text("Surface Size: (%d, %d)", view->surfaceSize().width(), view->surfaceSize().height()); - ImGui::Text("Pixel Ratio: %.1f", view->devicePixelRatio()); - ImGui::Text("No Draw: %s", view->noDraw() ? "TRUE" : "FALSE"); - ImGui::Text("Frustum Culling: %s", view->frustumCulling() ? "TRUE" : "FALSE"); - ImGui::Text("Compute: %s", view->isCompute() ? "TRUE" : "FALSE"); - ImGui::Text("Clear Depth Value: %f", static_cast(view->clearDepthValue())); - ImGui::Text("Clear Stencil Value: %d", view->clearStencilValue()); - int j = 1; - const auto commands = view->commands(); - for (const RenderCommand &command: commands) { - QString label(QLatin1String("Command ") + QString::number(j++)); - if (ImGui::TreeNode(label.toLatin1().data())) { - ImGui::Text("Primitive Type: %s %s", primitiveTypeName(command.m_primitiveType), - command.m_drawIndexed ? "(indexed)" : ""); - ImGui::Text("# Vertices: %d", command.m_primitiveCount); - ImGui::Text("# Primitives: %d", vertexToPrimitiveCount(command.m_primitiveType, command.m_primitiveCount)); - ImGui::Text("# Instances: %d", command.m_instanceCount); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - ImGui::Separator(); - } - } - - if (ImGui::Button("Dump")) - QMetaObject::invokeMethod(m_renderer->services()->systemInformation(), "dumpCommand", - Qt::QueuedConnection, Q_ARG(QString, QLatin1String("render rendercommands"))); - ImGui::End(); -} - -void ImGuiRenderer::renderDrawList(ImDrawData *draw_data) -{ - // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - ImGuiIO& io = ImGui::GetIO(); - int fb_width = int(io.DisplaySize.x * io.DisplayFramebufferScale.x); - int fb_height = int(io.DisplaySize.y * io.DisplayFramebufferScale.y); - if (fb_width == 0 || fb_height == 0) - return; - draw_data->ScaleClipRects(io.DisplayFramebufferScale); - - // Backup GL state - GLint last_active_texture; m_funcs->glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); - m_funcs->glActiveTexture(GL_TEXTURE0); - GLint last_program; m_funcs->glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); - GLint last_texture; m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); - GLint last_array_buffer; m_funcs->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); - GLint last_element_array_buffer; m_funcs->glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); - GLint last_vertex_array; m_funcs->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); - GLint last_blend_src_rgb; m_funcs->glGetIntegerv(GL_BLEND_SRC_RGB, &last_blend_src_rgb); - GLint last_blend_dst_rgb; m_funcs->glGetIntegerv(GL_BLEND_DST_RGB, &last_blend_dst_rgb); - GLint last_blend_src_alpha; m_funcs->glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha); - GLint last_blend_dst_alpha; m_funcs->glGetIntegerv(GL_BLEND_DST_ALPHA, &last_blend_dst_alpha); - GLint last_blend_equation_rgb; m_funcs->glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); - GLint last_blend_equation_alpha; m_funcs->glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); - GLint last_viewport[4]; m_funcs->glGetIntegerv(GL_VIEWPORT, last_viewport); - GLint last_scissor_box[4]; m_funcs->glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); - GLboolean last_enable_blend = m_funcs->glIsEnabled(GL_BLEND); - GLboolean last_enable_cull_face = m_funcs->glIsEnabled(GL_CULL_FACE); - GLboolean last_enable_depth_test = m_funcs->glIsEnabled(GL_DEPTH_TEST); - GLboolean last_enable_scissor_test = m_funcs->glIsEnabled(GL_SCISSOR_TEST); - - // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled - m_funcs->glEnable(GL_BLEND); - m_funcs->glBlendEquation(GL_FUNC_ADD); - m_funcs->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - m_funcs->glDisable(GL_CULL_FACE); - m_funcs->glDisable(GL_DEPTH_TEST); - m_funcs->glEnable(GL_SCISSOR_TEST); - - // Setup viewport, orthographic projection matrix - m_funcs->glViewport(0, 0, static_cast(fb_width), static_cast(fb_height)); - const float ortho_projection[4][4] = { - { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, - { 0.0f, 0.0f, -1.0f, 0.0f }, - {-1.0f, 1.0f, 0.0f, 1.0f }, - }; - m_funcs->glUseProgram(m_shaderHandle); - m_funcs->glUniform1i(m_attribLocationTex, 0); - m_funcs->glUniformMatrix4fv(m_attribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); - m_funcs->glBindVertexArray(m_vaoHandle); - - for (int n = 0; n < draw_data->CmdListsCount; n++) { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; - const ImDrawIdx* idx_buffer_offset = nullptr; - - m_funcs->glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle); - m_funcs->glBufferData(GL_ARRAY_BUFFER, static_cast(cmd_list->VtxBuffer.Size) * sizeof(ImDrawVert), static_cast(cmd_list->VtxBuffer.Data), GL_STREAM_DRAW); - - m_funcs->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementsHandle); - m_funcs->glBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast(cmd_list->IdxBuffer.Size) * sizeof(ImDrawIdx), static_cast(cmd_list->IdxBuffer.Data), GL_STREAM_DRAW); - - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) { - pcmd->UserCallback(cmd_list, pcmd); - } else { - m_funcs->glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); - m_funcs->glScissor(static_cast(pcmd->ClipRect.x), static_cast(fb_height - pcmd->ClipRect.w), - static_cast(pcmd->ClipRect.z - pcmd->ClipRect.x), static_cast(pcmd->ClipRect.w - pcmd->ClipRect.y)); - m_funcs->glDrawElements(GL_TRIANGLES, static_cast(pcmd->ElemCount), sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); - } - idx_buffer_offset += pcmd->ElemCount; - } - } - - // Restore modified GL state - m_funcs->glUseProgram(last_program); - m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); - m_funcs->glActiveTexture(last_active_texture); - m_funcs->glBindVertexArray(last_vertex_array); - m_funcs->glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); - m_funcs->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); - m_funcs->glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); - m_funcs->glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); - if (last_enable_blend) - m_funcs->glEnable(GL_BLEND); else m_funcs->glDisable(GL_BLEND); - if (last_enable_cull_face) - m_funcs->glEnable(GL_CULL_FACE); else m_funcs->glDisable(GL_CULL_FACE); - if (last_enable_depth_test) - m_funcs->glEnable(GL_DEPTH_TEST); else m_funcs->glDisable(GL_DEPTH_TEST); - if (last_enable_scissor_test) - m_funcs->glEnable(GL_SCISSOR_TEST); else m_funcs->glDisable(GL_SCISSOR_TEST); - m_funcs->glViewport(last_viewport[0], last_viewport[1], static_cast(last_viewport[2]), static_cast(last_viewport[3])); - m_funcs->glScissor(last_scissor_box[0], last_scissor_box[1], static_cast(last_scissor_box[2]), static_cast(last_scissor_box[3])); -} - -bool ImGuiRenderer::createFontsTexture() -{ - // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. - - // Upload texture to graphics system - GLint last_texture; - m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); - m_funcs->glGenTextures(1, &m_fontTexture); - m_funcs->glBindTexture(GL_TEXTURE_2D, m_fontTexture); - m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - m_funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - // Store our identifier - io.Fonts->TexID = (void *)(intptr_t)m_fontTexture; - - // Restore state - m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); - - return true; -} - -bool ImGuiRenderer::createDeviceObjects() -{ - auto *glContext = m_renderer->submissionContext()->openGLContext(); - if (glContext->format().majorVersion() < 3) { - qWarning() << "Qt3D Profiling overlay requires GL or GL ES >= 3"; - return false; - } - - // Backup GL state - GLint last_texture, last_array_buffer, last_vertex_array; - m_funcs->glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); - m_funcs->glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); - m_funcs->glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); - - const GLchar *vertex_shader = - "#version 330\n" - "uniform mat4 ProjMtx;\n" - "in vec2 Position;\n" - "in vec2 UV;\n" - "in vec4 Color;\n" - "out vec2 Frag_UV;\n" - "out vec4 Frag_Color;\n" - "void main()\n" - "{\n" - " Frag_UV = UV;\n" - " Frag_Color = Color;\n" - " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" - "}\n"; - - const GLchar* fragment_shader = - "#version 330\n" - "uniform sampler2D Texture;\n" - "in vec2 Frag_UV;\n" - "in vec4 Frag_Color;\n" - "out vec4 Out_Color;\n" - "void main()\n" - "{\n" - " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" - "}\n"; - - const GLchar *vertex_shader_es3 = - "#version 110\n" - "uniform mat4 ProjMtx;\n" - "in vec2 Position;\n" - "in vec2 UV;\n" - "in vec4 Color;\n" - "out vec2 Frag_UV;\n" - "out vec4 Frag_Color;\n" - "void main()\n" - "{\n" - " Frag_UV = UV;\n" - " Frag_Color = Color;\n" - " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" - "}\n"; - - const GLchar* fragment_shader_es3 = - "#version 110\n" - "uniform sampler2D Texture;\n" - "in vec2 Frag_UV;\n" - "in vec4 Frag_Color;\n" - "void main()\n" - "{\n" - " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" - "}\n"; - -// m_shaderHandle = m_funcs->glCreateProgram(); -// m_vertHandle = m_funcs->glCreateShader(GL_VERTEX_SHADER); -// m_fragHandle = m_funcs->glCreateShader(GL_FRAGMENT_SHADER); -// auto *glContext = m_renderer->submissionContext()->openGLContext(); -// m_funcs->glShaderSource(m_vertHandle, 1, &vertex_shader, nullptr); -// m_funcs->glShaderSource(m_fragHandle, 1, &fragment_shader, nullptr); -// m_funcs->glCompileShader(m_vertHandle); -// m_funcs->glCompileShader(m_fragHandle); -// m_funcs->glAttachShader(m_shaderHandle, m_vertHandle); -// m_funcs->glAttachShader(m_shaderHandle, m_fragHandle); -// m_funcs->glLinkProgram(m_shaderHandle); - - QString logs; - m_shader = new QOpenGLShaderProgram(this); - if (glContext->isOpenGLES()) { - if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader_es3)) - logs += m_shader->log(); - if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader_es3)) - logs += m_shader->log(); - } else { - if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader)) - logs += m_shader->log(); - if (!m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, fragment_shader)) - logs += m_shader->log(); - } - m_shader->link(); - logs += m_shader->log(); - if (!logs.isEmpty()) - qWarning() << logs; - m_shaderHandle = m_shader->programId(); - - m_attribLocationTex = m_funcs->glGetUniformLocation(m_shaderHandle, "Texture"); - m_attribLocationProjMtx = m_funcs->glGetUniformLocation(m_shaderHandle, "ProjMtx"); - m_attribLocationPosition = m_funcs->glGetAttribLocation(m_shaderHandle, "Position"); - m_attribLocationUV = m_funcs->glGetAttribLocation(m_shaderHandle, "UV"); - m_attribLocationColor = m_funcs->glGetAttribLocation(m_shaderHandle, "Color"); - - m_funcs->glGenBuffers(1, &m_vboHandle); - m_funcs->glGenBuffers(1, &m_elementsHandle); - - m_funcs->glGenVertexArrays(1, &m_vaoHandle); - m_funcs->glBindVertexArray(m_vaoHandle); - m_funcs->glBindBuffer(GL_ARRAY_BUFFER, m_vboHandle); - m_funcs->glEnableVertexAttribArray(m_attribLocationPosition); - m_funcs->glEnableVertexAttribArray(m_attribLocationUV); - m_funcs->glEnableVertexAttribArray(m_attribLocationColor); - -#define OFFSETOF(TYPE, ELEMENT) (reinterpret_cast(&((static_cast(nullptr))->ELEMENT))) - m_funcs->glVertexAttribPointer(m_attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, pos))); - m_funcs->glVertexAttribPointer(m_attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, uv))); - m_funcs->glVertexAttribPointer(m_attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), reinterpret_cast(OFFSETOF(ImDrawVert, col))); -#undef OFFSETOF - - createFontsTexture(); - - // Restore modified GL state - m_funcs->glBindTexture(GL_TEXTURE_2D, last_texture); - m_funcs->glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); - m_funcs->glBindVertexArray(last_vertex_array); - - return true; -} - -bool ImGuiRenderer::newFrame(const RenderView *renderView) -{ - if (!m_funcs) - m_funcs = m_renderer->submissionContext()->openGLContext()->extraFunctions(); - if (!m_fontTexture) - createDeviceObjects(); - if (!m_shader) - return false; - - ImGuiIO& io = ImGui::GetIO(); - - // Setup display size (every frame to accommodate for window resizing) - io.DisplaySize = ImVec2(renderView->surfaceSize().width() / renderView->devicePixelRatio(), renderView->surfaceSize().height() / renderView->devicePixelRatio()); - io.DisplayFramebufferScale = ImVec2(renderView->devicePixelRatio(), renderView->devicePixelRatio()); - - // Setup time step - double current_time = QDateTime::currentMSecsSinceEpoch() / 1000.; - io.DeltaTime = m_time > 0.0 ? static_cast(current_time - m_time) : 1.0f / 60.0f; - if (io.DeltaTime == 0.f) - io.DeltaTime = 1.0f / 60.0f; - m_time = current_time; - - // Setup inputs - for (int i = 0; i < 3; i++) - io.MouseDown[i] = m_mousePressed[i]; - - io.MouseWheelH = m_mouseWheelH; - io.MouseWheel = m_mouseWheel; - m_mouseWheelH = 0; - m_mouseWheel = 0; - - // Start the frame - ImGui::NewFrame(); - return true; -} - -void ImGuiRenderer::onMouseChange(QMouseEvent *event) -{ - ImGuiIO& io = ImGui::GetIO(); - io.MousePos = ImVec2(event->pos().x(), event->pos().y()); - m_mousePressed[0] = event->buttons() & Qt::LeftButton; - m_mousePressed[1] = event->buttons() & Qt::RightButton; - m_mousePressed[2] = event->buttons() & Qt::MiddleButton; -} - -void ImGuiRenderer::onWheel(QWheelEvent *event) -{ - // 5 lines per unit - m_mouseWheelH += event->pixelDelta().x() / (ImGui::GetTextLineHeight()); - m_mouseWheel += event->pixelDelta().y() / (5.f * ImGui::GetTextLineHeight()); -} - -void ImGuiRenderer::onKeyPressRelease(QKeyEvent *event) -{ - ImGuiIO& io = ImGui::GetIO(); - if (keyMap.contains(event->key())) - io.KeysDown[keyMap[event->key()]] = event->type() == QEvent::KeyPress; - - if (event->type() == QEvent::KeyPress) { - QString text = event->text(); - if (text.size() == 1) - io.AddInputCharacter(static_cast(text.at(0).unicode())); - } - -#ifdef Q_OS_DARWIN - io.KeyCtrl = event->modifiers() & Qt::MetaModifier; - io.KeyShift = event->modifiers() & Qt::ShiftModifier; - io.KeyAlt = event->modifiers() & Qt::AltModifier; - io.KeySuper = event->modifiers() & Qt::ControlModifier; // Command key -#else - io.KeyCtrl = event->modifiers() & Qt::ControlModifier; - io.KeyShift = event->modifiers() & Qt::ShiftModifier; - io.KeyAlt = event->modifiers() & Qt::AltModifier; - io.KeySuper = event->modifiers() & Qt::MetaModifier; -#endif -} - -void ImGuiRenderer::processEvent(QEvent *event) -{ - switch (event->type()) { - case QEvent::MouseMove: - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - this->onMouseChange(static_cast(event)); - break; - case QEvent::Wheel: - this->onWheel(static_cast(event)); - break; - case QEvent::KeyPress: - case QEvent::KeyRelease: - this->onKeyPressRelease(static_cast(event)); - break; - default: - break; - } -} - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/debug/imguirenderer_p.h b/src/render/renderers/opengl/debug/imguirenderer_p.h deleted file mode 100644 index e574574be..000000000 --- a/src/render/renderers/opengl/debug/imguirenderer_p.h +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3D_RENDER_GL_IMGUIRENDER_H_ -#define QT3D_RENDER_GL_IMGUIRENDER_H_ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include - -struct ImDrawData; - -QT_BEGIN_NAMESPACE - -class QMouseEvent; -class QWheelEvent; -class QKeyEvent; -class QOpenGLExtraFunctions; -class QOpenGLShaderProgram; - -namespace Qt3DCore { -class QServiceLocator; -} - -namespace Qt3DRender { -namespace Render { - -class RenderView; -class Renderer; - -namespace Debug { - -#define IMGUI_PERF_LOG_SIZE 30 - -class ImGuiRenderer : public QObject { - Q_OBJECT -public: - ImGuiRenderer(Qt3DRender::Render::Renderer *renderer); - - void processEvent(QEvent *event); - void renderDebugOverlay(const QVector &renderViews, const Render::RenderView *renderView, int jobsInLastFrame); - - void setCapabilities(const QString &capabilities); - -private: - bool newFrame(const RenderView *renderView); - void renderDrawList(ImDrawData *draw_data); - void onMouseChange(QMouseEvent *event); - void onWheel(QWheelEvent *event); - void onKeyPressRelease(QKeyEvent *event); - void showGLInfo(); - void showRenderDetails(const QVector &renderViews); - - bool createFontsTexture(); - bool createDeviceObjects(); - - double m_time = 0.; - bool m_mousePressed[3] = { false, false, false }; - float m_mouseWheel; - float m_mouseWheelH; - GLuint m_fontTexture = 0; - GLuint m_shaderHandle = 0, m_vertHandle = 0, m_fragHandle = 0; - int m_attribLocationTex = 0, m_attribLocationProjMtx = 0; - int m_attribLocationPosition = 0, m_attribLocationUV = 0, m_attribLocationColor = 0; - unsigned int m_vboHandle = 0, m_vaoHandle = 0, m_elementsHandle = 0; - - Renderer *m_renderer; - QOpenGLExtraFunctions *m_funcs = nullptr; - QOpenGLShaderProgram *m_shader = nullptr; - - bool m_showGLInfoWindow = false; - bool m_showRenderDetailsWindow = false; - - float m_fpsLog[IMGUI_PERF_LOG_SIZE]; - float m_jobsLog[IMGUI_PERF_LOG_SIZE]; - std::pair m_fpsRange; - std::pair m_jobsRange; - - QByteArray m_capabilities; -}; - -} // namespace Debug -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3D_RENDER_GL_IMGUIRENDER_H_ diff --git a/src/render/renderers/opengl/graphicshelpers/glfence_p.h b/src/render/renderers/opengl/graphicshelpers/glfence_p.h deleted file mode 100644 index 366065048..000000000 --- a/src/render/renderers/opengl/graphicshelpers/glfence_p.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GLFENCE_P_H -#define GLFENCE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -// GLsync is a pointer to a struct (unlike the rest of GL which used int ids) -// We cannot reference GLsync as it's only available since 3.2 We use FenceId -// to wrap that around and trust the GLHelpers will convert them accordingly. -using GLFence = void *; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - - -#endif // GLFENCE_P_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp b/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp deleted file mode 100644 index 25543bb19..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp +++ /dev/null @@ -1,1026 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicscontext_p.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(QT_OPENGL_ES_2) -#include -#include -#include -#include -#include -#include -#include -#include -#endif -#include -#include -#include -#include - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -#ifndef GL_READ_FRAMEBUFFER -#define GL_READ_FRAMEBUFFER 0x8CA8 -#endif - -#ifndef GL_DRAW_FRAMEBUFFER -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#endif - -#ifndef GL_MAX_IMAGE_UNITS -#define GL_MAX_IMAGE_UNITS 0x8F38 -#endif - -namespace { - -QOpenGLShader::ShaderType shaderType(Qt3DRender::QShaderProgram::ShaderType type) -{ - switch (type) { - case Qt3DRender::QShaderProgram::Vertex: return QOpenGLShader::Vertex; - case Qt3DRender::QShaderProgram::TessellationControl: return QOpenGLShader::TessellationControl; - case Qt3DRender::QShaderProgram::TessellationEvaluation: return QOpenGLShader::TessellationEvaluation; - case Qt3DRender::QShaderProgram::Geometry: return QOpenGLShader::Geometry; - case Qt3DRender::QShaderProgram::Fragment: return QOpenGLShader::Fragment; - case Qt3DRender::QShaderProgram::Compute: return QOpenGLShader::Compute; - default: Q_UNREACHABLE(); - } -} - -} // anonymous namespace - -namespace Qt3DRender { -namespace Render { - -namespace { - -void logOpenGLDebugMessage(const QOpenGLDebugMessage &debugMessage) -{ - qDebug() << "OpenGL debug message:" << debugMessage; -} - -} // anonymous - -GraphicsContext::GraphicsContext() - : m_initialized(false) - , m_supportsVAO(false) - , m_maxTextureUnits(0) - , m_maxImageUnits(0) - , m_defaultFBO(0) - , m_gl(nullptr) - , m_glHelper(nullptr) - , m_debugLogger(nullptr) - , m_currentVAO(nullptr) -{ -} - -GraphicsContext::~GraphicsContext() -{ -} - -void GraphicsContext::setOpenGLContext(QOpenGLContext* ctx) -{ - Q_ASSERT(ctx); - m_gl = ctx; -} - -void GraphicsContext::initialize() -{ - m_initialized = true; - - Q_ASSERT(m_gl); - - m_gl->functions()->glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &m_maxTextureUnits); - qCDebug(Backend) << "context supports" << m_maxTextureUnits << "texture units"; - m_gl->functions()->glGetIntegerv(GL_MAX_IMAGE_UNITS, &m_maxImageUnits); - qCDebug(Backend) << "context supports" << m_maxImageUnits << "image units"; - - if (m_gl->format().majorVersion() >= 3) { - m_supportsVAO = true; - } else { - QSet extensions = m_gl->extensions(); - m_supportsVAO = extensions.contains(QByteArrayLiteral("GL_OES_vertex_array_object")) - || extensions.contains(QByteArrayLiteral("GL_ARB_vertex_array_object")) - || extensions.contains(QByteArrayLiteral("GL_APPLE_vertex_array_object")); - } - - m_defaultFBO = m_gl->defaultFramebufferObject(); - qCDebug(Backend) << "VAO support = " << m_supportsVAO; -} - -void GraphicsContext::clearBackBuffer(QClearBuffers::BufferTypeFlags buffers) -{ - if (buffers != QClearBuffers::None) { - GLbitfield mask = 0; - - if (buffers & QClearBuffers::ColorBuffer) - mask |= GL_COLOR_BUFFER_BIT; - if (buffers & QClearBuffers::DepthBuffer) - mask |= GL_DEPTH_BUFFER_BIT; - if (buffers & QClearBuffers::StencilBuffer) - mask |= GL_STENCIL_BUFFER_BIT; - - m_gl->functions()->glClear(mask); - } -} - -bool GraphicsContext::hasValidGLHelper() const -{ - return m_glHelper != nullptr; -} - -bool GraphicsContext::isInitialized() const -{ - return m_initialized; -} - -bool GraphicsContext::makeCurrent(QSurface *surface) -{ - Q_ASSERT(m_gl); - if (!m_gl->makeCurrent(surface)) { - qCWarning(Backend) << Q_FUNC_INFO << "makeCurrent failed"; - return false; - } - - initializeHelpers(surface); - - return true; -} - -void GraphicsContext::initializeHelpers(QSurface *surface) -{ - // Set the correct GL Helper depending on the surface - // If no helper exists, create one - m_glHelper = m_glHelpers.value(surface); - if (!m_glHelper) { - m_glHelper = resolveHighestOpenGLFunctions(); - m_glHelpers.insert(surface, m_glHelper); - } -} - -void GraphicsContext::doneCurrent() -{ - Q_ASSERT(m_gl); - m_gl->doneCurrent(); - m_glHelper = nullptr; -} - -// Called by GL Command Thread -GraphicsContext::ShaderCreationInfo GraphicsContext::createShaderProgram(GLShader *shader) -{ - QOpenGLShaderProgram *shaderProgram = shader->shaderProgram(); - - // Compile shaders - const auto shaderCode = shader->shaderCode(); - - QString logs; - for (int i = QShaderProgram::Vertex; i <= QShaderProgram::Compute; ++i) { - const QShaderProgram::ShaderType type = static_cast(i); - if (!shaderCode.at(i).isEmpty()) { - // Note: logs only return the error but not all the shader code - // we could append it - if (!shaderProgram->addCacheableShaderFromSourceCode(shaderType(type), shaderCode.at(i))) - logs += shaderProgram->log(); - } - } - - // Call glBindFragDataLocation and link the program - // Since we are sharing shaders in the backend, we assume that if using custom - // fragOutputs, they should all be the same for a given shader - bindFragOutputs(shaderProgram->programId(), shader->fragOutputs()); - - const bool linkSucceeded = shaderProgram->link(); - logs += shaderProgram->log(); - - // Perform shader introspection - introspectShaderInterface(shader); - - ShaderCreationInfo info; - info.linkSucceeded = linkSucceeded; - info.logs = logs; - - return info; -} - -// That assumes that the shaderProgram in Shader stays the same -void GraphicsContext::introspectShaderInterface(GLShader *shader) -{ - QOpenGLShaderProgram *shaderProgram = shader->shaderProgram(); - GraphicsHelperInterface *glHelper = resolveHighestOpenGLFunctions(); - shader->initializeUniforms(glHelper->programUniformsAndLocations(shaderProgram->programId())); - shader->initializeAttributes(glHelper->programAttributesAndLocations(shaderProgram->programId())); - if (m_glHelper->supportsFeature(GraphicsHelperInterface::UniformBufferObject)) - shader->initializeUniformBlocks(m_glHelper->programUniformBlocks(shaderProgram->programId())); - if (m_glHelper->supportsFeature(GraphicsHelperInterface::ShaderStorageObject)) - shader->initializeShaderStorageBlocks(m_glHelper->programShaderStorageBlocks(shaderProgram->programId())); -} - - -// Called by Renderer::updateGLResources -void GraphicsContext::loadShader(Shader *shaderNode, - ShaderManager *shaderManager, - GLShaderManager *glShaderManager) -{ - const Qt3DCore::QNodeId shaderId = shaderNode->peerId(); - GLShader *glShader = glShaderManager->lookupResource(shaderId); - - // We already have a shader associated with the node - if (glShader != nullptr) { - // We need to abandon it - glShaderManager->abandon(glShader, shaderNode); - } - - // We create or adopt an already created glShader - glShader = glShaderManager->createOrAdoptExisting(shaderNode); - - const QVector sharedShaderIds = glShaderManager->shaderIdsForProgram(glShader); - if (sharedShaderIds.size() == 1) { - // Shader in the cache hasn't been loaded yet - glShader->setGraphicsContext(this); - glShader->setShaderCode(shaderNode->shaderCode()); - const ShaderCreationInfo loadResult = createShaderProgram(glShader); - shaderNode->setStatus(loadResult.linkSucceeded ? QShaderProgram::Ready : QShaderProgram::Error); - shaderNode->setLog(loadResult.logs); - // Loaded in the sense we tried to load it (and maybe it failed) - glShader->setLoaded(true); - } else { - // Find an already loaded shader that shares the same QOpenGLShaderProgram - for (const Qt3DCore::QNodeId sharedShaderId : sharedShaderIds) { - if (sharedShaderId != shaderNode->peerId()) { - Shader *refShader = shaderManager->lookupResource(sharedShaderId); - // We only introspect once per actual OpenGL shader program - // rather than once per ShaderNode. - shaderNode->initializeFromReference(*refShader); - break; - } - } - } - shaderNode->unsetDirty(); - // Ensure we will rebuilt material caches - shaderNode->markDirty(AbstractRenderer::AllDirty); -} - -void GraphicsContext::activateDrawBuffers(const AttachmentPack &attachments) -{ - const QVector activeDrawBuffers = attachments.getGlDrawBuffers(); - - if (m_glHelper->checkFrameBufferComplete()) { - if (activeDrawBuffers.size() > 1) {// We need MRT - if (m_glHelper->supportsFeature(GraphicsHelperInterface::MRT)) { - // Set up MRT, glDrawBuffers... - m_glHelper->drawBuffers(activeDrawBuffers.size(), activeDrawBuffers.data()); - } - } - } else { - qWarning() << "FBO incomplete"; - } -} - -void GraphicsContext::rasterMode(GLenum faceMode, GLenum rasterMode) -{ - m_glHelper->rasterMode(faceMode, rasterMode); -} - -/*! - * \internal - * Finds the highest supported opengl version and internally use the most optimized - * helper for a given version. - */ -GraphicsHelperInterface *GraphicsContext::resolveHighestOpenGLFunctions() -{ - Q_ASSERT(m_gl); - GraphicsHelperInterface *glHelper = nullptr; - - if (m_gl->isOpenGLES()) { - if (m_gl->format().majorVersion() >= 3) { - if (m_gl->format().minorVersion() >= 2) { - glHelper = new GraphicsHelperES3_2; - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES 3.2 Helper"; - } else if (m_gl->format().minorVersion() >= 1) { - glHelper = new GraphicsHelperES3_1; - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES 3.1 Helper"; - } else { - glHelper = new GraphicsHelperES3(); - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES 3.0 Helper"; - } - } else { - glHelper = new GraphicsHelperES2(); - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL ES2 Helper"; - } - glHelper->initializeHelper(m_gl, nullptr); - } -#ifndef QT_OPENGL_ES_2 - else { - QAbstractOpenGLFunctions *glFunctions = nullptr; - if ((glFunctions = m_gl->versionFunctions()) != nullptr) { - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 4.3"; - glHelper = new GraphicsHelperGL4(); - } else if ((glFunctions = m_gl->versionFunctions()) != nullptr) { - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 3.3"; - glHelper = new GraphicsHelperGL3_3(); - } else if ((glFunctions = m_gl->versionFunctions()) != nullptr) { - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 3.2"; - glHelper = new GraphicsHelperGL3_2(); - } else if ((glFunctions = m_gl->versionFunctions()) != nullptr) { - qCDebug(Backend) << Q_FUNC_INFO << " Building OpenGL 2 Helper"; - glHelper = new GraphicsHelperGL2(); - } - Q_ASSERT_X(glHelper, "GraphicsContext::resolveHighestOpenGLFunctions", "unable to create valid helper for available OpenGL version"); - glHelper->initializeHelper(m_gl, glFunctions); - } -#endif - - // Note: at this point we are certain the context (m_gl) is current with a surface - const QByteArray debugLoggingMode = qgetenv("QT3DRENDER_DEBUG_LOGGING"); - const bool enableDebugLogging = !debugLoggingMode.isEmpty(); - - if (enableDebugLogging && !m_debugLogger) { - if (m_gl->hasExtension("GL_KHR_debug")) { - qCDebug(Backend) << "Qt3D: Enabling OpenGL debug logging"; - m_debugLogger.reset(new QOpenGLDebugLogger); - if (m_debugLogger->initialize()) { - QObject::connect(m_debugLogger.data(), &QOpenGLDebugLogger::messageLogged, &logOpenGLDebugMessage); - const QString mode = QString::fromLocal8Bit(debugLoggingMode); - m_debugLogger->startLogging(mode.startsWith(QLatin1String("sync"), Qt::CaseInsensitive) - ? QOpenGLDebugLogger::SynchronousLogging - : QOpenGLDebugLogger::AsynchronousLogging); - - const auto msgs = m_debugLogger->loggedMessages(); - for (const QOpenGLDebugMessage &msg : msgs) - logOpenGLDebugMessage(msg); - } - } else { - qCDebug(Backend) << "Qt3D: OpenGL debug logging requested but GL_KHR_debug not supported"; - } - } - - - // Set Vendor and Extensions of reference GraphicsApiFilter - // TO DO: would that vary like the glHelper ? - - QStringList extensions; - const auto exts = m_gl->extensions(); - for (const QByteArray &ext : exts) - extensions << QString::fromUtf8(ext); - m_contextInfo.m_major = m_gl->format().version().first; - m_contextInfo.m_minor = m_gl->format().version().second; - m_contextInfo.m_api = m_gl->isOpenGLES() ? QGraphicsApiFilter::OpenGLES : QGraphicsApiFilter::OpenGL; - m_contextInfo.m_profile = static_cast(m_gl->format().profile()); - m_contextInfo.m_extensions = extensions; - m_contextInfo.m_vendor = QString::fromUtf8(reinterpret_cast(m_gl->functions()->glGetString(GL_VENDOR))); - - return glHelper; -} - -const GraphicsApiFilterData *GraphicsContext::contextInfo() const -{ - return &m_contextInfo; -} - -bool GraphicsContext::supportsDrawBuffersBlend() const -{ - return m_glHelper->supportsFeature(GraphicsHelperInterface::DrawBuffersBlend); -} - -/*! - * \internal - * Wraps an OpenGL call to glDrawElementsInstanced. - * If the call is not supported by the system's OpenGL version, - * it is simulated with a loop. - */ -void GraphicsContext::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - m_glHelper->drawElementsInstancedBaseVertexBaseInstance(primitiveType, - primitiveCount, - indexType, - indices, - instances, - baseVertex, - baseInstance); -} - -/*! - * \internal - * Wraps an OpenGL call to glDrawArraysInstanced. - */ -void GraphicsContext::drawArraysInstanced(GLenum primitiveType, - GLint first, - GLsizei count, - GLsizei instances) -{ - m_glHelper->drawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsContext::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseinstance) -{ - m_glHelper->drawArraysInstancedBaseInstance(primitiveType, - first, - count, - instances, - baseinstance); -} - -/*! - * \internal - * Wraps an OpenGL call to glDrawElements. - */ -void GraphicsContext::drawElements(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLint baseVertex) -{ - m_glHelper->drawElements(primitiveType, - primitiveCount, - indexType, - indices, - baseVertex); -} - -void GraphicsContext::drawElementsIndirect(GLenum mode, - GLenum type, - void *indirect) -{ - m_glHelper->drawElementsIndirect(mode, type, indirect); -} - -/*! - * \internal - * Wraps an OpenGL call to glDrawArrays. - */ -void GraphicsContext::drawArrays(GLenum primitiveType, - GLint first, - GLsizei count) -{ - m_glHelper->drawArrays(primitiveType, - first, - count); -} - -void GraphicsContext::drawArraysIndirect(GLenum mode, void *indirect) -{ - m_glHelper->drawArraysIndirect(mode, indirect); -} - -void GraphicsContext::setVerticesPerPatch(GLint verticesPerPatch) -{ - m_glHelper->setVerticesPerPatch(verticesPerPatch); -} - -void GraphicsContext::blendEquation(GLenum mode) -{ - m_glHelper->blendEquation(mode); -} - -void GraphicsContext::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) -{ - m_glHelper->blendFunci(buf, sfactor, dfactor); -} - -void GraphicsContext::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) -{ - m_glHelper->blendFuncSeparatei(buf, sRGB, dRGB, sAlpha, dAlpha); -} - -void GraphicsContext::alphaTest(GLenum mode1, GLenum mode2) -{ - m_glHelper->alphaTest(mode1, mode2); -} - -void GraphicsContext::bindFramebuffer(GLuint fbo, GraphicsHelperInterface::FBOBindMode mode) -{ - m_glHelper->bindFrameBufferObject(fbo, mode); -} - -void GraphicsContext::depthRange(GLdouble nearValue, GLdouble farValue) -{ - m_glHelper->depthRange(nearValue, farValue); -} - -void GraphicsContext::depthTest(GLenum mode) -{ - m_glHelper->depthTest(mode); -} - -void GraphicsContext::depthMask(GLenum mode) -{ - m_glHelper->depthMask(mode); -} - -void GraphicsContext::frontFace(GLenum mode) -{ - m_glHelper->frontFace(mode); -} - -void GraphicsContext::bindFragOutputs(GLuint shader, const QHash &outputs) -{ - if (m_glHelper->supportsFeature(GraphicsHelperInterface::MRT) && - m_glHelper->supportsFeature(GraphicsHelperInterface::BindableFragmentOutputs)) - m_glHelper->bindFragDataLocation(shader, outputs); -} - -void GraphicsContext::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - m_glHelper->bindImageTexture(imageUnit, - texture, - mipLevel, - layered, - layer, - access, - format); -} - -void GraphicsContext::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - m_glHelper->bindUniformBlock(programId, uniformBlockIndex, uniformBlockBinding); -} - -void GraphicsContext::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) -{ - m_glHelper->bindShaderStorageBlock(programId, shaderStorageBlockIndex, shaderStorageBlockBinding); -} - -void GraphicsContext::bindBufferBase(GLenum target, GLuint bindingIndex, GLuint buffer) -{ - m_glHelper->bindBufferBase(target, bindingIndex, buffer); -} - -void GraphicsContext::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - m_glHelper->buildUniformBuffer(v, description, buffer); -} - -void GraphicsContext::setMSAAEnabled(bool enabled) -{ - m_glHelper->setMSAAEnabled(enabled); -} - -void GraphicsContext::setAlphaCoverageEnabled(bool enabled) -{ - m_glHelper->setAlphaCoverageEnabled(enabled); -} - -void GraphicsContext::clearBufferf(GLint drawbuffer, const QVector4D &values) -{ - m_glHelper->clearBufferf(drawbuffer, values); -} - -GLuint GraphicsContext::boundFrameBufferObject() -{ - return m_glHelper->boundFrameBufferObject(); -} - -void GraphicsContext::clearColor(const QColor &color) -{ - m_gl->functions()->glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); -} - -void GraphicsContext::clearDepthValue(float depth) -{ - m_gl->functions()->glClearDepthf(depth); -} - -void GraphicsContext::clearStencilValue(int stencil) -{ - m_gl->functions()->glClearStencil(stencil); -} - -void GraphicsContext::enableClipPlane(int clipPlane) -{ - m_glHelper->enableClipPlane(clipPlane); -} - -void GraphicsContext::disableClipPlane(int clipPlane) -{ - m_glHelper->disableClipPlane(clipPlane); -} - -void GraphicsContext::setClipPlane(int clipPlane, const QVector3D &normal, float distance) -{ - m_glHelper->setClipPlane(clipPlane, normal, distance); -} - -GLint GraphicsContext::maxClipPlaneCount() -{ - return m_glHelper->maxClipPlaneCount(); -} - -GLint GraphicsContext::maxTextureUnitsCount() const -{ - return m_maxTextureUnits; -} - -GLint GraphicsContext::maxImageUnitsCount() const -{ - return m_maxImageUnits; -} - - -void GraphicsContext::enablePrimitiveRestart(int restartIndex) -{ - if (m_glHelper->supportsFeature(GraphicsHelperInterface::PrimitiveRestart)) - m_glHelper->enablePrimitiveRestart(restartIndex); -} - -void GraphicsContext::disablePrimitiveRestart() -{ - if (m_glHelper->supportsFeature(GraphicsHelperInterface::PrimitiveRestart)) - m_glHelper->disablePrimitiveRestart(); -} - -void GraphicsContext::pointSize(bool programmable, GLfloat value) -{ - m_glHelper->pointSize(programmable, value); -} - -void GraphicsContext::dispatchCompute(int x, int y, int z) -{ - if (m_glHelper->supportsFeature(GraphicsHelperInterface::Compute)) - m_glHelper->dispatchCompute(x, y, z); -} - -GLboolean GraphicsContext::unmapBuffer(GLenum target) -{ - return m_glHelper->unmapBuffer(target); -} - -char *GraphicsContext::mapBuffer(GLenum target, GLsizeiptr size) -{ - return m_glHelper->mapBuffer(target, size); -} - -void GraphicsContext::enablei(GLenum cap, GLuint index) -{ - m_glHelper->enablei(cap, index); -} - -void GraphicsContext::disablei(GLenum cap, GLuint index) -{ - m_glHelper->disablei(cap, index); -} - -void GraphicsContext::setSeamlessCubemap(bool enable) -{ - m_glHelper->setSeamlessCubemap(enable); -} - -void GraphicsContext::readBuffer(GLenum mode) -{ - m_glHelper->readBuffer(mode); -} - -void GraphicsContext::drawBuffer(GLenum mode) -{ - m_glHelper->drawBuffer(mode); -} - -void GraphicsContext::drawBuffers(GLsizei n, const int *bufs) -{ - m_glHelper->drawBuffers(n, bufs); -} - -void GraphicsContext::applyUniform(const ShaderUniform &description, const UniformValue &v) -{ - const UniformType type = m_glHelper->uniformTypeFromGLType(description.m_type); - - switch (type) { - case UniformType::Float: - // See QTBUG-57510 and uniform_p.h - if (v.storedType() == Int) { - float value = float(*v.constData()); - UniformValue floatV(value); - applyUniformHelper(description, floatV); - } else { - applyUniformHelper(description, v); - } - break; - case UniformType::Vec2: - applyUniformHelper(description, v); - break; - case UniformType::Vec3: - applyUniformHelper(description, v); - break; - case UniformType::Vec4: - applyUniformHelper(description, v); - break; - - case UniformType::Double: - applyUniformHelper(description, v); - break; - case UniformType::DVec2: - applyUniformHelper(description, v); - break; - case UniformType::DVec3: - applyUniformHelper(description, v); - break; - case UniformType::DVec4: - applyUniformHelper(description, v); - break; - - case UniformType::Sampler: - case UniformType::Image: - case UniformType::Int: - applyUniformHelper(description, v); - break; - case UniformType::IVec2: - applyUniformHelper(description, v); - break; - case UniformType::IVec3: - applyUniformHelper(description, v); - break; - case UniformType::IVec4: - applyUniformHelper(description, v); - break; - - case UniformType::UInt: - applyUniformHelper(description, v); - break; - case UniformType::UIVec2: - applyUniformHelper(description, v); - break; - case UniformType::UIVec3: - applyUniformHelper(description, v); - break; - case UniformType::UIVec4: - applyUniformHelper(description, v); - break; - - case UniformType::Bool: - applyUniformHelper(description, v); - break; - case UniformType::BVec2: - applyUniformHelper(description, v); - break; - case UniformType::BVec3: - applyUniformHelper(description, v); - break; - case UniformType::BVec4: - applyUniformHelper(description, v); - break; - - case UniformType::Mat2: - applyUniformHelper(description, v); - break; - case UniformType::Mat3: - applyUniformHelper(description, v); - break; - case UniformType::Mat4: - applyUniformHelper(description, v); - break; - case UniformType::Mat2x3: - applyUniformHelper(description, v); - break; - case UniformType::Mat3x2: - applyUniformHelper(description, v); - break; - case UniformType::Mat2x4: - applyUniformHelper(description, v); - break; - case UniformType::Mat4x2: - applyUniformHelper(description, v); - break; - case UniformType::Mat3x4: - applyUniformHelper(description, v); - break; - case UniformType::Mat4x3: - applyUniformHelper(description, v); - break; - - default: - break; - } -} - -void GraphicsContext::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - m_glHelper->memoryBarrier(barriers); -} - -GLint GraphicsContext::elementType(GLint type) -{ - switch (type) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - return GL_FLOAT; - -#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 - case GL_DOUBLE: -#ifdef GL_DOUBLE_VEC3 // For compiling on pre GL 4.1 systems - case GL_DOUBLE_VEC2: - case GL_DOUBLE_VEC3: - case GL_DOUBLE_VEC4: -#endif - return GL_DOUBLE; -#endif - default: - qWarning() << Q_FUNC_INFO << "unsupported:" << QString::number(type, 16); - } - - return GL_INVALID_VALUE; -} - -GLint GraphicsContext::tupleSizeFromType(GLint type) -{ - switch (type) { - case GL_FLOAT: -#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 - case GL_DOUBLE: -#endif - case GL_UNSIGNED_BYTE: - case GL_UNSIGNED_INT: - break; // fall through - - case GL_FLOAT_VEC2: -#ifdef GL_DOUBLE_VEC2 // For compiling on pre GL 4.1 systems. - case GL_DOUBLE_VEC2: -#endif - return 2; - - case GL_FLOAT_VEC3: -#ifdef GL_DOUBLE_VEC3 // For compiling on pre GL 4.1 systems. - case GL_DOUBLE_VEC3: -#endif - return 3; - - case GL_FLOAT_VEC4: -#ifdef GL_DOUBLE_VEC4 // For compiling on pre GL 4.1 systems. - case GL_DOUBLE_VEC4: -#endif - return 4; - - default: - qWarning() << Q_FUNC_INFO << "unsupported:" << QString::number(type, 16); - } - - return 1; -} - -GLuint GraphicsContext::byteSizeFromType(GLint type) -{ - switch (type) { - case GL_FLOAT: return sizeof(float); -#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 - case GL_DOUBLE: return sizeof(double); -#endif - case GL_UNSIGNED_BYTE: return sizeof(unsigned char); - case GL_UNSIGNED_INT: return sizeof(GLuint); - - case GL_FLOAT_VEC2: return sizeof(float) * 2; - case GL_FLOAT_VEC3: return sizeof(float) * 3; - case GL_FLOAT_VEC4: return sizeof(float) * 4; -#ifdef GL_DOUBLE_VEC3 // Required to compile on pre GL 4.1 systems - case GL_DOUBLE_VEC2: return sizeof(double) * 2; - case GL_DOUBLE_VEC3: return sizeof(double) * 3; - case GL_DOUBLE_VEC4: return sizeof(double) * 4; -#endif - default: - qWarning() << Q_FUNC_INFO << "unsupported:" << QString::number(type, 16); - } - - return 0; -} - -GLint GraphicsContext::glDataTypeFromAttributeDataType(QAttribute::VertexBaseType dataType) -{ - switch (dataType) { - case QAttribute::Byte: - return GL_BYTE; - case QAttribute::UnsignedByte: - return GL_UNSIGNED_BYTE; - case QAttribute::Short: - return GL_SHORT; - case QAttribute::UnsignedShort: - return GL_UNSIGNED_SHORT; - case QAttribute::Int: - return GL_INT; - case QAttribute::UnsignedInt: - return GL_UNSIGNED_INT; - case QAttribute::HalfFloat: -#ifdef GL_HALF_FLOAT - return GL_HALF_FLOAT; -#endif -#ifndef QT_OPENGL_ES_2 // Otherwise compile error as Qt defines GL_DOUBLE as GL_FLOAT when using ES2 - case QAttribute::Double: - return GL_DOUBLE; -#endif - case QAttribute::Float: - break; - default: - qWarning() << Q_FUNC_INFO << "unsupported dataType:" << dataType; - } - return GL_FLOAT; -} - -QT3D_UNIFORM_TYPE_IMPL(UniformType::Float, float, glUniform1fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Vec2, float, glUniform2fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Vec3, float, glUniform3fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Vec4, float, glUniform4fv) - -// OpenGL expects int* as values for booleans -QT3D_UNIFORM_TYPE_IMPL(UniformType::Bool, int, glUniform1iv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::BVec2, int, glUniform2iv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::BVec3, int, glUniform3iv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::BVec4, int, glUniform4iv) - -QT3D_UNIFORM_TYPE_IMPL(UniformType::Int, int, glUniform1iv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::IVec2, int, glUniform2iv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::IVec3, int, glUniform3iv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::IVec4, int, glUniform4iv) - -QT3D_UNIFORM_TYPE_IMPL(UniformType::UInt, uint, glUniform1uiv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::UIVec2, uint, glUniform2uiv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::UIVec3, uint, glUniform3uiv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::UIVec4, uint, glUniform4uiv) - -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat2, float, glUniformMatrix2fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3, float, glUniformMatrix3fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4, float, glUniformMatrix4fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat2x3, float, glUniformMatrix2x3fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3x2, float, glUniformMatrix3x2fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat2x4, float, glUniformMatrix2x4fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4x2, float, glUniformMatrix4x2fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3x4, float, glUniformMatrix3x4fv) -QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4x3, float, glUniformMatrix4x3fv) - -} // namespace Render -} // namespace Qt3DRender of namespace - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h b/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h deleted file mode 100644 index d3f3615d5..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h +++ /dev/null @@ -1,264 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSCONTEXT_H -#define QT3DRENDER_RENDER_GRAPHICSCONTEXT_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLShaderProgram; -class QAbstractOpenGLFunctions; -class QOpenGLDebugLogger; - -namespace Qt3DRender { - -namespace Render { - -class GraphicsHelperInterface; -class RenderTarget; -class AttachmentPack; -class ShaderManager; -class GLShader; -class GLShaderManager; - -typedef QPair NamedUniformLocation; - -class Q_AUTOTEST_EXPORT GraphicsContext -{ -public: - GraphicsContext(); - ~GraphicsContext(); - - void setOpenGLContext(QOpenGLContext* ctx); - QOpenGLContext *openGLContext() { return m_gl; } - bool makeCurrent(QSurface *surface); - void doneCurrent(); - bool hasValidGLHelper() const; - bool isInitialized() const; - - // Shaders - struct ShaderCreationInfo - { - bool linkSucceeded = false; - QString logs; - }; - - ShaderCreationInfo createShaderProgram(GLShader *shaderNode); - void introspectShaderInterface(GLShader *shader); - void loadShader(Shader* shader, ShaderManager *shaderManager, GLShaderManager *glShaderManager); - - GLuint defaultFBO() const { return m_defaultFBO; } - - const GraphicsApiFilterData *contextInfo() const; - - // Wrapper methods - void clearBackBuffer(QClearBuffers::BufferTypeFlags buffers); - void alphaTest(GLenum mode1, GLenum mode2); - void bindFramebuffer(GLuint fbo, GraphicsHelperInterface::FBOBindMode mode); - void bindBufferBase(GLenum target, GLuint bindingIndex, GLuint buffer); - void bindFragOutputs(GLuint shader, const QHash &outputs); - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format); - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding); - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding); - void blendEquation(GLenum mode); - void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor); - void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha); - GLuint boundFrameBufferObject(); - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer); - void clearBufferf(GLint drawbuffer, const QVector4D &values); - void clearColor(const QColor &color); - void clearDepthValue(float depth); - void clearStencilValue(int stencil); - void depthRange(GLdouble nearValue, GLdouble farValue); - void depthMask(GLenum mode); - void depthTest(GLenum mode); - void disableClipPlane(int clipPlane); - void disablei(GLenum cap, GLuint index); - void disablePrimitiveRestart(); - void dispatchCompute(int x, int y, int z); - char * mapBuffer(GLenum target, GLsizeiptr size); - GLboolean unmapBuffer(GLenum target); - void drawArrays(GLenum primitiveType, GLint first, GLsizei count); - void drawArraysIndirect(GLenum mode,void *indirect); - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances); - void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseinstance); - void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLint baseVertex); - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect); - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLsizei instances, GLint baseVertex, GLint baseInstance); - void enableClipPlane(int clipPlane); - void enablei(GLenum cap, GLuint index); - void enablePrimitiveRestart(int restartIndex); - void frontFace(GLenum mode); - GLint maxClipPlaneCount(); - GLint maxTextureUnitsCount() const; - GLint maxImageUnitsCount() const; - void pointSize(bool programmable, GLfloat value); - void readBuffer(GLenum mode); - void drawBuffer(GLenum mode); - void drawBuffers(GLsizei n, const int *bufs); - void setMSAAEnabled(bool enabled); - void setAlphaCoverageEnabled(bool enabled); - void setClipPlane(int clipPlane, const QVector3D &normal, float distance); - void setSeamlessCubemap(bool enable); - void setVerticesPerPatch(GLint verticesPerPatch); - void memoryBarrier(QMemoryBarrier::Operations barriers); - void activateDrawBuffers(const AttachmentPack &attachments); - void rasterMode(GLenum faceMode, GLenum rasterMode); - - // Helper methods - static GLint elementType(GLint type); - static GLint tupleSizeFromType(GLint type); - static GLuint byteSizeFromType(GLint type); - static GLint glDataTypeFromAttributeDataType(QAttribute::VertexBaseType dataType); - - bool supportsDrawBuffersBlend() const; - bool supportsVAO() const { return m_supportsVAO; } - - void initialize(); - void initializeHelpers(QSurface *surface); - GraphicsHelperInterface *resolveHighestOpenGLFunctions(); - - bool m_initialized; - bool m_supportsVAO; - GLint m_maxTextureUnits; - GLint m_maxImageUnits; - GLuint m_defaultFBO; - QOpenGLContext *m_gl; - GraphicsHelperInterface *m_glHelper; - - QHash m_glHelpers; - GraphicsApiFilterData m_contextInfo; - QScopedPointer m_debugLogger; - - friend class OpenGLVertexArrayObject; - OpenGLVertexArrayObject *m_currentVAO; - - void applyUniform(const ShaderUniform &description, const UniformValue &v); - - template - void applyUniformHelper(const ShaderUniform &, const UniformValue &) const - { - Q_ASSERT_X(false, Q_FUNC_INFO, "Uniform: Didn't provide specialized apply() implementation"); - } -}; - -#define QT3D_UNIFORM_TYPE_PROTO(UniformTypeEnum, BaseType, Func) \ -template<> \ -void GraphicsContext::applyUniformHelper(const ShaderUniform &description, const UniformValue &value) const; - -#define QT3D_UNIFORM_TYPE_IMPL(UniformTypeEnum, BaseType, Func) \ - template<> \ - void GraphicsContext::applyUniformHelper(const ShaderUniform &description, const UniformValue &value) const \ -{ \ - const int count = qMin(description.m_size, int(value.byteSize() / description.m_rawByteSize)); \ - m_glHelper->Func(description.m_location, count, value.constData()); \ -} - - -QT3D_UNIFORM_TYPE_PROTO(UniformType::Float, float, glUniform1fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Vec2, float, glUniform2fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Vec3, float, glUniform3fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Vec4, float, glUniform4fv) - -// OpenGL expects int* as values for booleans -QT3D_UNIFORM_TYPE_PROTO(UniformType::Bool, int, glUniform1iv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::BVec2, int, glUniform2iv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::BVec3, int, glUniform3iv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::BVec4, int, glUniform4iv) - -QT3D_UNIFORM_TYPE_PROTO(UniformType::Int, int, glUniform1iv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::IVec2, int, glUniform2iv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::IVec3, int, glUniform3iv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::IVec4, int, glUniform4iv) - -QT3D_UNIFORM_TYPE_PROTO(UniformType::UInt, uint, glUniform1uiv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::UIVec2, uint, glUniform2uiv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::UIVec3, uint, glUniform3uiv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::UIVec4, uint, glUniform4uiv) - -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat2, float, glUniformMatrix2fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3, float, glUniformMatrix3fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4, float, glUniformMatrix4fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat2x3, float, glUniformMatrix2x3fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3x2, float, glUniformMatrix3x2fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat2x4, float, glUniformMatrix2x4fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4x2, float, glUniformMatrix4x2fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3x4, float, glUniformMatrix3x4fv) -QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4x3, float, glUniformMatrix4x3fv) - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GRAPHICSCONTEXT_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp deleted file mode 100644 index 5f77dd376..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp +++ /dev/null @@ -1,1034 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelperes2_p.h" -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -// ES 3.0+ -#ifndef GL_SAMPLER_3D -#define GL_SAMPLER_3D 0x8B5F -#endif -#ifndef GL_SAMPLER_2D_SHADOW -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#endif -#ifndef GL_SAMPLER_CUBE_SHADOW -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#endif -#ifndef GL_SAMPLER_2D_ARRAY -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#endif -#ifndef GL_SAMPLER_2D_ARRAY_SHADOW -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#endif - -namespace Qt3DRender { -namespace Render { - -GraphicsHelperES2::GraphicsHelperES2() - : m_funcs(0) - , m_supportFramebufferBlit(false) -{ -} - -GraphicsHelperES2::~GraphicsHelperES2() -{ -} - -void GraphicsHelperES2::initializeHelper(QOpenGLContext *context, - QAbstractOpenGLFunctions *) -{ - Q_ASSERT(context); - m_funcs = context->functions(); - Q_ASSERT(m_funcs); - m_ext.reset(new QOpenGLExtensions(context)); - if (m_ext->hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit)) - m_supportFramebufferBlit = true; -} - -void GraphicsHelperES2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; - - if (baseVertex != 0) - qWarning() << "glDrawElementsInstancedBaseVertex is not supported with OpenGL ES 2"; - - for (GLint i = 0; i < instances; i++) - drawElements(primitiveType, - primitiveCount, - indexType, - indices); -} - -void GraphicsHelperES2::drawArraysInstanced(GLenum primitiveType, - GLint first, - GLsizei count, - GLsizei instances) -{ - for (GLint i = 0; i < instances; i++) - drawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperES2::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL ES 2"; - for (GLint i = 0; i < instances; i++) - drawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperES2::drawElements(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLint baseVertex) -{ - if (baseVertex != 0) - qWarning() << "glDrawElementsBaseVertex is not supported with OpenGL ES 2"; - QOpenGLExtensions *xfuncs = static_cast(m_funcs); - if (indexType == GL_UNSIGNED_INT && !xfuncs->hasOpenGLExtension(QOpenGLExtensions::ElementIndexUint)) { - static bool warnShown = false; - if (!warnShown) { - warnShown = true; - qWarning("GL_UNSIGNED_INT index type not supported on this system, skipping draw call."); - } - return; - } - m_funcs->glDrawElements(primitiveType, - primitiveCount, - indexType, - indices); -} - -void GraphicsHelperES2::drawArrays(GLenum primitiveType, - GLint first, - GLsizei count) -{ - m_funcs->glDrawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperES2::drawElementsIndirect(GLenum, GLenum, void *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "Indirect Drawing is not supported with OpenGL ES 2"; -} - -void GraphicsHelperES2::drawArraysIndirect(GLenum , void *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "Indirect Drawing is not supported with OpenGL ES 2"; -} - -void GraphicsHelperES2::setVerticesPerPatch(GLint verticesPerPatch) -{ - Q_UNUSED(verticesPerPatch); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "Tessellation not supported with OpenGL ES 2"; -} - -void GraphicsHelperES2::useProgram(GLuint programId) -{ - m_funcs->glUseProgram(programId); -} - -QVector GraphicsHelperES2::programUniformsAndLocations(GLuint programId) -{ - QVector uniforms; - - GLint nbrActiveUniforms = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); - uniforms.reserve(nbrActiveUniforms); - char uniformName[256]; - for (GLint i = 0; i < nbrActiveUniforms; i++) { - ShaderUniform uniform; - GLsizei uniformNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, - &uniform.m_size, &uniform.m_type, uniformName); - uniformName[sizeof(uniformName) - 1] = '\0'; - uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); - uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); - // Work around for uniform array names that aren't returned with [0] by some drivers - if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) - uniform.m_name.append(QLatin1String("[0]")); - uniform.m_rawByteSize = uniformByteSize(uniform); - uniforms.append(uniform); - } - return uniforms; -} - -QVector GraphicsHelperES2::programAttributesAndLocations(GLuint programId) -{ - QVector attributes; - GLint nbrActiveAttributes = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); - attributes.reserve(nbrActiveAttributes); - char attributeName[256]; - for (GLint i = 0; i < nbrActiveAttributes; i++) { - ShaderAttribute attribute; - GLsizei attributeNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, - &attribute.m_size, &attribute.m_type, attributeName); - attributeName[sizeof(attributeName) - 1] = '\0'; - attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); - attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); - attributes.append(attribute); - } - return attributes; -} - -QVector GraphicsHelperES2::programUniformBlocks(GLuint programId) -{ - Q_UNUSED(programId); - QVector blocks; - static bool showWarning = true; - if (!showWarning) - return blocks; - showWarning = false; - qWarning() << "UBO are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; - return blocks; -} - -QVector GraphicsHelperES2::programShaderStorageBlocks(GLuint programId) -{ - Q_UNUSED(programId); - QVector blocks; - static bool showWarning = true; - if (!showWarning) - return blocks; - showWarning = false; - qWarning() << "SSBO are not supported by OpenGL ES 2.0 (since OpenGL ES 3.1)"; - return blocks; -} - -void GraphicsHelperES2::vertexAttribDivisor(GLuint index, GLuint divisor) -{ - Q_UNUSED(index); - Q_UNUSED(divisor); -} - -void GraphicsHelperES2::vertexAttributePointer(GLenum shaderDataType, - GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const GLvoid *pointer) -{ - switch (shaderDataType) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - case GL_FLOAT_MAT2: - case GL_FLOAT_MAT3: - case GL_FLOAT_MAT4: - m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); - break; - - default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; - Q_UNREACHABLE(); - } -} - -void GraphicsHelperES2::readBuffer(GLenum mode) -{ - Q_UNUSED(mode) - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glReadBuffer not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; -} - -void GraphicsHelperES2::drawBuffer(GLenum mode) -{ - Q_UNUSED(mode); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glDrawBuffer is not supported with OpenGL ES 2"; -} - -void *GraphicsHelperES2::fenceSync() -{ - qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; - return nullptr; -} - -void GraphicsHelperES2::clientWaitSync(void *, GLuint64 ) -{ - qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; -} - -void GraphicsHelperES2::waitSync(void *) -{ - qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; -} - -bool GraphicsHelperES2::wasSyncSignaled(void *) -{ - qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; - return false; -} - -void GraphicsHelperES2::deleteSync(void *) -{ - qWarning() << "Fences are not supported by OpenGL ES 2.0 (since OpenGL ES 3.0)"; -} - -void GraphicsHelperES2::rasterMode(GLenum faceMode, GLenum rasterMode) -{ - Q_UNUSED(faceMode); - Q_UNUSED(rasterMode); - qWarning() << "glPolyonMode is not supported with OpenGL ES"; -} - -void GraphicsHelperES2::blendEquation(GLenum mode) -{ - m_funcs->glBlendEquation(mode); -} - -void GraphicsHelperES2::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) -{ - Q_UNUSED(buf); - Q_UNUSED(sfactor); - Q_UNUSED(dfactor); - - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glBlendFunci() not supported by OpenGL ES 2.0"; -} - -void GraphicsHelperES2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) -{ - Q_UNUSED(buf); - Q_UNUSED(sRGB); - Q_UNUSED(dRGB); - Q_UNUSED(sAlpha); - Q_UNUSED(dAlpha); - - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glBlendFuncSeparatei() not supported by OpenGL ES 2.0"; -} - -void GraphicsHelperES2::alphaTest(GLenum, GLenum) -{ - qCWarning(Render::Rendering) << Q_FUNC_INFO << "AlphaTest not available with OpenGL ES 2.0"; -} - -void GraphicsHelperES2::depthTest(GLenum mode) -{ - m_funcs->glEnable(GL_DEPTH_TEST); - m_funcs->glDepthFunc(mode); -} - -void GraphicsHelperES2::depthMask(GLenum mode) -{ - m_funcs->glDepthMask(mode); -} - -void GraphicsHelperES2::depthRange(GLdouble nearValue, GLdouble farValue) -{ - m_funcs->glDepthRangef(static_cast(nearValue), static_cast(farValue)); -} - -void GraphicsHelperES2::frontFace(GLenum mode) -{ - m_funcs->glFrontFace(mode); -} - -void GraphicsHelperES2::setMSAAEnabled(bool enabled) -{ - Q_UNUSED(enabled); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "MSAA not available with OpenGL ES 2.0"; -} - -void GraphicsHelperES2::setAlphaCoverageEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) - : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); -} - -GLuint GraphicsHelperES2::createFrameBufferObject() -{ - GLuint id; - m_funcs->glGenFramebuffers(1, &id); - return id; -} - -void GraphicsHelperES2::releaseFrameBufferObject(GLuint frameBufferId) -{ - m_funcs->glDeleteFramebuffers(1, &frameBufferId); -} - -void GraphicsHelperES2::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) -{ - Q_UNUSED(mode) - // For ES2 the spec states for target: The symbolic constant must be GL_FRAMEBUFFER - // so mode is ignored and is always set to GL_FRAMEBUFFER - m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); -} - -void GraphicsHelperES2::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - Q_UNUSED(imageUnit) - Q_UNUSED(texture) - Q_UNUSED(mipLevel) - Q_UNUSED(layered) - Q_UNUSED(layer) - Q_UNUSED(access) - Q_UNUSED(format) - qWarning() << "Shader Images are not supported by ES 2.0 (since ES 3.1)"; - -} - -GLuint GraphicsHelperES2::boundFrameBufferObject() -{ - GLint id = 0; - m_funcs->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id); - return id; -} - -bool GraphicsHelperES2::checkFrameBufferComplete() -{ - return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); -} - -bool GraphicsHelperES2::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - // Use a renderbuffer for depth or stencil attachments since this is - // problematic before GLES 3.2. Keep using textures for everything else. - // For ES2 individual Depth and Stencil buffers need to be an option because - // DepthStencil is an extension. - return attachment.m_point == QRenderTargetOutput::DepthStencil || - attachment.m_point == QRenderTargetOutput::Depth || - attachment.m_point == QRenderTargetOutput::Stencil; -} - -void GraphicsHelperES2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - GLenum attr = GL_COLOR_ATTACHMENT0; - - if (attachment.m_point == QRenderTargetOutput::Color0) - attr = GL_COLOR_ATTACHMENT0; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - else - qCritical() << "Unsupported FBO attachment OpenGL ES 2.0"; - - const QOpenGLTexture::Target target = texture->target(); - - if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face == QAbstractTexture::AllFaces) { - qWarning() << "OpenGL ES 2.0 doesn't handle attaching all the faces of a cube map texture at once to an FBO"; - return; - } - - texture->bind(); - if (target == QOpenGLTexture::Target2D) - m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); - else if (target == QOpenGLTexture::TargetCubeMap) - m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else - qCritical() << "Unsupported Texture FBO attachment format"; - texture->release(); -} - -void GraphicsHelperES2::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) -{ - if (attachment.m_point != QRenderTargetOutput::DepthStencil && - attachment.m_point != QRenderTargetOutput::Depth && - attachment.m_point != QRenderTargetOutput::Stencil) { - qCritical() << "Renderbuffers only supported for combined depth-stencil, depth, or stencil, but got attachment point" - << attachment.m_point; - return; - } - - renderBuffer->bind(); - if (attachment.m_point == QRenderTargetOutput::DepthStencil || - attachment.m_point == QRenderTargetOutput::Depth) - m_funcs->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer->renderBufferId()); - if (attachment.m_point == QRenderTargetOutput::DepthStencil || - attachment.m_point == QRenderTargetOutput::Stencil) - m_funcs->glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBuffer->renderBufferId()); - renderBuffer->release(); -} - -bool GraphicsHelperES2::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case RenderBufferDimensionRetrieval: - return true; - case BlitFramebuffer: - return m_supportFramebufferBlit; - default: - return false; - } -} - -void GraphicsHelperES2::drawBuffers(GLsizei, const int *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "drawBuffers is not supported by ES 2.0"; -} - -void GraphicsHelperES2::bindFragDataLocation(GLuint , const QHash &) -{ - qCritical() << "bindFragDataLocation is not supported by ES 2.0"; -} - -void GraphicsHelperES2::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - Q_UNUSED(programId); - Q_UNUSED(uniformBlockIndex); - Q_UNUSED(uniformBlockBinding); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "UBO are not supported by ES 2.0 (since ES 3.0)"; -} - -void GraphicsHelperES2::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) -{ - Q_UNUSED(programId); - Q_UNUSED(shaderStorageBlockIndex); - Q_UNUSED(shaderStorageBlockBinding); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "SSBO are not supported by ES 2.0 (since ES 3.1)"; -} - -void GraphicsHelperES2::bindBufferBase(GLenum target, GLuint index, GLuint buffer) -{ - Q_UNUSED(target); - Q_UNUSED(index); - Q_UNUSED(buffer); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "bindBufferBase is not supported by ES 2.0 (since ES 3.0)"; -} - -void GraphicsHelperES2::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - Q_UNUSED(v); - Q_UNUSED(description); - Q_UNUSED(buffer); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "UBO are not supported by ES 2.0 (since ES 3.0)"; -} - -uint GraphicsHelperES2::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - int arrayStride = qMax(description.m_arrayStride, 0); - int matrixStride = qMax(description.m_matrixStride, 0); - - switch (description.m_type) { - - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - rawByteSize = 8; - break; - - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - rawByteSize = 12; - break; - - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - rawByteSize = 16; - break; - - case GL_FLOAT_MAT2: - rawByteSize = matrixStride ? 2 * matrixStride : 16; - break; - - case GL_FLOAT_MAT3: - rawByteSize = matrixStride ? 3 * matrixStride : 36; - break; - - case GL_FLOAT_MAT4: - rawByteSize = matrixStride ? 4 * matrixStride : 64; - break; - - case GL_BOOL: - rawByteSize = 1; - break; - - case GL_BOOL_VEC2: - rawByteSize = 2; - break; - - case GL_BOOL_VEC3: - rawByteSize = 3; - break; - - case GL_BOOL_VEC4: - rawByteSize = 4; - break; - - case GL_INT: - case GL_FLOAT: - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - rawByteSize = 4; - break; - } - - return arrayStride ? rawByteSize * arrayStride : rawByteSize; -} - -void GraphicsHelperES2::enableClipPlane(int) -{ -} - -void GraphicsHelperES2::disableClipPlane(int) -{ -} - -void GraphicsHelperES2::setClipPlane(int, const QVector3D &, float) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "Clip planes not supported by OpenGL ES 2.0"; -} - -GLint GraphicsHelperES2::maxClipPlaneCount() -{ - return 0; -} - -void GraphicsHelperES2::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - Q_UNUSED(barriers); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "memory barrier is not supported by OpenGL ES 2.0 (since 4.3)"; -} - -void GraphicsHelperES2::enablePrimitiveRestart(int) -{ -} - -void GraphicsHelperES2::enableVertexAttributeArray(int location) -{ - m_funcs->glEnableVertexAttribArray(location); -} - -void GraphicsHelperES2::disablePrimitiveRestart() -{ -} - -void GraphicsHelperES2::clearBufferf(GLint drawbuffer, const QVector4D &values) -{ - Q_UNUSED(drawbuffer); - Q_UNUSED(values); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glClearBuffer*() not supported by OpenGL ES 2.0"; -} - -void GraphicsHelperES2::pointSize(bool programmable, GLfloat value) -{ - // If this is not a reset to default values, print a warning - if (programmable || !qFuzzyCompare(value, 1.0f)) { - static bool warned = false; - if (!warned) { - qWarning() << "glPointSize() and GL_PROGRAM_POINT_SIZE are not supported by ES 2.0"; - warned = true; - } - } -} - -void GraphicsHelperES2::enablei(GLenum cap, GLuint index) -{ - Q_UNUSED(cap); - Q_UNUSED(index); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glEnablei() not supported by OpenGL ES 2.0"; -} - -void GraphicsHelperES2::disablei(GLenum cap, GLuint index) -{ - Q_UNUSED(cap); - Q_UNUSED(index); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glDisablei() not supported by OpenGL ES 2.0"; -} - -void GraphicsHelperES2::setSeamlessCubemap(bool enable) -{ - Q_UNUSED(enable); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "GL_TEXTURE_CUBE_MAP_SEAMLESS not supported by OpenGL ES 2.0"; -} - -QSize GraphicsHelperES2::getRenderBufferDimensions(GLuint renderBufferId) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); - - return QSize(width, height); -} - -QSize GraphicsHelperES2::getTextureDimensions(GLuint textureId, GLenum target, uint level) -{ - Q_UNUSED(textureId); - Q_UNUSED(target); - Q_UNUSED(level); - qCritical() << "getTextureDimensions is not supported by ES 2.0"; - return QSize(0, 0); -} - -void GraphicsHelperES2::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) -{ - Q_UNUSED(wx); - Q_UNUSED(wy); - Q_UNUSED(wz); - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "Compute Shaders are not supported by ES 2.0 (since ES 3.1)"; -} - -char *GraphicsHelperES2::mapBuffer(GLenum target, GLsizeiptr size) -{ - Q_UNUSED(target); - Q_UNUSED(size); - static bool showWarning = true; - if (!showWarning) - return nullptr; - showWarning = false; - qWarning() << "Map buffer is not a core requirement for ES 2.0"; - return nullptr; -} - -GLboolean GraphicsHelperES2::unmapBuffer(GLenum target) -{ - Q_UNUSED(target); - static bool showWarning = true; - if (!showWarning) - return false; - showWarning = false; - qWarning() << "unMap buffer is not a core requirement for ES 2.0"; - return false; -} - -void GraphicsHelperES2::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform1fv(location, count, values); -} - -void GraphicsHelperES2::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform2fv(location, count, values); -} - -void GraphicsHelperES2::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform3fv(location, count, values); -} - -void GraphicsHelperES2::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform4fv(location, count, values); -} - -void GraphicsHelperES2::glUniform1iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform1iv(location, count, values); -} - -void GraphicsHelperES2::glUniform2iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform2iv(location, count, values); -} - -void GraphicsHelperES2::glUniform3iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform3iv(location, count, values); -} - -void GraphicsHelperES2::glUniform4iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform4iv(location, count, values); -} - -void GraphicsHelperES2::glUniform1uiv(GLint , GLsizei , const GLuint *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniform1uiv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniform2uiv(GLint , GLsizei , const GLuint *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniform2uiv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniform3uiv(GLint , GLsizei , const GLuint *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniform3uiv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniform4uiv(GLint , GLsizei , const GLuint *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniform4uiv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2fv(location, count, false, values); -} - -void GraphicsHelperES2::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3fv(location, count, false, values); -} - -void GraphicsHelperES2::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4fv(location, count, false, values); -} - -void GraphicsHelperES2::glUniformMatrix2x3fv(GLint , GLsizei , const GLfloat *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniformMatrix2x3fv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniformMatrix3x2fv(GLint , GLsizei , const GLfloat *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniformMatrix3x2fv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniformMatrix2x4fv(GLint , GLsizei , const GLfloat *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniformMatrix2x4fv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniformMatrix4x2fv(GLint , GLsizei , const GLfloat *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniformMatrix4x2fv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniformMatrix3x4fv(GLint , GLsizei , const GLfloat *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniformMatrix3x4fv not supported by ES 2"; -} - -void GraphicsHelperES2::glUniformMatrix4x3fv(GLint , GLsizei , const GLfloat *) -{ - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "glUniformMatrix4x3fv not supported by ES 2"; -} - -UniformType GraphicsHelperES2::uniformTypeFromGLType(GLenum type) -{ - switch (type) { - case GL_FLOAT: - return UniformType::Float; - case GL_FLOAT_VEC2: - return UniformType::Vec2; - case GL_FLOAT_VEC3: - return UniformType::Vec3; - case GL_FLOAT_VEC4: - return UniformType::Vec4; - case GL_FLOAT_MAT2: - return UniformType::Mat2; - case GL_FLOAT_MAT3: - return UniformType::Mat3; - case GL_FLOAT_MAT4: - return UniformType::Mat4; - case GL_INT: - return UniformType::Int; - case GL_INT_VEC2: - return UniformType::IVec2; - case GL_INT_VEC3: - return UniformType::IVec3; - case GL_INT_VEC4: - return UniformType::IVec4; - case GL_BOOL: - return UniformType::Bool; - case GL_BOOL_VEC2: - return UniformType::BVec2; - case GL_BOOL_VEC3: - return UniformType::BVec3; - case GL_BOOL_VEC4: - return UniformType::BVec4; - - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - return UniformType::Sampler; - default: - Q_UNREACHABLE(); - return UniformType::Float; - } -} - -void GraphicsHelperES2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) -{ - if (!m_supportFramebufferBlit) { - static bool showWarning = true; - if (!showWarning) - return; - showWarning = false; - qWarning() << "Framebuffer blits are not supported by ES 2.0 (since ES 3.1)"; - } else - m_ext->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes2_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelperes2_p.h deleted file mode 100644 index 882931ad9..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes2_p.h +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES2_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES2_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLExtensions; - -namespace Qt3DRender { -namespace Render { - -class GraphicsHelperES2 : public GraphicsHelperInterface -{ -public: - GraphicsHelperES2(); - virtual ~GraphicsHelperES2(); - - // QGraphicHelperInterface interface - void alphaTest(GLenum mode1, GLenum mode2) override; - void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; - void bindFragDataLocation(GLuint shader, const QHash &outputs) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; - void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; - void blendEquation(GLenum mode) override; - void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; - void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; - void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; - GLuint boundFrameBufferObject() override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; - bool checkFrameBufferComplete() override; - void clearBufferf(GLint drawbuffer, const QVector4D &values) override; - GLuint createFrameBufferObject() override; - void depthMask(GLenum mode) override; - void depthRange(GLdouble nearValue, GLdouble farValue) override; - void depthTest(GLenum mode) override; - void disableClipPlane(int clipPlane) override; - void disablei(GLenum cap, GLuint index) override; - void disablePrimitiveRestart() override; - void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; - char *mapBuffer(GLenum target, GLsizeiptr size) override; - GLboolean unmapBuffer(GLenum target) override; - void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; - void drawArraysIndirect(GLenum mode,void *indirect) override; - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; - void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; - void drawBuffers(GLsizei n, const int *bufs) override; - void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - void enableClipPlane(int clipPlane) override; - void enablei(GLenum cap, GLuint index) override; - void enablePrimitiveRestart(int primitiveRestartIndex) override; - void enableVertexAttributeArray(int location) override; - void frontFace(GLenum mode) override; - QSize getRenderBufferDimensions(GLuint renderBufferId) override; - QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; - void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; - void pointSize(bool programmable, GLfloat value) override; - GLint maxClipPlaneCount() override; - void memoryBarrier(QMemoryBarrier::Operations barriers) override; - QVector programUniformBlocks(GLuint programId) override; - QVector programAttributesAndLocations(GLuint programId) override; - QVector programUniformsAndLocations(GLuint programId) override; - QVector programShaderStorageBlocks(GLuint programId) override; - void releaseFrameBufferObject(GLuint frameBufferId) override; - void setMSAAEnabled(bool enable) override; - void setAlphaCoverageEnabled(bool enable) override; - void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; - void setSeamlessCubemap(bool enable) override; - void setVerticesPerPatch(GLint verticesPerPatch) override; - bool supportsFeature(Feature feature) const override; - uint uniformByteSize(const ShaderUniform &description) override; - void useProgram(GLuint programId) override; - void vertexAttribDivisor(GLuint index, GLuint divisor) override; - void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; - void readBuffer(GLenum mode) override; - void drawBuffer(GLenum mode) override; - void rasterMode(GLenum faceMode, GLenum rasterMode) override; - - void *fenceSync() override; - void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; - void waitSync(void *sync) override; - bool wasSyncSignaled(void *sync) override; - void deleteSync(void *sync) override; - - void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; - - void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; - - void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; - - void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; - - UniformType uniformTypeFromGLType(GLenum glType) override; - -protected: - QOpenGLFunctions *m_funcs; - bool m_supportFramebufferBlit; - QScopedPointer m_ext; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES2_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp deleted file mode 100644 index 5e5d2e001..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp +++ /dev/null @@ -1,768 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 Svenn-Arne Dragly. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelperes3_p.h" -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -// ES 3.0+ -#ifndef GL_SAMPLER_3D -#define GL_SAMPLER_3D 0x8B5F -#endif -#ifndef GL_SAMPLER_2D_SHADOW -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#endif -#ifndef GL_SAMPLER_CUBE_SHADOW -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#endif -#ifndef GL_SAMPLER_2D_ARRAY -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#endif -#ifndef GL_SAMPLER_2D_ARRAY_SHADOW -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#endif -#ifndef GL_FLOAT_MAT2x3 -#define GL_FLOAT_MAT2x3 0x8B65 -#endif -#ifndef GL_FLOAT_MAT2x4 -#define GL_FLOAT_MAT2x4 0x8B66 -#endif -#ifndef GL_FLOAT_MAT3x2 -#define GL_FLOAT_MAT3x2 0x8B67 -#endif -#ifndef GL_FLOAT_MAT3x4 -#define GL_FLOAT_MAT3x4 0x8B68 -#endif -#ifndef GL_FLOAT_MAT4x2 -#define GL_FLOAT_MAT4x2 0x8B69 -#endif -#ifndef GL_FLOAT_MAT4x3 -#define GL_FLOAT_MAT4x3 0x8B6A -#endif -#ifndef GL_UNSIGNED_INT_VEC2 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#endif -#ifndef GL_UNSIGNED_INT_VEC3 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#endif -#ifndef GL_UNSIGNED_INT_VEC4 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 -#endif -#ifndef GL_INT_SAMPLER_2D -#define GL_INT_SAMPLER_2D 0x8DCA -#endif -#ifndef GL_INT_SAMPLER_3D -#define GL_INT_SAMPLER_3D 0x8DCB -#endif -#ifndef GL_INT_SAMPLER_CUBE -#define GL_INT_SAMPLER_CUBE 0x8DCC -#endif -#ifndef GL_INT_SAMPLER_2D_ARRAY -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#endif -#ifndef GL_UNSIGNED_INT_SAMPLER_2D -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#endif -#ifndef GL_UNSIGNED_INT_SAMPLER_3D -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#endif -#ifndef GL_UNSIGNED_INT_SAMPLER_CUBE -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#endif -#ifndef GL_UNSIGNED_INT_SAMPLER_2D_ARRAY -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#endif - -#ifndef GL_ACTIVE_UNIFORM_BLOCKS -#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -#endif -#ifndef GL_UNIFORM_BLOCK_INDEX -#define GL_UNIFORM_BLOCK_INDEX 0x8A3A -#endif -#ifndef GL_UNIFORM_OFFSET -#define GL_UNIFORM_OFFSET 0x8A3B -#endif -#ifndef GL_UNIFORM_ARRAY_STRIDE -#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -#endif -#ifndef GL_UNIFORM_MATRIX_STRIDE -#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -#endif -#ifndef GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -#endif -#ifndef GL_UNIFORM_BLOCK_BINDING -#define GL_UNIFORM_BLOCK_BINDING 0x8A3F -#endif -#ifndef GL_UNIFORM_BLOCK_DATA_SIZE -#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -#endif - -#ifndef GL_DRAW_FRAMEBUFFER -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#endif - -#ifndef GL_READ_FRAMEBUFFER -#define GL_READ_FRAMEBUFFER 0x8CA8 -#endif - -#ifndef GL_SIGNALED -#define GL_SIGNALED 0x9119 -#endif - -#ifndef GL_SYNC_STATUS -#define GL_SYNC_STATUS 0x9114 -#endif - -#ifndef GL_TIMEOUT_IGNORED -#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull -#endif - -#ifndef GL_SYNC_GPU_COMMANDS_COMPLETE -#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 -#endif - -#ifndef GL_SYNC_FLUSH_COMMANDS_BIT -#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 -#endif - -namespace Qt3DRender { -namespace Render { - -GraphicsHelperES3::GraphicsHelperES3() -{ -} - -GraphicsHelperES3::~GraphicsHelperES3() -{ -} - -void GraphicsHelperES3::initializeHelper(QOpenGLContext *context, - QAbstractOpenGLFunctions *functions) -{ - GraphicsHelperES2::initializeHelper(context, functions); - m_extraFuncs = context->extraFunctions(); - Q_ASSERT(m_extraFuncs); -} - -void GraphicsHelperES3::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 3"; - - if (baseVertex != 0) - qWarning() << "glDrawElementsInstancedBaseVertex is not supported with OpenGL ES 3"; - - m_extraFuncs->glDrawElementsInstanced(primitiveType, - primitiveCount, - indexType, - indices, - instances); -} - -void GraphicsHelperES3::vertexAttribDivisor(GLuint index, GLuint divisor) -{ - m_extraFuncs->glVertexAttribDivisor(index, divisor); -} - -void GraphicsHelperES3::vertexAttributePointer(GLenum shaderDataType, - GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const GLvoid *pointer) -{ - switch (shaderDataType) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - case GL_FLOAT_MAT2: - case GL_FLOAT_MAT2x3: - case GL_FLOAT_MAT2x4: - case GL_FLOAT_MAT3: - case GL_FLOAT_MAT3x2: - case GL_FLOAT_MAT3x4: - case GL_FLOAT_MAT4x2: - case GL_FLOAT_MAT4x3: - case GL_FLOAT_MAT4: - m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); - break; - - case GL_INT: - case GL_INT_VEC2: - case GL_INT_VEC3: - case GL_INT_VEC4: - case GL_UNSIGNED_INT: - case GL_UNSIGNED_INT_VEC2: - case GL_UNSIGNED_INT_VEC3: - case GL_UNSIGNED_INT_VEC4: - m_extraFuncs->glVertexAttribIPointer(index, size, type, stride, pointer); - break; - - default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; - Q_UNREACHABLE(); - } -} - -void GraphicsHelperES3::drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) -{ - m_extraFuncs->glDrawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsHelperES3::readBuffer(GLenum mode) -{ - m_extraFuncs->glReadBuffer(mode); -} - -void GraphicsHelperES3::drawBuffer(GLenum mode) -{ - Q_UNUSED(mode); - qWarning() << "glDrawBuffer is not supported with OpenGL ES 3"; -} - -void GraphicsHelperES3::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - GLenum attr = GL_COLOR_ATTACHMENT0; - - if (attachment.m_point <= QRenderTargetOutput::Color15) - attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - else - qCritical() << "Unsupported FBO attachment OpenGL ES 3.0"; - - const QOpenGLTexture::Target target = texture->target(); - - if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face == QAbstractTexture::AllFaces) { - qWarning() << "OpenGL ES 3.0 doesn't handle attaching all the faces of a cube map texture at once to an FBO"; - return; - } - - texture->bind(); - if (target == QOpenGLTexture::Target2D) - m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); - else if (target == QOpenGLTexture::TargetCubeMap) - m_funcs->glFramebufferTexture2D(GL_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else - qCritical() << "Unsupported Texture FBO attachment format"; - texture->release(); -} - -void GraphicsHelperES3::bindFrameBufferObject(GLuint frameBufferId, GraphicsHelperInterface::FBOBindMode mode) -{ - switch (mode) { - case FBODraw: - m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); - return; - case FBORead: - m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); - return; - case FBOReadAndDraw: - default: - m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); - return; - } -} - -bool GraphicsHelperES3::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case RenderBufferDimensionRetrieval: - case MRT: - case BlitFramebuffer: - case UniformBufferObject: - case MapBuffer: - case Fences: - return true; - default: - return false; - } -} - -void GraphicsHelperES3::drawBuffers(GLsizei n, const int *bufs) -{ - QVarLengthArray drawBufs(n); - - for (int i = 0; i < n; i++) - drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; - m_extraFuncs->glDrawBuffers(n, drawBufs.constData()); -} - -UniformType GraphicsHelperES3::uniformTypeFromGLType(GLenum glType) -{ - switch (glType) { - case GL_SAMPLER_3D: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_2D_ARRAY: - case GL_SAMPLER_2D_ARRAY_SHADOW: - return UniformType::Sampler; - default: - return GraphicsHelperES2::uniformTypeFromGLType(glType); - } -} - -uint GraphicsHelperES3::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - int arrayStride = qMax(description.m_arrayStride, 0); - int matrixStride = qMax(description.m_matrixStride, 0); - - switch (description.m_type) { - - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - case GL_UNSIGNED_INT_VEC2: - rawByteSize = 8; - break; - - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - case GL_UNSIGNED_INT_VEC3: - rawByteSize = 12; - break; - - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - case GL_UNSIGNED_INT_VEC4: - rawByteSize = 16; - break; - - case GL_FLOAT_MAT2: - rawByteSize = matrixStride ? 2 * matrixStride : 16; - break; - - case GL_FLOAT_MAT2x4: - rawByteSize = matrixStride ? 2 * matrixStride : 32; - break; - - case GL_FLOAT_MAT4x2: - rawByteSize = matrixStride ? 4 * matrixStride : 32; - break; - - case GL_FLOAT_MAT3: - rawByteSize = matrixStride ? 3 * matrixStride : 36; - break; - - case GL_FLOAT_MAT2x3: - rawByteSize = matrixStride ? 2 * matrixStride : 24; - break; - - case GL_FLOAT_MAT3x2: - rawByteSize = matrixStride ? 3 * matrixStride : 24; - break; - - case GL_FLOAT_MAT4: - rawByteSize = matrixStride ? 4 * matrixStride : 64; - break; - - case GL_FLOAT_MAT4x3: - rawByteSize = matrixStride ? 4 * matrixStride : 48; - break; - - case GL_FLOAT_MAT3x4: - rawByteSize = matrixStride ? 3 * matrixStride : 48; - break; - - case GL_BOOL: - rawByteSize = 1; - break; - - case GL_BOOL_VEC2: - rawByteSize = 2; - break; - - case GL_BOOL_VEC3: - rawByteSize = 3; - break; - - case GL_BOOL_VEC4: - rawByteSize = 4; - break; - - case GL_INT: - case GL_FLOAT: - case GL_UNSIGNED_INT: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_2D_ARRAY_SHADOW: - rawByteSize = 4; - break; - } - - return arrayStride ? rawByteSize * arrayStride : rawByteSize; -} - -void *GraphicsHelperES3::fenceSync() -{ - return m_extraFuncs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); -} - -void GraphicsHelperES3::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) -{ - m_extraFuncs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); -} - -void GraphicsHelperES3::waitSync(void *sync) -{ - m_extraFuncs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); -} - -bool GraphicsHelperES3::wasSyncSignaled(void *sync) -{ - GLint v; - m_extraFuncs->glGetSynciv(static_cast(sync), - GL_SYNC_STATUS, - sizeof(v), - nullptr, - &v); - return v == GL_SIGNALED; -} - -void GraphicsHelperES3::deleteSync(void *sync) -{ - m_extraFuncs->glDeleteSync(static_cast(sync)); -} - -void GraphicsHelperES3::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) -{ - m_extraFuncs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); -} - -void GraphicsHelperES3::bindBufferBase(GLenum target, GLuint index, GLuint buffer) -{ - m_extraFuncs->glBindBufferBase(target, index, buffer); -} - -bool GraphicsHelperES3::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - // Use a renderbuffer for combined depth+stencil attachments since this is - // problematic before GLES 3.2. Keep using textures for everything else. - return attachment.m_point == QRenderTargetOutput::DepthStencil; -} - -void GraphicsHelperES3::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - m_extraFuncs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); -} - -void GraphicsHelperES3::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - char *bufferData = buffer.data(); - - switch (description.m_type) { - - case GL_FLOAT: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_FLOAT_VEC2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_FLOAT_VEC3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_FLOAT_VEC4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_FLOAT_MAT2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); - break; - } - - case GL_FLOAT_MAT2x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); - break; - } - - case GL_FLOAT_MAT2x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); - break; - } - - case GL_FLOAT_MAT3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); - break; - } - - case GL_FLOAT_MAT3x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); - break; - } - - case GL_FLOAT_MAT3x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); - break; - } - - case GL_FLOAT_MAT4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); - break; - } - - case GL_FLOAT_MAT4x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); - break; - } - - case GL_FLOAT_MAT4x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); - break; - } - - case GL_INT: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_INT_VEC2: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_INT_VEC3: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_INT_VEC4: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_UNSIGNED_INT: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_UNSIGNED_INT_VEC2: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_UNSIGNED_INT_VEC3: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_UNSIGNED_INT_VEC4: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_BOOL: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_BOOL_VEC2: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_BOOL_VEC3: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_BOOL_VEC4: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - // note: only GLES 3.0 supported types, not the same as OpenGL proper - // (also, no MS samplers before ES 3.1) - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_2D_ARRAY_SHADOW: - { - Q_ASSERT(description.m_size == 1); - int value = v.toInt(); - QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); - break; - } - - default: - qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; - break; - } -} - -char *GraphicsHelperES3::mapBuffer(GLenum target, GLsizeiptr size) -{ - return static_cast(m_extraFuncs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); -} - -GLboolean GraphicsHelperES3::unmapBuffer(GLenum target) -{ - return m_extraFuncs->glUnmapBuffer(target); -} - -QVector GraphicsHelperES3::programUniformsAndLocations(GLuint programId) -{ - QVector uniforms; - - GLint nbrActiveUniforms = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); - uniforms.reserve(nbrActiveUniforms); - char uniformName[256]; - for (GLint i = 0; i < nbrActiveUniforms; i++) { - ShaderUniform uniform; - GLsizei uniformNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, - &uniform.m_size, &uniform.m_type, uniformName); - uniformName[sizeof(uniformName) - 1] = '\0'; - uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); - uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); - m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); - m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); - m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); - m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); - uniform.m_rawByteSize = uniformByteSize(uniform); - uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; - } - - return uniforms; -} - -QVector GraphicsHelperES3::programUniformBlocks(GLuint programId) -{ - QVector blocks; - GLint nbrActiveUniformsBlocks = 0; - m_extraFuncs->glGetProgramiv(programId, GL_ACTIVE_UNIFORM_BLOCKS, &nbrActiveUniformsBlocks); - blocks.reserve(nbrActiveUniformsBlocks); - for (GLint i = 0; i < nbrActiveUniformsBlocks; i++) { - QByteArray uniformBlockName(256, '\0'); - GLsizei length = 0; - ShaderUniformBlock uniformBlock; - m_extraFuncs->glGetActiveUniformBlockName(programId, i, 256, &length, uniformBlockName.data()); - uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); - uniformBlock.m_index = i; - m_extraFuncs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &uniformBlock.m_activeUniformsCount); - m_extraFuncs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_BINDING, &uniformBlock.m_binding); - m_extraFuncs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.m_size); - blocks.append(uniformBlock); - } - return blocks; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp deleted file mode 100644 index 9c424d962..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2018 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelperes3_1_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -// ES 3.1+ -#ifndef GL_SAMPLER_2D_MULTISAMPLE -#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 -#endif -#ifndef GL_INT_SAMPLER_2D_MULTISAMPLE -#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 -#endif -#ifndef GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A -#endif -#ifndef GL_ACTIVE_RESOURCES -#define GL_ACTIVE_RESOURCES 0x92F5 -#endif -#ifndef GL_BUFFER_BINDING -#define GL_BUFFER_BINDING 0x9302 -#endif -#ifndef GL_BUFFER_DATA_SIZE -#define GL_BUFFER_DATA_SIZE 0x9303 -#endif -#ifndef GL_NUM_ACTIVE_VARIABLES -#define GL_NUM_ACTIVE_VARIABLES 0x9304 -#endif -#ifndef GL_SHADER_STORAGE_BLOCK -#define GL_SHADER_STORAGE_BLOCK 0x92E6 -#endif -#ifndef GL_ALL_BARRIER_BITS -#define GL_ALL_BARRIER_BITS 0xFFFFFFFF -#endif -#ifndef GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT -#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 -#endif -#ifndef GL_ELEMENT_ARRAY_BARRIER_BIT -#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 -#endif -#ifndef GL_UNIFORM_BARRIER_BIT -#define GL_UNIFORM_BARRIER_BIT 0x00000004 -#endif -#ifndef GL_TEXTURE_FETCH_BARRIER_BIT -#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 -#endif -#ifndef GL_SHADER_IMAGE_ACCESS_BARRIER_BIT -#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 -#endif -#ifndef GL_COMMAND_BARRIER_BIT -#define GL_COMMAND_BARRIER_BIT 0x00000040 -#endif -#ifndef GL_PIXEL_BUFFER_BARRIER_BIT -#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 -#endif -#ifndef GL_TEXTURE_UPDATE_BARRIER_BIT -#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 -#endif -#ifndef GL_BUFFER_UPDATE_BARRIER_BIT -#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 -#endif -#ifndef GL_FRAMEBUFFER_BARRIER_BIT -#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 -#endif -#ifndef GL_TRANSFORM_FEEDBACK_BARRIER_BIT -#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 -#endif -#ifndef GL_ATOMIC_COUNTER_BARRIER_BIT -#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 -#endif -#ifndef GL_SHADER_STORAGE_BARRIER_BIT -#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 -#endif -#ifndef GL_IMAGE_2D -#define GL_IMAGE_2D 0x904D -#endif -#ifndef GL_IMAGE_3D -#define GL_IMAGE_3D 0x904E -#endif -#ifndef GL_IMAGE_CUBE -#define GL_IMAGE_CUBE 0x9050 -#endif -#ifndef GL_IMAGE_2D_ARRAY -#define GL_IMAGE_2D_ARRAY 0x9053 -#endif -#ifndef GL_INT_IMAGE_2D -#define GL_INT_IMAGE_2D 0x9058 -#endif -#ifndef GL_INT_IMAGE_3D -#define GL_INT_IMAGE_3D 0x9059 -#endif -#ifndef GL_INT_IMAGE_CUBE -#define GL_INT_IMAGE_CUBE 0x905B -#endif -#ifndef GL_INT_IMAGE_2D_ARRAY -#define GL_INT_IMAGE_2D_ARRAY 0x905E -#endif -#ifndef GL_UNSIGNED_INT_IMAGE_2D -#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 -#endif -#ifndef GL_UNSIGNED_INT_IMAGE_3D -#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 -#endif -#ifndef GL_UNSIGNED_INT_IMAGE_CUBE -#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 -#endif -#ifndef GL_UNSIGNED_INT_IMAGE_2D_ARRAY -#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 -#endif - - -namespace Qt3DRender { -namespace Render { - -namespace { - -GLbitfield memoryBarrierGLBitfield(QMemoryBarrier::Operations barriers) -{ - GLbitfield bits = 0; - - if (barriers.testFlag(QMemoryBarrier::All)) { - bits |= GL_ALL_BARRIER_BITS; - return bits; - } - - if (barriers.testFlag(QMemoryBarrier::VertexAttributeArray)) - bits |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::ElementArray)) - bits |= GL_ELEMENT_ARRAY_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::Uniform)) - bits |= GL_UNIFORM_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::TextureFetch)) - bits |= GL_TEXTURE_FETCH_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::ShaderImageAccess)) - bits |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::Command)) - bits |= GL_COMMAND_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::PixelBuffer)) - bits |= GL_PIXEL_BUFFER_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::TextureUpdate)) - bits |= GL_TEXTURE_UPDATE_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::BufferUpdate)) - bits |= GL_BUFFER_UPDATE_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::FrameBuffer)) - bits |= GL_FRAMEBUFFER_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::TransformFeedback)) - bits |= GL_TRANSFORM_FEEDBACK_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::AtomicCounter)) - bits |= GL_ATOMIC_COUNTER_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::ShaderStorage)) - bits |= GL_SHADER_STORAGE_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::QueryBuffer)) - qWarning() << "QueryBuffer barrier not supported by ES 3.1"; - - return bits; -} - -} // anonymous - - -GraphicsHelperES3_1::GraphicsHelperES3_1() -{ -} - -GraphicsHelperES3_1::~GraphicsHelperES3_1() -{ -} - -bool GraphicsHelperES3_1::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case GraphicsHelperInterface::Compute: - case GraphicsHelperInterface::ShaderStorageObject: - case GraphicsHelperInterface::IndirectDrawing: - case GraphicsHelperInterface::ShaderImage: - return true; - default: - break; - } - return GraphicsHelperES3::supportsFeature(feature); -} - -void GraphicsHelperES3_1::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - m_extraFuncs->glBindImageTexture(imageUnit, - texture, - mipLevel, - layered, - layer, - access, - format); -} - -void GraphicsHelperES3_1::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) -{ - m_extraFuncs->glDispatchCompute(wx, wy, wz); -} - -void GraphicsHelperES3_1::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - m_extraFuncs->glMemoryBarrier(memoryBarrierGLBitfield(barriers)); -} - -void GraphicsHelperES3_1::drawArraysIndirect(GLenum mode, void *indirect) -{ - m_extraFuncs->glDrawArraysIndirect(mode, indirect); -} - -void GraphicsHelperES3_1::drawElementsIndirect(GLenum mode, GLenum type, void *indirect) -{ - m_extraFuncs->glDrawElementsIndirect(mode, type, indirect); -} - -void GraphicsHelperES3_1::bindShaderStorageBlock(GLuint , GLuint , GLuint ) -{ - // ES 3.1 has no API for that, bindings have to be specified directly in the shader - // with layout(std430, binding = 3) - qWarning() << "ES 3.1 has no bindShaderStorageBlock API, it uses binding declaration from the shader storage block"; -} - -QVector GraphicsHelperES3_1::programShaderStorageBlocks(GLuint programId) -{ - QVector blocks; - GLint nbrActiveShaderStorageBlocks = 0; - m_extraFuncs->glGetProgramInterfaceiv(programId, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &nbrActiveShaderStorageBlocks); - blocks.reserve(nbrActiveShaderStorageBlocks); - for (GLint i = 0; i < nbrActiveShaderStorageBlocks; ++i) { - QByteArray storageBlockName(256, '\0'); - GLsizei length = 0; - ShaderStorageBlock storageBlock; - m_extraFuncs->glGetProgramResourceName(programId, GL_SHADER_STORAGE_BLOCK, i, 256, &length, storageBlockName.data()); - storageBlock.m_index = i; - storageBlock.m_name = QString::fromUtf8(storageBlockName.left(length)); - GLenum prop = GL_BUFFER_BINDING; - m_extraFuncs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_binding); - prop = GL_BUFFER_DATA_SIZE; - m_extraFuncs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_size); - prop = GL_NUM_ACTIVE_VARIABLES; - m_extraFuncs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_activeVariablesCount); - blocks.push_back(storageBlock); - } - return blocks; -} - -UniformType GraphicsHelperES3_1::uniformTypeFromGLType(GLenum glType) -{ - switch (glType) { - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - return UniformType::Sampler; - case GL_IMAGE_2D: - case GL_IMAGE_3D: - case GL_IMAGE_CUBE: - case GL_IMAGE_2D_ARRAY: - case GL_INT_IMAGE_2D: - case GL_INT_IMAGE_3D: - case GL_INT_IMAGE_CUBE: - case GL_INT_IMAGE_2D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D: - case GL_UNSIGNED_INT_IMAGE_3D: - case GL_UNSIGNED_INT_IMAGE_CUBE: - case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: - return UniformType::Image; - - default: - return GraphicsHelperES3::uniformTypeFromGLType(glType); - } -} - -uint GraphicsHelperES3_1::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - - switch (description.m_type) { - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_IMAGE_2D: - case GL_IMAGE_3D: - case GL_IMAGE_CUBE: - case GL_IMAGE_2D_ARRAY: - case GL_INT_IMAGE_2D: - case GL_INT_IMAGE_3D: - case GL_INT_IMAGE_CUBE: - case GL_INT_IMAGE_2D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D: - case GL_UNSIGNED_INT_IMAGE_3D: - case GL_UNSIGNED_INT_IMAGE_CUBE: - case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: - rawByteSize = 4; - break; - - default: - rawByteSize = GraphicsHelperES3::uniformByteSize(description); - break; - } - - return rawByteSize; -} - -void GraphicsHelperES3_1::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - char *bufferData = buffer.data(); - - switch (description.m_type) { - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - { - Q_ASSERT(description.m_size == 1); - int value = v.toInt(); - QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); - break; - } - - default: - GraphicsHelperES3::buildUniformBuffer(v, description, buffer); - break; - } -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h deleted file mode 100644 index 43d9ae7dd..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2018 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_1_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_1_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class GraphicsHelperES3_1 : public GraphicsHelperES3 -{ -public: - GraphicsHelperES3_1(); - ~GraphicsHelperES3_1(); - - bool supportsFeature(Feature feature) const override; - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; - void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; - void memoryBarrier(QMemoryBarrier::Operations barriers) override; - void drawArraysIndirect(GLenum mode,void *indirect) override; - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; - QVector programShaderStorageBlocks(GLuint programId) override; - - // QGraphicHelperInterface interface - UniformType uniformTypeFromGLType(GLenum glType) override; - uint uniformByteSize(const ShaderUniform &description) override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_1_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp deleted file mode 100644 index 9d0988410..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelperes3_2_p.h" -#include -#include -#include - -QT_BEGIN_NAMESPACE - -#ifndef GL_DRAW_FRAMEBUFFER -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#endif - -#ifndef GL_DEPTH_STENCIL_ATTACHMENT -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#endif - -#ifndef GL_PATCH_VERTICES -#define GL_PATCH_VERTICES 36466 -#endif - -#ifndef GL_IMAGE_BUFFER -#define GL_IMAGE_BUFFER 0x9051 -#endif -#ifndef GL_IMAGE_CUBE_MAP_ARRAY -#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 -#endif -#ifndef GL_INT_IMAGE_BUFFER -#define GL_INT_IMAGE_BUFFER 0x905C -#endif -#ifndef GL_INT_IMAGE_CUBE_MAP_ARRAY -#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F -#endif -#ifndef GL_UNSIGNED_INT_IMAGE_BUFFER -#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 -#endif -#ifndef GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY -#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A -#endif - -namespace Qt3DRender { -namespace Render { - -GraphicsHelperES3_2::GraphicsHelperES3_2() -{ -} - -GraphicsHelperES3_2::~GraphicsHelperES3_2() -{ -} - -bool GraphicsHelperES3_2::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case GraphicsHelperInterface::Tessellation: - return true; - default: - break; - } - return GraphicsHelperES3_1::supportsFeature(feature); -} - -bool GraphicsHelperES3_2::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - Q_UNUSED(attachment); - // This is first ES version where we have glFramebufferTexture, so - // attaching a D24S8 texture to the combined depth-stencil attachment point - // should work. - return false; -} - -void GraphicsHelperES3_2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - GLenum attr = GL_COLOR_ATTACHMENT0; - - if (attachment.m_point <= QRenderTargetOutput::Color15) - attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::DepthStencil) - attr = GL_DEPTH_STENCIL_ATTACHMENT; - else - qCritical() << "Unsupported FBO attachment OpenGL ES 3.2"; - - const QOpenGLTexture::Target target = texture->target(); - - texture->bind(); - if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face != QAbstractTexture::AllFaces) - m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else - m_extraFuncs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); - texture->release(); -} - -void GraphicsHelperES3_2::setVerticesPerPatch(GLint verticesPerPatch) -{ - m_extraFuncs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); -} - -void GraphicsHelperES3_2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex, GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; - - m_extraFuncs->glDrawElementsInstancedBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - instances, - baseVertex); -} - -UniformType GraphicsHelperES3_2::uniformTypeFromGLType(GLenum glType) -{ - switch (glType) { - case GL_IMAGE_BUFFER: - case GL_IMAGE_CUBE_MAP_ARRAY: - case GL_INT_IMAGE_BUFFER: - case GL_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_UNSIGNED_INT_IMAGE_BUFFER: - case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: - return UniformType::Image; - - default: - return GraphicsHelperES3_1::uniformTypeFromGLType(glType); - } -} - -uint GraphicsHelperES3_2::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - - switch (description.m_type) { - case GL_IMAGE_BUFFER: - case GL_IMAGE_CUBE_MAP_ARRAY: - case GL_INT_IMAGE_BUFFER: - case GL_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_UNSIGNED_INT_IMAGE_BUFFER: - case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: - rawByteSize = 4; - break; - - default: - rawByteSize = GraphicsHelperES3_1::uniformByteSize(description); - break; - } - - return rawByteSize; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h deleted file mode 100644 index 6b1a893d4..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h +++ /dev/null @@ -1,84 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class GraphicsHelperES3_2 : public GraphicsHelperES3_1 -{ -public: - GraphicsHelperES3_2(); - ~GraphicsHelperES3_2(); - - bool supportsFeature(Feature feature) const override; - - // QGraphicHelperInterface interface - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void setVerticesPerPatch(GLint verticesPerPatch) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - UniformType uniformTypeFromGLType(GLenum glType) override; - uint uniformByteSize(const ShaderUniform &description) override; - -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_p.h deleted file mode 100644 index dc5cef10c..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_p.h +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 Svenn-Arne Dragly. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class GraphicsHelperES3 : public GraphicsHelperES2 -{ -public: - GraphicsHelperES3(); - ~GraphicsHelperES3(); - - // QGraphicHelperInterface interface - void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; - void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; - void drawBuffers(GLsizei n, const int *bufs) override; - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - void readBuffer(GLenum mode) override; - void drawBuffer(GLenum mode) override; - void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; - char *mapBuffer(GLenum target, GLsizeiptr size) override; - QVector programUniformsAndLocations(GLuint programId) override; - QVector programUniformBlocks(GLuint programId) override; - bool supportsFeature(Feature feature) const override; - GLboolean unmapBuffer(GLenum target) override; - void vertexAttribDivisor(GLuint index, GLuint divisor) override; - void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; - - UniformType uniformTypeFromGLType(GLenum glType) override; - uint uniformByteSize(const ShaderUniform &description) override; - - void *fenceSync() override; - void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; - void waitSync(void *sync) override; - bool wasSyncSignaled(void *sync) override; - void deleteSync(void *sync) override; - -protected: - QOpenGLExtraFunctions *m_extraFuncs = nullptr; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp deleted file mode 100644 index b9ee16acb..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp +++ /dev/null @@ -1,935 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelpergl2_p.h" -#ifndef QT_OPENGL_ES_2 -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -GraphicsHelperGL2::GraphicsHelperGL2() - : m_funcs(nullptr) - , m_fboFuncs(nullptr) -{ - -} - -void GraphicsHelperGL2::initializeHelper(QOpenGLContext *context, - QAbstractOpenGLFunctions *functions) -{ - Q_UNUSED(context); - m_funcs = static_cast(functions); - const bool ok = m_funcs->initializeOpenGLFunctions(); - Q_ASSERT(ok); - Q_UNUSED(ok); - if (context->hasExtension(QByteArrayLiteral("GL_ARB_framebuffer_object"))) { - m_fboFuncs = new QOpenGLExtension_ARB_framebuffer_object(); - const bool extensionOk = m_fboFuncs->initializeOpenGLFunctions(); - Q_ASSERT(extensionOk); - Q_UNUSED(extensionOk); - } -} - -void GraphicsHelperGL2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; - - if (baseVertex != 0) - qWarning() << "glDrawElementsInstancedBaseVertex is not supported with OpenGL ES 2"; - - for (GLint i = 0; i < instances; i++) - drawElements(primitiveType, - primitiveCount, - indexType, - indices); -} - -void GraphicsHelperGL2::drawArraysInstanced(GLenum primitiveType, - GLint first, - GLsizei count, - GLsizei instances) -{ - for (GLint i = 0; i < instances; i++) - drawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperGL2::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL 2"; - for (GLint i = 0; i < instances; i++) - drawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperGL2::drawElements(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLint baseVertex) -{ - if (baseVertex != 0) - qWarning() << "glDrawElementsBaseVertex is not supported with OpenGL 2"; - - m_funcs->glDrawElements(primitiveType, - primitiveCount, - indexType, - indices); -} - -void GraphicsHelperGL2::drawArrays(GLenum primitiveType, - GLint first, - GLsizei count) -{ - m_funcs->glDrawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperGL2::drawElementsIndirect(GLenum, GLenum, void *) -{ - qWarning() << "Indirect Drawing is not supported with OpenGL 2"; -} - -void GraphicsHelperGL2::drawArraysIndirect(GLenum , void *) -{ - qWarning() << "Indirect Drawing is not supported with OpenGL 2"; -} - -void GraphicsHelperGL2::setVerticesPerPatch(GLint verticesPerPatch) -{ - Q_UNUSED(verticesPerPatch); - qWarning() << "Tessellation not supported with OpenGL 2"; -} - -void GraphicsHelperGL2::useProgram(GLuint programId) -{ - m_funcs->glUseProgram(programId); -} - -QVector GraphicsHelperGL2::programUniformsAndLocations(GLuint programId) -{ - QVector uniforms; - - GLint nbrActiveUniforms = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); - uniforms.reserve(nbrActiveUniforms); - char uniformName[256]; - for (GLint i = 0; i < nbrActiveUniforms; i++) { - ShaderUniform uniform; - GLsizei uniformNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, - &uniform.m_size, &uniform.m_type, uniformName); - uniformName[sizeof(uniformName) - 1] = '\0'; - uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); - uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); - // Work around for uniform array names that aren't returned with [0] by some drivers - if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) - uniform.m_name.append(QLatin1String("[0]")); - uniform.m_rawByteSize = uniformByteSize(uniform); - uniforms.append(uniform); - } - return uniforms; -} - -QVector GraphicsHelperGL2::programAttributesAndLocations(GLuint programId) -{ - QVector attributes; - GLint nbrActiveAttributes = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); - attributes.reserve(nbrActiveAttributes); - char attributeName[256]; - for (GLint i = 0; i < nbrActiveAttributes; i++) { - ShaderAttribute attribute; - GLsizei attributeNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, - &attribute.m_size, &attribute.m_type, attributeName); - attributeName[sizeof(attributeName) - 1] = '\0'; - attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); - attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); - attributes.append(attribute); - } - return attributes; -} - -QVector GraphicsHelperGL2::programUniformBlocks(GLuint programId) -{ - Q_UNUSED(programId); - QVector blocks; - qWarning() << "UBO are not supported by OpenGL 2.0 (since OpenGL 3.1)"; - return blocks; -} - -QVector GraphicsHelperGL2::programShaderStorageBlocks(GLuint programId) -{ - Q_UNUSED(programId); - qWarning() << "SSBO are not supported by OpenGL 2.0 (since OpenGL 4.3)"; - return QVector(); -} - -void GraphicsHelperGL2::vertexAttribDivisor(GLuint index, - GLuint divisor) -{ - Q_UNUSED(index); - Q_UNUSED(divisor); -} - -void GraphicsHelperGL2::vertexAttributePointer(GLenum shaderDataType, - GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const GLvoid *pointer) -{ - switch (shaderDataType) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - case GL_FLOAT_MAT2: - case GL_FLOAT_MAT2x3: - case GL_FLOAT_MAT2x4: - case GL_FLOAT_MAT3: - case GL_FLOAT_MAT3x2: - case GL_FLOAT_MAT3x4: - case GL_FLOAT_MAT4x2: - case GL_FLOAT_MAT4x3: - case GL_FLOAT_MAT4: - m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); - break; - - default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; - Q_UNREACHABLE(); - } -} - -void GraphicsHelperGL2::readBuffer(GLenum mode) -{ - m_funcs->glReadBuffer(mode); -} - -void GraphicsHelperGL2::drawBuffer(GLenum mode) -{ - m_funcs->glDrawBuffer(mode); -} - -void *GraphicsHelperGL2::fenceSync() -{ - qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; - return nullptr; -} - -void GraphicsHelperGL2::clientWaitSync(void *, GLuint64 ) -{ - qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; -} - -void GraphicsHelperGL2::waitSync(void *) -{ - qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; -} - -bool GraphicsHelperGL2::wasSyncSignaled(void *) -{ - qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; - return false; -} - -void GraphicsHelperGL2::deleteSync(void *) -{ - qWarning() << "Fences are not supported by OpenGL 2.0 (since OpenGL 3.2)"; -} - -void GraphicsHelperGL2::rasterMode(GLenum faceMode, GLenum rasterMode) -{ - m_funcs->glPolygonMode(faceMode, rasterMode); -} - -void GraphicsHelperGL2::blendEquation(GLenum mode) -{ - m_funcs->glBlendEquation(mode); -} - -void GraphicsHelperGL2::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) -{ - Q_UNUSED(buf); - Q_UNUSED(sfactor); - Q_UNUSED(dfactor); - - qWarning() << "glBlendFunci() not supported by OpenGL 2.0 (since OpenGL 4.0)"; -} - -void GraphicsHelperGL2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) -{ - Q_UNUSED(buf); - Q_UNUSED(sRGB); - Q_UNUSED(dRGB); - Q_UNUSED(sAlpha); - Q_UNUSED(dAlpha); - - qWarning() << "glBlendFuncSeparatei() not supported by OpenGL 2.0 (since OpenGL 4.0)"; -} - -void GraphicsHelperGL2::alphaTest(GLenum mode1, GLenum mode2) -{ - m_funcs->glEnable(GL_ALPHA_TEST); - m_funcs->glAlphaFunc(mode1, mode2); -} - -void GraphicsHelperGL2::depthTest(GLenum mode) -{ - m_funcs->glEnable(GL_DEPTH_TEST); - m_funcs->glDepthFunc(mode); -} - -void GraphicsHelperGL2::depthMask(GLenum mode) -{ - m_funcs->glDepthMask(mode); -} - -void GraphicsHelperGL2::depthRange(GLdouble nearValue, GLdouble farValue) -{ - m_funcs->glDepthRange(nearValue, farValue); -} - -void GraphicsHelperGL2::frontFace(GLenum mode) -{ - m_funcs->glFrontFace(mode); -} - -void GraphicsHelperGL2::setMSAAEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_MULTISAMPLE) - : m_funcs->glDisable(GL_MULTISAMPLE); -} - -void GraphicsHelperGL2::setAlphaCoverageEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) - : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); -} - -GLuint GraphicsHelperGL2::createFrameBufferObject() -{ - if (m_fboFuncs != nullptr) { - GLuint id; - m_fboFuncs->glGenFramebuffers(1, &id); - return id; - } - qWarning() << "FBO not supported by your OpenGL hardware"; - return 0; -} - -void GraphicsHelperGL2::releaseFrameBufferObject(GLuint frameBufferId) -{ - if (m_fboFuncs != nullptr) - m_fboFuncs->glDeleteFramebuffers(1, &frameBufferId); - else - qWarning() << "FBO not supported by your OpenGL hardware"; -} - -bool GraphicsHelperGL2::checkFrameBufferComplete() -{ - if (m_fboFuncs != nullptr) - return (m_fboFuncs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); - return false; -} - -bool GraphicsHelperGL2::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - Q_UNUSED(attachment); - return false; -} - -void GraphicsHelperGL2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - if (m_fboFuncs != nullptr) { - GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; - - if (attachment.m_point <= QRenderTargetOutput::Color15) - attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - else - qCritical() << "DepthStencil Attachment not supported on OpenGL 2.0"; - - const QOpenGLTexture::Target target = texture->target(); - - if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face == QAbstractTexture::AllFaces) { - qWarning() << "OpenGL 2.0 doesn't handle attaching all the faces of a cube map texture at once to an FBO"; - return; - } - - texture->bind(); - if (target == QOpenGLTexture::Target3D) - m_fboFuncs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMap) - m_fboFuncs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else if (target == QOpenGLTexture::Target1D) - m_fboFuncs->glFramebufferTexture1D(GL_DRAW_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); - else if (target == QOpenGLTexture::Target2D || target == QOpenGLTexture::TargetRectangle) - m_fboFuncs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, target, texture->textureId(), attachment.m_mipLevel); - else - qCritical() << "Texture format not supported for Attachment on OpenGL 2.0"; - texture->release(); - } -} - -void GraphicsHelperGL2::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) -{ - Q_UNUSED(renderBuffer); - Q_UNUSED(attachment); - Q_UNREACHABLE(); -} - -bool GraphicsHelperGL2::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case MRT: - return (m_fboFuncs != nullptr); - case TextureDimensionRetrieval: - case MapBuffer: - return true; - default: - return false; - } -} - -void GraphicsHelperGL2::drawBuffers(GLsizei n, const int *bufs) -{ - QVarLengthArray drawBufs(n); - - for (int i = 0; i < n; i++) - drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; - m_funcs->glDrawBuffers(n, drawBufs.constData()); -} - -void GraphicsHelperGL2::bindFragDataLocation(GLuint, const QHash &) -{ - qCritical() << "bindFragDataLocation is not supported by GL 2.0"; -} - -void GraphicsHelperGL2::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) -{ - if (m_fboFuncs != nullptr) { - switch (mode) { - case FBODraw: - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); - return; - case FBORead: - m_fboFuncs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); - return; - case FBOReadAndDraw: - default: - m_fboFuncs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); - return; - } - } else { - qWarning() << "FBO not supported by your OpenGL hardware"; - } -} - -void GraphicsHelperGL2::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - Q_UNUSED(imageUnit) - Q_UNUSED(texture) - Q_UNUSED(mipLevel) - Q_UNUSED(layered) - Q_UNUSED(layer) - Q_UNUSED(access) - Q_UNUSED(format) - qWarning() << "Shader Images are not supported by OpenGL 2.0 (since OpenGL 4.2)"; - -} - -GLuint GraphicsHelperGL2::boundFrameBufferObject() -{ - GLint id = 0; - m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); - return id; -} - -void GraphicsHelperGL2::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - Q_UNUSED(programId); - Q_UNUSED(uniformBlockIndex); - Q_UNUSED(uniformBlockBinding); - qWarning() << "UBO are not supported by OpenGL 2.0 (since OpenGL 3.1)"; -} - -void GraphicsHelperGL2::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) -{ - Q_UNUSED(programId); - Q_UNUSED(shaderStorageBlockIndex); - Q_UNUSED(shaderStorageBlockBinding); - qWarning() << "SSBO are not supported by OpenGL 2.0 (since OpenGL 4.3)"; -} - -void GraphicsHelperGL2::bindBufferBase(GLenum target, GLuint index, GLuint buffer) -{ - Q_UNUSED(target); - Q_UNUSED(index); - Q_UNUSED(buffer); - qWarning() << "bindBufferBase is not supported by OpenGL 2.0 (since OpenGL 3.0)"; -} - -void GraphicsHelperGL2::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - Q_UNUSED(v); - Q_UNUSED(description); - Q_UNUSED(buffer); - qWarning() << "UBO are not supported by OpenGL 2.0 (since OpenGL 3.1)"; -} - -uint GraphicsHelperGL2::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - int arrayStride = qMax(description.m_arrayStride, 0); - int matrixStride = qMax(description.m_matrixStride, 0); - - switch (description.m_type) { - - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - rawByteSize = 8; - break; - - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - rawByteSize = 12; - break; - - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - rawByteSize = 16; - break; - - case GL_FLOAT_MAT2: - rawByteSize = matrixStride ? 2 * matrixStride : 16; - break; - - case GL_FLOAT_MAT2x4: - rawByteSize = matrixStride ? 2 * matrixStride : 32; - break; - - case GL_FLOAT_MAT4x2: - rawByteSize = matrixStride ? 4 * matrixStride : 32; - break; - - case GL_FLOAT_MAT3: - rawByteSize = matrixStride ? 3 * matrixStride : 36; - break; - - case GL_FLOAT_MAT2x3: - rawByteSize = matrixStride ? 2 * matrixStride : 24; - break; - - case GL_FLOAT_MAT3x2: - rawByteSize = matrixStride ? 3 * matrixStride : 24; - break; - - case GL_FLOAT_MAT4: - rawByteSize = matrixStride ? 4 * matrixStride : 64; - break; - - case GL_FLOAT_MAT4x3: - rawByteSize = matrixStride ? 4 * matrixStride : 48; - break; - - case GL_FLOAT_MAT3x4: - rawByteSize = matrixStride ? 3 * matrixStride : 48; - break; - - case GL_BOOL: - rawByteSize = 1; - break; - - case GL_BOOL_VEC2: - rawByteSize = 2; - break; - - case GL_BOOL_VEC3: - rawByteSize = 3; - break; - - case GL_BOOL_VEC4: - rawByteSize = 4; - break; - - case GL_INT: - case GL_FLOAT: - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - rawByteSize = 4; - break; - - default: - Q_UNREACHABLE(); - } - - return arrayStride ? rawByteSize * arrayStride : rawByteSize; -} - -void GraphicsHelperGL2::enableClipPlane(int clipPlane) -{ - m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL2::disableClipPlane(int clipPlane) -{ - m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL2::setClipPlane(int clipPlane, const QVector3D &normal, float distance) -{ - double plane[4]; - plane[0] = normal.x(); - plane[1] = normal.y(); - plane[2] = normal.z(); - plane[3] = distance; - - m_funcs->glClipPlane(GL_CLIP_PLANE0 + clipPlane, plane); -} - -GLint GraphicsHelperGL2::maxClipPlaneCount() -{ - GLint max = 0; - m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); - return max; -} - -void GraphicsHelperGL2::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - Q_UNUSED(barriers); - qWarning() << "memory barrier is not supported by OpenGL 2.0 (since 4.3)"; -} - -void GraphicsHelperGL2::enablePrimitiveRestart(int) -{ -} - -void GraphicsHelperGL2::enableVertexAttributeArray(int location) -{ - m_funcs->glEnableVertexAttribArray(location); -} - -void GraphicsHelperGL2::disablePrimitiveRestart() -{ -} - -void GraphicsHelperGL2::clearBufferf(GLint drawbuffer, const QVector4D &values) -{ - Q_UNUSED(drawbuffer); - Q_UNUSED(values); - qWarning() << "glClearBuffer*() not supported by OpenGL 2.0"; -} - -void GraphicsHelperGL2::pointSize(bool programmable, GLfloat value) -{ - m_funcs->glEnable(GL_POINT_SPRITE); - if (programmable) - m_funcs->glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); - else - m_funcs->glPointSize(value); -} - -void GraphicsHelperGL2::enablei(GLenum cap, GLuint index) -{ - Q_UNUSED(cap); - Q_UNUSED(index); - qWarning() << "glEnablei() not supported by OpenGL 2.0 (since 3.0)"; -} - -void GraphicsHelperGL2::disablei(GLenum cap, GLuint index) -{ - Q_UNUSED(cap); - Q_UNUSED(index); - qWarning() << "glDisablei() not supported by OpenGL 2.0 (since 3.0)"; -} - -void GraphicsHelperGL2::setSeamlessCubemap(bool enable) -{ - Q_UNUSED(enable); - qWarning() << "GL_TEXTURE_CUBE_MAP_SEAMLESS not supported by OpenGL 2.0 (since 3.2)"; -} - -QSize GraphicsHelperGL2::getRenderBufferDimensions(GLuint renderBufferId) -{ - Q_UNUSED(renderBufferId); - qCritical() << "RenderBuffer dimensions retrival not supported on OpenGL 2.0"; - return QSize(0,0); -} - -QSize GraphicsHelperGL2::getTextureDimensions(GLuint textureId, GLenum target, uint level) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindTexture(target, textureId); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); - m_funcs->glBindTexture(target, 0); - - return QSize(width, height); -} - -void GraphicsHelperGL2::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) -{ - Q_UNUSED(wx); - Q_UNUSED(wy); - Q_UNUSED(wz); - qWarning() << "Compute Shaders are not supported by OpenGL 2.0 (since OpenGL 4.3)"; -} - -char *GraphicsHelperGL2::mapBuffer(GLenum target, GLsizeiptr size) -{ - Q_UNUSED(size); - return static_cast(m_funcs->glMapBuffer(target, GL_READ_WRITE)); -} - -GLboolean GraphicsHelperGL2::unmapBuffer(GLenum target) -{ - return m_funcs->glUnmapBuffer(target); -} - -void GraphicsHelperGL2::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform1fv(location, count, values); -} - -void GraphicsHelperGL2::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform2fv(location, count, values); -} - -void GraphicsHelperGL2::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform3fv(location, count, values); -} - -void GraphicsHelperGL2::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform4fv(location, count, values); -} - -void GraphicsHelperGL2::glUniform1iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform1iv(location, count, values); -} - -void GraphicsHelperGL2::glUniform2iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform2iv(location, count, values); -} - -void GraphicsHelperGL2::glUniform3iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform3iv(location, count, values); -} - -void GraphicsHelperGL2::glUniform4iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform4iv(location, count, values); -} - -void GraphicsHelperGL2::glUniform1uiv(GLint , GLsizei , const GLuint *) -{ - qWarning() << "glUniform1uiv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniform2uiv(GLint , GLsizei , const GLuint *) -{ - qWarning() << "glUniform2uiv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniform3uiv(GLint , GLsizei , const GLuint *) -{ - qWarning() << "glUniform3uiv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniform4uiv(GLint , GLsizei , const GLuint *) -{ - qWarning() << "glUniform4uiv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2fv(location, count, false, values); -} - -void GraphicsHelperGL2::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3fv(location, count, false, values); -} - -void GraphicsHelperGL2::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4fv(location, count, false, values); -} - -void GraphicsHelperGL2::glUniformMatrix2x3fv(GLint , GLsizei , const GLfloat *) -{ - qWarning() << "glUniformMatrix2x3fv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniformMatrix3x2fv(GLint , GLsizei , const GLfloat *) -{ - qWarning() << "glUniformMatrix3x2fv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniformMatrix2x4fv(GLint , GLsizei , const GLfloat *) -{ - qWarning() << "glUniformMatrix2x4fv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniformMatrix4x2fv(GLint , GLsizei , const GLfloat *) -{ - qWarning() << "glUniformMatrix4x2fv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniformMatrix3x4fv(GLint , GLsizei , const GLfloat *) -{ - qWarning() << "glUniformMatrix3x4fv not supported by GL 2"; -} - -void GraphicsHelperGL2::glUniformMatrix4x3fv(GLint , GLsizei , const GLfloat *) -{ - qWarning() << "glUniformMatrix4x3fv not supported by GL 2"; -} - -UniformType GraphicsHelperGL2::uniformTypeFromGLType(GLenum type) -{ - switch (type) { - case GL_FLOAT: - return UniformType::Float; - case GL_FLOAT_VEC2: - return UniformType::Vec2; - case GL_FLOAT_VEC3: - return UniformType::Vec3; - case GL_FLOAT_VEC4: - return UniformType::Vec4; - case GL_FLOAT_MAT2: - return UniformType::Mat2; - case GL_FLOAT_MAT3: - return UniformType::Mat3; - case GL_FLOAT_MAT4: - return UniformType::Mat4; - case GL_INT: - return UniformType::Int; - case GL_INT_VEC2: - return UniformType::IVec2; - case GL_INT_VEC3: - return UniformType::IVec3; - case GL_INT_VEC4: - return UniformType::IVec4; - case GL_BOOL: - return UniformType::Bool; - case GL_BOOL_VEC2: - return UniformType::BVec2; - case GL_BOOL_VEC3: - return UniformType::BVec3; - case GL_BOOL_VEC4: - return UniformType::BVec4; - - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_3D: - return UniformType::Sampler; - - default: - Q_UNREACHABLE(); - return UniformType::Float; - } -} - -void GraphicsHelperGL2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) -{ - Q_UNUSED(srcX0); - Q_UNUSED(srcX1); - Q_UNUSED(srcY0); - Q_UNUSED(srcY1); - Q_UNUSED(dstX0); - Q_UNUSED(dstX1); - Q_UNUSED(dstY0); - Q_UNUSED(dstY1); - Q_UNUSED(mask); - Q_UNUSED(filter); - qWarning() << "Framebuffer blits are not supported by ES 2.0 (since ES 3.1)"; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h deleted file mode 100644 index eb85b8537..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h +++ /dev/null @@ -1,183 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -#ifndef QT_OPENGL_ES_2 - -QT_BEGIN_NAMESPACE - -class QOpenGLFunctions_2_0; -class QOpenGLExtension_ARB_framebuffer_object; - -namespace Qt3DRender { -namespace Render { - -class Q_AUTOTEST_EXPORT GraphicsHelperGL2 : public GraphicsHelperInterface -{ -public: - GraphicsHelperGL2(); - - // QGraphicHelperInterface interface - void alphaTest(GLenum mode1, GLenum mode2) override; - void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; - void bindFragDataLocation(GLuint shader, const QHash &outputs) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; - void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; - void blendEquation(GLenum mode) override; - void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; - void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; - void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; - GLuint boundFrameBufferObject() override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; - bool checkFrameBufferComplete() override; - void clearBufferf(GLint drawbuffer, const QVector4D &values) override; - GLuint createFrameBufferObject() override; - void depthMask(GLenum mode) override; - void depthRange(GLdouble nearValue, GLdouble farValue) override; - void depthTest(GLenum mode) override; - void disableClipPlane(int clipPlane) override; - void disablei(GLenum cap, GLuint index) override; - void disablePrimitiveRestart() override; - void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; - char *mapBuffer(GLenum target, GLsizeiptr size) override; - GLboolean unmapBuffer(GLenum target) override; - void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; - void drawArraysIndirect(GLenum mode,void *indirect) override; - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; - void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; - void drawBuffers(GLsizei n, const int *bufs) override; - void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - void enableClipPlane(int clipPlane) override; - void enablei(GLenum cap, GLuint index) override; - void enablePrimitiveRestart(int primitiveRestartIndex) override; - void enableVertexAttributeArray(int location) override; - void frontFace(GLenum mode) override; - QSize getRenderBufferDimensions(GLuint renderBufferId) override; - QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; - void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; - void pointSize(bool programmable, GLfloat value) override; - GLint maxClipPlaneCount() override; - void memoryBarrier(QMemoryBarrier::Operations barriers) override; - QVector programUniformBlocks(GLuint programId) override; - QVector programAttributesAndLocations(GLuint programId) override; - QVector programUniformsAndLocations(GLuint programId) override; - QVector programShaderStorageBlocks(GLuint programId) override; - void releaseFrameBufferObject(GLuint frameBufferId) override; - void setMSAAEnabled(bool enable) override; - void setAlphaCoverageEnabled(bool enable) override; - void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; - void setSeamlessCubemap(bool enable) override; - void setVerticesPerPatch(GLint verticesPerPatch) override; - bool supportsFeature(Feature feature) const override; - uint uniformByteSize(const ShaderUniform &description) override; - void useProgram(GLuint programId) override; - void vertexAttribDivisor(GLuint index, GLuint divisor) override; - void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; - void readBuffer(GLenum mode) override; - void drawBuffer(GLenum mode) override; - void rasterMode(GLenum faceMode, GLenum rasterMode) override; - - void *fenceSync() override; - void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; - void waitSync(void *sync) override; - bool wasSyncSignaled(void *sync) override; - void deleteSync(void *sync) override; - - void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; - - void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; - - void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; - - void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; - - UniformType uniformTypeFromGLType(GLenum glType) override; - -private: - QOpenGLFunctions_2_0 *m_funcs; - QOpenGLExtension_ARB_framebuffer_object *m_fboFuncs; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp deleted file mode 100644 index f20491358..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp +++ /dev/null @@ -1,1245 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelpergl3_2_p.h" - -#ifndef QT_OPENGL_ES_2 -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -# ifndef QT_OPENGL_3 -# define GL_PATCH_VERTICES 36466 -# define GL_ACTIVE_RESOURCES 0x92F5 -# define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -# define GL_BUFFER_BINDING 0x9302 -# define GL_BUFFER_DATA_SIZE 0x9303 -# define GL_NUM_ACTIVE_VARIABLES 0x9304 -# define GL_SHADER_STORAGE_BLOCK 0x92E6 -# define GL_UNIFORM 0x92E1 -# define GL_UNIFORM_BLOCK 0x92E2 -# define GL_UNIFORM_BLOCK_INDEX 0x8A3A -# define GL_UNIFORM_OFFSET 0x8A3B -# define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -# define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -# define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -# define GL_UNIFORM_BLOCK_BINDING 0x8A3F -# define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -# endif - -namespace Qt3DRender { -namespace Render { - -GraphicsHelperGL3_2::GraphicsHelperGL3_2() - : m_funcs(nullptr) - , m_tessFuncs() -{ -} - -GraphicsHelperGL3_2::~GraphicsHelperGL3_2() -{ -} - -void GraphicsHelperGL3_2::initializeHelper(QOpenGLContext *context, - QAbstractOpenGLFunctions *functions) -{ - m_funcs = static_cast(functions); - const bool ok = m_funcs->initializeOpenGLFunctions(); - Q_ASSERT(ok); - Q_UNUSED(ok); - - if (context->hasExtension(QByteArrayLiteral("GL_ARB_tessellation_shader"))) { - m_tessFuncs.reset(new QOpenGLExtension_ARB_tessellation_shader); - m_tessFuncs->initializeOpenGLFunctions(); - } -} - -void GraphicsHelperGL3_2::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; - - // glDrawElements OpenGL 3.1 or greater - m_funcs->glDrawElementsInstancedBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - instances, - baseVertex); -} - -void GraphicsHelperGL3_2::drawArraysInstanced(GLenum primitiveType, - GLint first, - GLsizei count, - GLsizei instances) -{ - // glDrawArraysInstanced OpenGL 3.1 or greater - m_funcs->glDrawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsHelperGL3_2::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL 3"; - m_funcs->glDrawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsHelperGL3_2::drawElements(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLint baseVertex) -{ - m_funcs->glDrawElementsBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - baseVertex); -} - -void GraphicsHelperGL3_2::drawArrays(GLenum primitiveType, - GLint first, - GLsizei count) -{ - m_funcs->glDrawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperGL3_2::drawElementsIndirect(GLenum, GLenum, void *) -{ - qWarning() << "Indirect Drawing is not supported with OpenGL 3.2"; -} - -void GraphicsHelperGL3_2::drawArraysIndirect(GLenum , void *) -{ - qWarning() << "Indirect Drawing is not supported with OpenGL 3.2"; -} - -void GraphicsHelperGL3_2::setVerticesPerPatch(GLint verticesPerPatch) -{ -#if defined(QT_OPENGL_4) - if (!m_tessFuncs) { - qWarning() << "Tessellation not supported with OpenGL 3 without GL_ARB_tessellation_shader"; - return; - } - - m_tessFuncs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); -#else - Q_UNUSED(verticesPerPatch); - qWarning() << "Tessellation not supported"; -#endif -} - -void GraphicsHelperGL3_2::useProgram(GLuint programId) -{ - m_funcs->glUseProgram(programId); -} - -QVector GraphicsHelperGL3_2::programUniformsAndLocations(GLuint programId) -{ - QVector uniforms; - - GLint nbrActiveUniforms = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); - uniforms.reserve(nbrActiveUniforms); - char uniformName[256]; - for (GLint i = 0; i < nbrActiveUniforms; i++) { - ShaderUniform uniform; - GLsizei uniformNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, - &uniform.m_size, &uniform.m_type, uniformName); - uniformName[sizeof(uniformName) - 1] = '\0'; - uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); - uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); - // Work around for uniform array names that aren't returned with [0] by some drivers - if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) - uniform.m_name.append(QLatin1String("[0]")); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); - uniform.m_rawByteSize = uniformByteSize(uniform); - uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; - } - - return uniforms; -} - -QVector GraphicsHelperGL3_2::programAttributesAndLocations(GLuint programId) -{ - QVector attributes; - GLint nbrActiveAttributes = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); - attributes.reserve(nbrActiveAttributes); - char attributeName[256]; - for (GLint i = 0; i < nbrActiveAttributes; i++) { - ShaderAttribute attribute; - GLsizei attributeNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, - &attribute.m_size, &attribute.m_type, attributeName); - attributeName[sizeof(attributeName) - 1] = '\0'; - attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); - attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); - attributes.append(attribute); - } - return attributes; -} - -QVector GraphicsHelperGL3_2::programUniformBlocks(GLuint programId) -{ - QVector blocks; - GLint nbrActiveUniformsBlocks = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORM_BLOCKS, &nbrActiveUniformsBlocks); - blocks.reserve(nbrActiveUniformsBlocks); - for (GLint i = 0; i < nbrActiveUniformsBlocks; i++) { - QByteArray uniformBlockName(256, '\0'); - GLsizei length = 0; - ShaderUniformBlock uniformBlock; - m_funcs->glGetActiveUniformBlockName(programId, i, 256, &length, uniformBlockName.data()); - uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); - uniformBlock.m_index = i; - m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &uniformBlock.m_activeUniformsCount); - m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_BINDING, &uniformBlock.m_binding); - m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.m_size); - blocks.append(uniformBlock); - } - return blocks; -} - -QVector GraphicsHelperGL3_2::programShaderStorageBlocks(GLuint programId) -{ - Q_UNUSED(programId); - QVector blocks; - qWarning() << "SSBO are not supported by OpenGL 3.2 (since OpenGL 4.3)"; - return blocks; -} - -void GraphicsHelperGL3_2::vertexAttribDivisor(GLuint index, GLuint divisor) -{ - Q_UNUSED(index); - Q_UNUSED(divisor); - qCWarning(Render::Rendering) << "Vertex attribute divisor not available with OpenGL 3.2 core"; -} - -void GraphicsHelperGL3_2::vertexAttributePointer(GLenum shaderDataType, - GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const GLvoid *pointer) -{ - switch (shaderDataType) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - case GL_FLOAT_MAT2: - case GL_FLOAT_MAT2x3: - case GL_FLOAT_MAT2x4: - case GL_FLOAT_MAT3: - case GL_FLOAT_MAT3x2: - case GL_FLOAT_MAT3x4: - case GL_FLOAT_MAT4x2: - case GL_FLOAT_MAT4x3: - case GL_FLOAT_MAT4: - m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); - break; - - case GL_INT: - case GL_INT_VEC2: - case GL_INT_VEC3: - case GL_INT_VEC4: - case GL_UNSIGNED_INT: - case GL_UNSIGNED_INT_VEC2: - case GL_UNSIGNED_INT_VEC3: - case GL_UNSIGNED_INT_VEC4: - m_funcs->glVertexAttribIPointer(index, size, type, stride, pointer); - break; - - default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; - Q_UNREACHABLE(); - } -} - -void GraphicsHelperGL3_2::readBuffer(GLenum mode) -{ - m_funcs->glReadBuffer(mode); -} - -void GraphicsHelperGL3_2::drawBuffer(GLenum mode) -{ - m_funcs->glDrawBuffer(mode); -} - -void *GraphicsHelperGL3_2::fenceSync() -{ - return m_funcs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); -} - -void GraphicsHelperGL3_2::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) -{ - m_funcs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); -} - -void GraphicsHelperGL3_2::waitSync(void *sync) -{ - m_funcs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); -} - -bool GraphicsHelperGL3_2::wasSyncSignaled(void *sync) -{ - GLint v; - m_funcs->glGetSynciv(static_cast(sync), - GL_SYNC_STATUS, - sizeof(v), - nullptr, - &v); - return v == GL_SIGNALED; -} - -void GraphicsHelperGL3_2::deleteSync(void *sync) -{ - m_funcs->glDeleteSync(static_cast(sync)); -} - -void GraphicsHelperGL3_2::rasterMode(GLenum faceMode, GLenum rasterMode) -{ - m_funcs->glPolygonMode(faceMode, rasterMode); -} - -void GraphicsHelperGL3_2::blendEquation(GLenum mode) -{ - m_funcs->glBlendEquation(mode); -} - -void GraphicsHelperGL3_2::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) -{ - Q_UNUSED(buf); - Q_UNUSED(sfactor); - Q_UNUSED(dfactor); - - qWarning() << "glBlendFunci() not supported by OpenGL 3.0 (since OpenGL 4.0)"; -} - -void GraphicsHelperGL3_2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) -{ - Q_UNUSED(buf); - Q_UNUSED(sRGB); - Q_UNUSED(dRGB); - Q_UNUSED(sAlpha); - Q_UNUSED(dAlpha); - - qWarning() << "glBlendFuncSeparatei() not supported by OpenGL 3.0 (since OpenGL 4.0)"; -} - -void GraphicsHelperGL3_2::alphaTest(GLenum, GLenum) -{ - qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; -} - -void GraphicsHelperGL3_2::depthTest(GLenum mode) -{ - m_funcs->glEnable(GL_DEPTH_TEST); - m_funcs->glDepthFunc(mode); -} - -void GraphicsHelperGL3_2::depthMask(GLenum mode) -{ - m_funcs->glDepthMask(mode); -} - -void GraphicsHelperGL3_2::depthRange(GLdouble nearValue, GLdouble farValue) -{ - m_funcs->glDepthRange(nearValue, farValue); -} - -void GraphicsHelperGL3_2::frontFace(GLenum mode) -{ - m_funcs->glFrontFace(mode); - -} - -void GraphicsHelperGL3_2::setMSAAEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_MULTISAMPLE) - : m_funcs->glDisable(GL_MULTISAMPLE); -} - -void GraphicsHelperGL3_2::setAlphaCoverageEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) - : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); -} - -GLuint GraphicsHelperGL3_2::createFrameBufferObject() -{ - GLuint id; - m_funcs->glGenFramebuffers(1, &id); - return id; -} - -void GraphicsHelperGL3_2::releaseFrameBufferObject(GLuint frameBufferId) -{ - m_funcs->glDeleteFramebuffers(1, &frameBufferId); -} - -void GraphicsHelperGL3_2::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) -{ - switch (mode) { - case FBODraw: - m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); - return; - case FBORead: - m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); - return; - case FBOReadAndDraw: - default: - m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); - return; - } -} - -void GraphicsHelperGL3_2::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - Q_UNUSED(imageUnit) - Q_UNUSED(texture) - Q_UNUSED(mipLevel) - Q_UNUSED(layered) - Q_UNUSED(layer) - Q_UNUSED(access) - Q_UNUSED(format) - qWarning() << "Shader Images are not supported by OpenGL 3.2 (since OpenGL 4.2)"; - -} - -GLuint GraphicsHelperGL3_2::boundFrameBufferObject() -{ - GLint id = 0; - m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); - return id; -} - -bool GraphicsHelperGL3_2::checkFrameBufferComplete() -{ - return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); -} - -bool GraphicsHelperGL3_2::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - Q_UNUSED(attachment); - return false; -} - -void GraphicsHelperGL3_2::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; - - if (attachment.m_point <= QRenderTargetOutput::Color15) - attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - - texture->bind(); - QOpenGLTexture::Target target = texture->target(); - if (target == QOpenGLTexture::Target1DArray || target == QOpenGLTexture::Target2DArray || - target == QOpenGLTexture::Target2DMultisampleArray || target == QOpenGLTexture::Target3D) - m_funcs->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMapArray) - m_funcs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMap) - m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else - m_funcs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); - texture->release(); -} - -void GraphicsHelperGL3_2::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) -{ - Q_UNUSED(renderBuffer); - Q_UNUSED(attachment); - Q_UNREACHABLE(); -} - -bool GraphicsHelperGL3_2::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case MRT: - case UniformBufferObject: - case PrimitiveRestart: - case RenderBufferDimensionRetrieval: - case TextureDimensionRetrieval: - case BindableFragmentOutputs: - case BlitFramebuffer: - case Fences: - return true; - case Tessellation: - return !m_tessFuncs.isNull(); - default: - return false; - } -} - -void GraphicsHelperGL3_2::drawBuffers(GLsizei n, const int *bufs) -{ - // Use QVarLengthArray here - QVarLengthArray drawBufs(n); - - for (int i = 0; i < n; i++) - drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; - m_funcs->glDrawBuffers(n, drawBufs.constData()); -} - -void GraphicsHelperGL3_2::bindFragDataLocation(GLuint shader, const QHash &outputs) -{ - for (auto it = outputs.begin(), end = outputs.end(); it != end; ++it) - m_funcs->glBindFragDataLocation(shader, it.value(), it.key().toStdString().c_str()); -} - -void GraphicsHelperGL3_2::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - m_funcs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); -} - -void GraphicsHelperGL3_2::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) -{ - Q_UNUSED(programId); - Q_UNUSED(shaderStorageBlockIndex); - Q_UNUSED(shaderStorageBlockBinding); - qWarning() << "SSBO are not supported by OpenGL 3.0 (since OpenGL 4.3)"; -} - -void GraphicsHelperGL3_2::bindBufferBase(GLenum target, GLuint index, GLuint buffer) -{ - m_funcs->glBindBufferBase(target, index, buffer); -} - -void GraphicsHelperGL3_2::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - char *bufferData = buffer.data(); - - switch (description.m_type) { - - case GL_FLOAT: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_FLOAT_VEC2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_FLOAT_VEC3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_FLOAT_VEC4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_FLOAT_MAT2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); - break; - } - - case GL_FLOAT_MAT2x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); - break; - } - - case GL_FLOAT_MAT2x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); - break; - } - - case GL_FLOAT_MAT3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); - break; - } - - case GL_FLOAT_MAT3x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); - break; - } - - case GL_FLOAT_MAT3x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); - break; - } - - case GL_FLOAT_MAT4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); - break; - } - - case GL_FLOAT_MAT4x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); - break; - } - - case GL_FLOAT_MAT4x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); - break; - } - - case GL_INT: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_INT_VEC2: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_INT_VEC3: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_INT_VEC4: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_UNSIGNED_INT: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_UNSIGNED_INT_VEC2: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_UNSIGNED_INT_VEC3: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_UNSIGNED_INT_VEC4: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_BOOL: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_BOOL_VEC2: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_BOOL_VEC3: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_BOOL_VEC4: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_2D_RECT: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_1D_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: { - Q_ASSERT(description.m_size == 1); - int value = v.toInt(); - QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); - break; - } - - default: - qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; - break; - } -} - -uint GraphicsHelperGL3_2::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - int arrayStride = qMax(description.m_arrayStride, 0); - int matrixStride = qMax(description.m_matrixStride, 0); - - switch (description.m_type) { - - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - case GL_UNSIGNED_INT_VEC2: - rawByteSize = 8; - break; - - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - case GL_UNSIGNED_INT_VEC3: - rawByteSize = 12; - break; - - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - case GL_UNSIGNED_INT_VEC4: - rawByteSize = 16; - break; - - case GL_FLOAT_MAT2: - rawByteSize = matrixStride ? 2 * matrixStride : 16; - break; - - case GL_FLOAT_MAT2x4: - rawByteSize = matrixStride ? 2 * matrixStride : 32; - break; - - case GL_FLOAT_MAT4x2: - rawByteSize = matrixStride ? 4 * matrixStride : 32; - break; - - case GL_FLOAT_MAT3: - rawByteSize = matrixStride ? 3 * matrixStride : 36; - break; - - case GL_FLOAT_MAT2x3: - rawByteSize = matrixStride ? 2 * matrixStride : 24; - break; - - case GL_FLOAT_MAT3x2: - rawByteSize = matrixStride ? 3 * matrixStride : 24; - break; - - case GL_FLOAT_MAT4: - rawByteSize = matrixStride ? 4 * matrixStride : 64; - break; - - case GL_FLOAT_MAT4x3: - rawByteSize = matrixStride ? 4 * matrixStride : 48; - break; - - case GL_FLOAT_MAT3x4: - rawByteSize = matrixStride ? 3 * matrixStride : 48; - break; - - case GL_BOOL: - rawByteSize = 1; - break; - - case GL_BOOL_VEC2: - rawByteSize = 2; - break; - - case GL_BOOL_VEC3: - rawByteSize = 3; - break; - - case GL_BOOL_VEC4: - rawByteSize = 4; - break; - - case GL_INT: - case GL_FLOAT: - case GL_UNSIGNED_INT: - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_2D_RECT: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_1D_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - rawByteSize = 4; - break; - } - - return arrayStride ? rawByteSize * arrayStride : rawByteSize; -} - -void GraphicsHelperGL3_2::enableClipPlane(int clipPlane) -{ - m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL3_2::disableClipPlane(int clipPlane) -{ - m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL3_2::setClipPlane(int clipPlane, const QVector3D &normal, float distance) -{ - // deprecated - Q_UNUSED(clipPlane); - Q_UNUSED(normal); - Q_UNUSED(distance); -} - -GLint GraphicsHelperGL3_2::maxClipPlaneCount() -{ - GLint max = 0; - m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); - return max; -} - -void GraphicsHelperGL3_2::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - Q_UNUSED(barriers); - qWarning() << "memory barrier is not supported by OpenGL 3.0 (since 4.3)"; -} - -void GraphicsHelperGL3_2::enablePrimitiveRestart(int primitiveRestartIndex) -{ - m_funcs->glPrimitiveRestartIndex(primitiveRestartIndex); - m_funcs->glEnable(GL_PRIMITIVE_RESTART); -} - -void GraphicsHelperGL3_2::enableVertexAttributeArray(int location) -{ - m_funcs->glEnableVertexAttribArray(location); -} - -void GraphicsHelperGL3_2::disablePrimitiveRestart() -{ - m_funcs->glDisable(GL_PRIMITIVE_RESTART); -} - -void GraphicsHelperGL3_2::clearBufferf(GLint drawbuffer, const QVector4D &values) -{ - GLfloat vec[4] = {values[0], values[1], values[2], values[3]}; - m_funcs->glClearBufferfv(GL_COLOR, drawbuffer, vec); -} - -void GraphicsHelperGL3_2::pointSize(bool programmable, GLfloat value) -{ - if (programmable) { - m_funcs->glEnable(GL_PROGRAM_POINT_SIZE); - } else { - m_funcs->glDisable(GL_PROGRAM_POINT_SIZE); - m_funcs->glPointSize(value); - } -} - -void GraphicsHelperGL3_2::enablei(GLenum cap, GLuint index) -{ - m_funcs->glEnablei(cap, index); -} - -void GraphicsHelperGL3_2::disablei(GLenum cap, GLuint index) -{ - m_funcs->glDisablei(cap, index); -} - -void GraphicsHelperGL3_2::setSeamlessCubemap(bool enable) -{ - if (enable) - m_funcs->glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - else - m_funcs->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); -} - -QSize GraphicsHelperGL3_2::getRenderBufferDimensions(GLuint renderBufferId) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); - - return QSize(width, height); -} - -QSize GraphicsHelperGL3_2::getTextureDimensions(GLuint textureId, GLenum target, uint level) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindTexture(target, textureId); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); - m_funcs->glBindTexture(target, 0); - - return QSize(width, height); -} - -void GraphicsHelperGL3_2::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) -{ - Q_UNUSED(wx); - Q_UNUSED(wy); - Q_UNUSED(wz); - qWarning() << "Compute Shaders are not supported by OpenGL 3.2 (since OpenGL 4.3)"; -} - -char *GraphicsHelperGL3_2::mapBuffer(GLenum target, GLsizeiptr size) -{ - return static_cast(m_funcs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); -} - -GLboolean GraphicsHelperGL3_2::unmapBuffer(GLenum target) -{ - return m_funcs->glUnmapBuffer(target); -} - -void GraphicsHelperGL3_2::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform1fv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform2fv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform3fv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform4fv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform1iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform1iv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform2iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform2iv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform3iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform3iv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform4iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform4iv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform1uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform1uiv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform2uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform2uiv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform3uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform3uiv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniform4uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform4uiv(location, count, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2x3fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3x2fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2x4fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4x2fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3x4fv(location, count, false, values); -} - -void GraphicsHelperGL3_2::glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4x3fv(location, count, false, values); -} - -UniformType GraphicsHelperGL3_2::uniformTypeFromGLType(GLenum type) -{ - switch (type) { - case GL_FLOAT: - return UniformType::Float; - case GL_FLOAT_VEC2: - return UniformType::Vec2; - case GL_FLOAT_VEC3: - return UniformType::Vec3; - case GL_FLOAT_VEC4: - return UniformType::Vec4; - case GL_FLOAT_MAT2: - return UniformType::Mat2; - case GL_FLOAT_MAT3: - return UniformType::Mat3; - case GL_FLOAT_MAT4: - return UniformType::Mat4; - case GL_FLOAT_MAT2x3: - return UniformType::Mat2x3; - case GL_FLOAT_MAT3x2: - return UniformType::Mat3x2; - case GL_FLOAT_MAT2x4: - return UniformType::Mat2x4; - case GL_FLOAT_MAT4x2: - return UniformType::Mat4x2; - case GL_FLOAT_MAT3x4: - return UniformType::Mat3x4; - case GL_FLOAT_MAT4x3: - return UniformType::Mat4x3; - case GL_INT: - return UniformType::Int; - case GL_INT_VEC2: - return UniformType::IVec2; - case GL_INT_VEC3: - return UniformType::IVec3; - case GL_INT_VEC4: - return UniformType::IVec4; - case GL_UNSIGNED_INT: - return UniformType::UInt; - case GL_UNSIGNED_INT_VEC2: - return UniformType::UIVec2; - case GL_UNSIGNED_INT_VEC3: - return UniformType::UIVec3; - case GL_UNSIGNED_INT_VEC4: - return UniformType::UIVec4; - case GL_BOOL: - return UniformType::Bool; - case GL_BOOL_VEC2: - return UniformType::BVec2; - case GL_BOOL_VEC3: - return UniformType::BVec3; - case GL_BOOL_VEC4: - return UniformType::BVec4; - - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_RECT: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_SAMPLER_3D: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - return UniformType::Sampler; - default: - Q_UNREACHABLE(); - return UniformType::Float; - } -} - -void GraphicsHelperGL3_2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) -{ - m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h deleted file mode 100644 index 914afc9ff..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h +++ /dev/null @@ -1,185 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -#ifndef QT_OPENGL_ES_2 - -QT_BEGIN_NAMESPACE - -class QOpenGLFunctions_3_2_Core; -class QOpenGLExtension_ARB_tessellation_shader; - -namespace Qt3DRender { -namespace Render { - -class Q_AUTOTEST_EXPORT GraphicsHelperGL3_2 : public GraphicsHelperInterface -{ -public: - GraphicsHelperGL3_2(); - ~GraphicsHelperGL3_2(); - - // QGraphicHelperInterface interface - void alphaTest(GLenum mode1, GLenum mode2) override; - void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; - void bindFragDataLocation(GLuint shader, const QHash &outputs) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; - void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; - void blendEquation(GLenum mode) override; - void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; - void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; - void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; - GLuint boundFrameBufferObject() override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; - bool checkFrameBufferComplete() override; - void clearBufferf(GLint drawbuffer, const QVector4D &values) override; - GLuint createFrameBufferObject() override; - void depthMask(GLenum mode) override; - void depthRange(GLdouble nearValue, GLdouble farValue) override; - void depthTest(GLenum mode) override; - void disableClipPlane(int clipPlane) override; - void disablei(GLenum cap, GLuint index) override; - void disablePrimitiveRestart() override; - void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; - char *mapBuffer(GLenum target, GLsizeiptr size) override; - GLboolean unmapBuffer(GLenum target) override; - void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; - void drawArraysIndirect(GLenum mode,void *indirect) override; - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; - void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; - void drawBuffers(GLsizei n, const int *bufs) override; - void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - void enableClipPlane(int clipPlane) override; - void enablei(GLenum cap, GLuint index) override; - void enablePrimitiveRestart(int primitiveRestartIndex) override; - void enableVertexAttributeArray(int location) override; - void frontFace(GLenum mode) override; - QSize getRenderBufferDimensions(GLuint renderBufferId) override; - QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; - void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; - void pointSize(bool programmable, GLfloat value) override; - GLint maxClipPlaneCount() override; - void memoryBarrier(QMemoryBarrier::Operations barriers) override; - QVector programUniformBlocks(GLuint programId) override; - QVector programAttributesAndLocations(GLuint programId) override; - QVector programUniformsAndLocations(GLuint programId) override; - QVector programShaderStorageBlocks(GLuint programId) override; - void releaseFrameBufferObject(GLuint frameBufferId) override; - void setMSAAEnabled(bool enable) override; - void setAlphaCoverageEnabled(bool enable) override; - void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; - void setSeamlessCubemap(bool enable) override; - void setVerticesPerPatch(GLint verticesPerPatch) override; - bool supportsFeature(Feature feature) const override; - uint uniformByteSize(const ShaderUniform &description) override; - void useProgram(GLuint programId) override; - void vertexAttribDivisor(GLuint index, GLuint divisor) override; - void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; - void readBuffer(GLenum mode) override; - void drawBuffer(GLenum mode) override; - void rasterMode(GLenum faceMode, GLenum rasterMode) override; - - void *fenceSync() override; - void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; - void waitSync(void *sync) override; - bool wasSyncSignaled(void *sync) override; - void deleteSync(void *sync) override; - - void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; - - void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; - - void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; - - void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; - - UniformType uniformTypeFromGLType(GLenum glType) override; - -private: - QOpenGLFunctions_3_2_Core *m_funcs; - QScopedPointer m_tessFuncs; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp deleted file mode 100644 index ddffb38e2..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp +++ /dev/null @@ -1,1240 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelpergl3_3_p.h" - -#ifndef QT_OPENGL_ES_2 -#include -#include -#include -#include -#include - -# ifndef QT_OPENGL_3_2 -# define GL_PATCH_VERTICES 36466 -# define GL_ACTIVE_RESOURCES 0x92F5 -# define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -# define GL_BUFFER_BINDING 0x9302 -# define GL_BUFFER_DATA_SIZE 0x9303 -# define GL_NUM_ACTIVE_VARIABLES 0x9304 -# define GL_SHADER_STORAGE_BLOCK 0x92E6 -# define GL_UNIFORM 0x92E1 -# define GL_UNIFORM_BLOCK 0x92E2 -# define GL_UNIFORM_BLOCK_INDEX 0x8A3A -# define GL_UNIFORM_OFFSET 0x8A3B -# define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -# define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -# define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -# define GL_UNIFORM_BLOCK_BINDING 0x8A3F -# define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -# endif - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -GraphicsHelperGL3_3::GraphicsHelperGL3_3() - : m_funcs(nullptr) - , m_tessFuncs() -{ -} - -GraphicsHelperGL3_3::~GraphicsHelperGL3_3() -{ -} - -void GraphicsHelperGL3_3::initializeHelper(QOpenGLContext *context, - QAbstractOpenGLFunctions *functions) -{ - m_funcs = static_cast(functions); - const bool ok = m_funcs->initializeOpenGLFunctions(); - Q_ASSERT(ok); - Q_UNUSED(ok); - - if (context->hasExtension(QByteArrayLiteral("GL_ARB_tessellation_shader"))) { - m_tessFuncs.reset(new QOpenGLExtension_ARB_tessellation_shader); - m_tessFuncs->initializeOpenGLFunctions(); - } -} - -void GraphicsHelperGL3_3::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL 3"; - - // glDrawElements OpenGL 3.1 or greater - m_funcs->glDrawElementsInstancedBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - instances, - baseVertex); -} - -void GraphicsHelperGL3_3::drawArraysInstanced(GLenum primitiveType, - GLint first, - GLsizei count, - GLsizei instances) -{ - // glDrawArraysInstanced OpenGL 3.1 or greater - m_funcs->glDrawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsHelperGL3_3::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawArraysInstancedBaseInstance is not supported with OpenGL 3"; - m_funcs->glDrawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsHelperGL3_3::drawElements(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLint baseVertex) -{ - m_funcs->glDrawElementsBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - baseVertex); -} - -void GraphicsHelperGL3_3::drawElementsIndirect(GLenum, GLenum, void *) -{ - qWarning() << "Indirect Drawing is not supported with OpenGL 3"; -} - -void GraphicsHelperGL3_3::drawArrays(GLenum primitiveType, - GLint first, - GLsizei count) -{ - m_funcs->glDrawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperGL3_3::drawArraysIndirect(GLenum , void *) -{ - qWarning() << "Indirect Drawing is not supported with OpenGL 3"; -} - -void GraphicsHelperGL3_3::setVerticesPerPatch(GLint verticesPerPatch) -{ -#if defined(QT_OPENGL_4) - if (!m_tessFuncs) { - qWarning() << "Tessellation not supported with OpenGL 3 without GL_ARB_tessellation_shader"; - return; - } - - m_tessFuncs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); -#else - Q_UNUSED(verticesPerPatch); - qWarning() << "Tessellation not supported"; -#endif -} - -void GraphicsHelperGL3_3::useProgram(GLuint programId) -{ - m_funcs->glUseProgram(programId); -} - -QVector GraphicsHelperGL3_3::programUniformsAndLocations(GLuint programId) -{ - QVector uniforms; - - GLint nbrActiveUniforms = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &nbrActiveUniforms); - uniforms.reserve(nbrActiveUniforms); - char uniformName[256]; - for (GLint i = 0; i < nbrActiveUniforms; i++) { - ShaderUniform uniform; - GLsizei uniformNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, - &uniform.m_size, &uniform.m_type, uniformName); - uniformName[sizeof(uniformName) - 1] = '\0'; - uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); - uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); - // Work around for uniform array names that aren't returned with [0] by some drivers - if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) - uniform.m_name.append(QLatin1String("[0]")); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); - uniform.m_rawByteSize = uniformByteSize(uniform); - uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; - } - - return uniforms; -} - -QVector GraphicsHelperGL3_3::programAttributesAndLocations(GLuint programId) -{ - QVector attributes; - GLint nbrActiveAttributes = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); - attributes.reserve(nbrActiveAttributes); - char attributeName[256]; - for (GLint i = 0; i < nbrActiveAttributes; i++) { - ShaderAttribute attribute; - GLsizei attributeNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, - &attribute.m_size, &attribute.m_type, attributeName); - attributeName[sizeof(attributeName) - 1] = '\0'; - attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); - attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); - attributes.append(attribute); - } - return attributes; -} - -QVector GraphicsHelperGL3_3::programUniformBlocks(GLuint programId) -{ - QVector blocks; - GLint nbrActiveUniformsBlocks = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_UNIFORM_BLOCKS, &nbrActiveUniformsBlocks); - blocks.reserve(nbrActiveUniformsBlocks); - for (GLint i = 0; i < nbrActiveUniformsBlocks; i++) { - QByteArray uniformBlockName(256, '\0'); - GLsizei length = 0; - ShaderUniformBlock uniformBlock; - m_funcs->glGetActiveUniformBlockName(programId, i, 256, &length, uniformBlockName.data()); - uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); - uniformBlock.m_index = i; - m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &uniformBlock.m_activeUniformsCount); - m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_BINDING, &uniformBlock.m_binding); - m_funcs->glGetActiveUniformBlockiv(programId, i, GL_UNIFORM_BLOCK_DATA_SIZE, &uniformBlock.m_size); - blocks.append(uniformBlock); - } - return blocks; -} - -QVector GraphicsHelperGL3_3::programShaderStorageBlocks(GLuint programId) -{ - Q_UNUSED(programId); - QVector blocks; - qWarning() << "SSBO are not supported by OpenGL 3.3 (since OpenGL 4.3)"; - return blocks; -} - -void GraphicsHelperGL3_3::vertexAttribDivisor(GLuint index, GLuint divisor) -{ - m_funcs->glVertexAttribDivisor(index, divisor); -} - -void GraphicsHelperGL3_3::vertexAttributePointer(GLenum shaderDataType, - GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const GLvoid *pointer) -{ - switch (shaderDataType) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - case GL_FLOAT_MAT2: - case GL_FLOAT_MAT2x3: - case GL_FLOAT_MAT2x4: - case GL_FLOAT_MAT3: - case GL_FLOAT_MAT3x2: - case GL_FLOAT_MAT3x4: - case GL_FLOAT_MAT4x2: - case GL_FLOAT_MAT4x3: - case GL_FLOAT_MAT4: - m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); - break; - - case GL_INT: - case GL_INT_VEC2: - case GL_INT_VEC3: - case GL_INT_VEC4: - case GL_UNSIGNED_INT: - case GL_UNSIGNED_INT_VEC2: - case GL_UNSIGNED_INT_VEC3: - case GL_UNSIGNED_INT_VEC4: - m_funcs->glVertexAttribIPointer(index, size, type, stride, pointer); - break; - - default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; - } -} - -void GraphicsHelperGL3_3::readBuffer(GLenum mode) -{ - m_funcs->glReadBuffer(mode); -} - -void GraphicsHelperGL3_3::drawBuffer(GLenum mode) -{ - m_funcs->glDrawBuffer(mode); -} - -void *GraphicsHelperGL3_3::fenceSync() -{ - return m_funcs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); -} - -void GraphicsHelperGL3_3::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) -{ - m_funcs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); -} - -void GraphicsHelperGL3_3::waitSync(void *sync) -{ - m_funcs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); -} - -bool GraphicsHelperGL3_3::wasSyncSignaled(void *sync) -{ - GLint v; - m_funcs->glGetSynciv(static_cast(sync), - GL_SYNC_STATUS, - sizeof(v), - nullptr, - &v); - return v == GL_SIGNALED; -} - -void GraphicsHelperGL3_3::deleteSync(void *sync) -{ - m_funcs->glDeleteSync(static_cast(sync)); -} - -void GraphicsHelperGL3_3::rasterMode(GLenum faceMode, GLenum rasterMode) -{ - m_funcs->glPolygonMode(faceMode, rasterMode); -} - -void GraphicsHelperGL3_3::blendEquation(GLenum mode) -{ - m_funcs->glBlendEquation(mode); -} - -void GraphicsHelperGL3_3::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) -{ - Q_UNUSED(buf); - Q_UNUSED(sfactor); - Q_UNUSED(dfactor); - - qWarning() << "glBlendFunci() not supported by OpenGL 3.3 (since OpenGL 4.0)"; -} - -void GraphicsHelperGL3_3::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) -{ - Q_UNUSED(buf); - Q_UNUSED(sRGB); - Q_UNUSED(dRGB); - Q_UNUSED(sAlpha); - Q_UNUSED(dAlpha); - - qWarning() << "glBlendFuncSeparatei() not supported by OpenGL 3.3 (since OpenGL 4.0)"; -} - -void GraphicsHelperGL3_3::alphaTest(GLenum, GLenum) -{ - qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; -} - -void GraphicsHelperGL3_3::depthTest(GLenum mode) -{ - m_funcs->glEnable(GL_DEPTH_TEST); - m_funcs->glDepthFunc(mode); -} - -void GraphicsHelperGL3_3::depthMask(GLenum mode) -{ - m_funcs->glDepthMask(mode); -} - -void GraphicsHelperGL3_3::depthRange(GLdouble nearValue, GLdouble farValue) -{ - m_funcs->glDepthRange(nearValue, farValue); -} - -void GraphicsHelperGL3_3::frontFace(GLenum mode) -{ - m_funcs->glFrontFace(mode); - -} - -void GraphicsHelperGL3_3::setMSAAEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_MULTISAMPLE) - : m_funcs->glDisable(GL_MULTISAMPLE); -} - -void GraphicsHelperGL3_3::setAlphaCoverageEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) - : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); -} - -GLuint GraphicsHelperGL3_3::createFrameBufferObject() -{ - GLuint id; - m_funcs->glGenFramebuffers(1, &id); - return id; -} - -void GraphicsHelperGL3_3::releaseFrameBufferObject(GLuint frameBufferId) -{ - m_funcs->glDeleteFramebuffers(1, &frameBufferId); -} - -void GraphicsHelperGL3_3::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) -{ - switch (mode) { - case FBODraw: - m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); - return; - case FBORead: - m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); - return; - case FBOReadAndDraw: - default: - m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); - return; - } -} - -GLuint GraphicsHelperGL3_3::boundFrameBufferObject() -{ - GLint id = 0; - m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); - return id; -} - -bool GraphicsHelperGL3_3::checkFrameBufferComplete() -{ - return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); -} - -bool GraphicsHelperGL3_3::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - Q_UNUSED(attachment); - return false; -} - -void GraphicsHelperGL3_3::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; - - if (attachment.m_point <= QRenderTargetOutput::Color15) - attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - - texture->bind(); - QOpenGLTexture::Target target = texture->target(); - if (target == QOpenGLTexture::Target1DArray || target == QOpenGLTexture::Target2DArray || - target == QOpenGLTexture::Target2DMultisampleArray || target == QOpenGLTexture::Target3D) - m_funcs->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMapArray) - m_funcs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face != QAbstractTexture::AllFaces) - m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else - m_funcs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); - texture->release(); -} - -void GraphicsHelperGL3_3::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) -{ - Q_UNUSED(renderBuffer); - Q_UNUSED(attachment); - Q_UNREACHABLE(); -} - -bool GraphicsHelperGL3_3::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case MRT: - case UniformBufferObject: - case PrimitiveRestart: - case RenderBufferDimensionRetrieval: - case TextureDimensionRetrieval: - case BindableFragmentOutputs: - case BlitFramebuffer: - case Fences: - return true; - case Tessellation: - return !m_tessFuncs.isNull(); - default: - return false; - } -} - -void GraphicsHelperGL3_3::drawBuffers(GLsizei n, const int *bufs) -{ - // Use QVarLengthArray here - QVarLengthArray drawBufs(n); - - for (int i = 0; i < n; i++) - drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; - m_funcs->glDrawBuffers(n, drawBufs.constData()); -} - -void GraphicsHelperGL3_3::bindFragDataLocation(GLuint shader, const QHash &outputs) -{ - for (auto it = outputs.begin(), end = outputs.end(); it != end; ++it) - m_funcs->glBindFragDataLocation(shader, it.value(), it.key().toStdString().c_str()); -} - -void GraphicsHelperGL3_3::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - m_funcs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); -} - -void GraphicsHelperGL3_3::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) -{ - Q_UNUSED(programId); - Q_UNUSED(shaderStorageBlockIndex); - Q_UNUSED(shaderStorageBlockBinding); - qWarning() << "SSBO are not supported by OpenGL 3.3 (since OpenGL 4.3)"; -} - -void GraphicsHelperGL3_3::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - Q_UNUSED(imageUnit) - Q_UNUSED(texture) - Q_UNUSED(mipLevel) - Q_UNUSED(layered) - Q_UNUSED(layer) - Q_UNUSED(access) - Q_UNUSED(format) - qWarning() << "Shader Images are not supported by OpenGL 3.3 (since OpenGL 4.2)"; -} - -void GraphicsHelperGL3_3::bindBufferBase(GLenum target, GLuint index, GLuint buffer) -{ - m_funcs->glBindBufferBase(target, index, buffer); -} - -void GraphicsHelperGL3_3::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - char *bufferData = buffer.data(); - - switch (description.m_type) { - - case GL_FLOAT: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_FLOAT_VEC2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_FLOAT_VEC3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_FLOAT_VEC4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_FLOAT_MAT2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); - break; - } - - case GL_FLOAT_MAT2x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); - break; - } - - case GL_FLOAT_MAT2x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); - break; - } - - case GL_FLOAT_MAT3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); - break; - } - - case GL_FLOAT_MAT3x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); - break; - } - - case GL_FLOAT_MAT3x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); - break; - } - - case GL_FLOAT_MAT4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); - break; - } - - case GL_FLOAT_MAT4x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); - break; - } - - case GL_FLOAT_MAT4x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); - break; - } - - case GL_INT: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_INT_VEC2: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_INT_VEC3: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_INT_VEC4: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_UNSIGNED_INT: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_UNSIGNED_INT_VEC2: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_UNSIGNED_INT_VEC3: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_UNSIGNED_INT_VEC4: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_BOOL: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_BOOL_VEC2: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_BOOL_VEC3: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_BOOL_VEC4: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_2D_RECT: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_1D_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: { - Q_ASSERT(description.m_size == 1); - int value = v.toInt(); - QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); - break; - } - - default: - qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; - break; - } -} - -uint GraphicsHelperGL3_3::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - int arrayStride = qMax(description.m_arrayStride, 0); - int matrixStride = qMax(description.m_matrixStride, 0); - - switch (description.m_type) { - - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - case GL_UNSIGNED_INT_VEC2: - rawByteSize = 8; - break; - - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - case GL_UNSIGNED_INT_VEC3: - rawByteSize = 12; - break; - - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - case GL_UNSIGNED_INT_VEC4: - rawByteSize = 16; - break; - - case GL_FLOAT_MAT2: - rawByteSize = matrixStride ? 2 * matrixStride : 16; - break; - - case GL_FLOAT_MAT2x4: - rawByteSize = matrixStride ? 2 * matrixStride : 32; - break; - - case GL_FLOAT_MAT4x2: - rawByteSize = matrixStride ? 4 * matrixStride : 32; - break; - - case GL_FLOAT_MAT3: - rawByteSize = matrixStride ? 3 * matrixStride : 36; - break; - - case GL_FLOAT_MAT2x3: - rawByteSize = matrixStride ? 2 * matrixStride : 24; - break; - - case GL_FLOAT_MAT3x2: - rawByteSize = matrixStride ? 3 * matrixStride : 24; - break; - - case GL_FLOAT_MAT4: - rawByteSize = matrixStride ? 4 * matrixStride : 64; - break; - - case GL_FLOAT_MAT4x3: - rawByteSize = matrixStride ? 4 * matrixStride : 48; - break; - - case GL_FLOAT_MAT3x4: - rawByteSize = matrixStride ? 3 * matrixStride : 48; - break; - - case GL_BOOL: - rawByteSize = 1; - break; - - case GL_BOOL_VEC2: - rawByteSize = 2; - break; - - case GL_BOOL_VEC3: - rawByteSize = 3; - break; - - case GL_BOOL_VEC4: - rawByteSize = 4; - break; - - case GL_INT: - case GL_FLOAT: - case GL_UNSIGNED_INT: - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_2D_RECT: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_1D_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - rawByteSize = 4; - break; - } - - return arrayStride ? rawByteSize * arrayStride : rawByteSize; -} - -void GraphicsHelperGL3_3::enableClipPlane(int clipPlane) -{ - m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL3_3::disableClipPlane(int clipPlane) -{ - m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL3_3::setClipPlane(int clipPlane, const QVector3D &normal, float distance) -{ - // deprecated - Q_UNUSED(clipPlane); - Q_UNUSED(normal); - Q_UNUSED(distance); -} - -GLint GraphicsHelperGL3_3::maxClipPlaneCount() -{ - GLint max = 0; - m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); - return max; -} - -void GraphicsHelperGL3_3::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - Q_UNUSED(barriers); - qWarning() << "memory barrier is not supported by OpenGL 3.3 (since 4.3)"; -} - -void GraphicsHelperGL3_3::enablePrimitiveRestart(int primitiveRestartIndex) -{ - m_funcs->glPrimitiveRestartIndex(primitiveRestartIndex); - m_funcs->glEnable(GL_PRIMITIVE_RESTART); -} - -void GraphicsHelperGL3_3::enableVertexAttributeArray(int location) -{ - m_funcs->glEnableVertexAttribArray(location); -} - -void GraphicsHelperGL3_3::disablePrimitiveRestart() -{ - m_funcs->glDisable(GL_PRIMITIVE_RESTART); -} - -void GraphicsHelperGL3_3::clearBufferf(GLint drawbuffer, const QVector4D &values) -{ - GLfloat vec[4] = {values[0], values[1], values[2], values[3]}; - m_funcs->glClearBufferfv(GL_COLOR, drawbuffer, vec); -} - -void GraphicsHelperGL3_3::pointSize(bool programmable, GLfloat value) -{ - if (programmable) { - m_funcs->glEnable(GL_PROGRAM_POINT_SIZE); - } else { - m_funcs->glDisable(GL_PROGRAM_POINT_SIZE); - m_funcs->glPointSize(value); - } -} - -void GraphicsHelperGL3_3::enablei(GLenum cap, GLuint index) -{ - m_funcs->glEnablei(cap, index); -} - -void GraphicsHelperGL3_3::disablei(GLenum cap, GLuint index) -{ - m_funcs->glDisablei(cap, index); -} - -void GraphicsHelperGL3_3::setSeamlessCubemap(bool enable) -{ - if (enable) - m_funcs->glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - else - m_funcs->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); -} - -QSize GraphicsHelperGL3_3::getRenderBufferDimensions(GLuint renderBufferId) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); - - return QSize(width, height); -} - -QSize GraphicsHelperGL3_3::getTextureDimensions(GLuint textureId, GLenum target, uint level) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindTexture(target, textureId); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); - m_funcs->glBindTexture(target, 0); - - return QSize(width, height); -} - -void GraphicsHelperGL3_3::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) -{ - Q_UNUSED(wx); - Q_UNUSED(wy); - Q_UNUSED(wz); - qWarning() << "Compute Shaders are not supported by OpenGL 3.3 (since OpenGL 4.3)"; -} - -char *GraphicsHelperGL3_3::mapBuffer(GLenum target, GLsizeiptr size) -{ - return static_cast(m_funcs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); -} - -GLboolean GraphicsHelperGL3_3::unmapBuffer(GLenum target) -{ - return m_funcs->glUnmapBuffer(target); -} - -void GraphicsHelperGL3_3::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform1fv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform2fv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform3fv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform4fv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform1iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform1iv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform2iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform2iv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform3iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform3iv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform4iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform4iv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform1uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform1uiv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform2uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform2uiv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform3uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform3uiv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniform4uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform4uiv(location, count, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2x3fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3x2fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2x4fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4x2fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3x4fv(location, count, false, values); -} - -void GraphicsHelperGL3_3::glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4x3fv(location, count, false, values); -} - -UniformType GraphicsHelperGL3_3::uniformTypeFromGLType(GLenum type) -{ - switch (type) { - case GL_FLOAT: - return UniformType::Float; - case GL_FLOAT_VEC2: - return UniformType::Vec2; - case GL_FLOAT_VEC3: - return UniformType::Vec3; - case GL_FLOAT_VEC4: - return UniformType::Vec4; - case GL_FLOAT_MAT2: - return UniformType::Mat2; - case GL_FLOAT_MAT3: - return UniformType::Mat3; - case GL_FLOAT_MAT4: - return UniformType::Mat4; - case GL_FLOAT_MAT2x3: - return UniformType::Mat2x3; - case GL_FLOAT_MAT3x2: - return UniformType::Mat3x2; - case GL_FLOAT_MAT2x4: - return UniformType::Mat2x4; - case GL_FLOAT_MAT4x2: - return UniformType::Mat4x2; - case GL_FLOAT_MAT3x4: - return UniformType::Mat3x4; - case GL_FLOAT_MAT4x3: - return UniformType::Mat4x3; - case GL_INT: - return UniformType::Int; - case GL_INT_VEC2: - return UniformType::IVec2; - case GL_INT_VEC3: - return UniformType::IVec3; - case GL_INT_VEC4: - return UniformType::IVec4; - case GL_UNSIGNED_INT: - return UniformType::UInt; - case GL_UNSIGNED_INT_VEC2: - return UniformType::UIVec2; - case GL_UNSIGNED_INT_VEC3: - return UniformType::UIVec3; - case GL_UNSIGNED_INT_VEC4: - return UniformType::UIVec4; - case GL_BOOL: - return UniformType::Bool; - case GL_BOOL_VEC2: - return UniformType::BVec2; - case GL_BOOL_VEC3: - return UniformType::BVec3; - case GL_BOOL_VEC4: - return UniformType::BVec4; - - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_RECT: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_2D_ARRAY: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_SAMPLER_3D: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - return UniformType::Sampler; - default: - Q_UNREACHABLE(); - return UniformType::Float; - } -} - -void GraphicsHelperGL3_3::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) -{ - m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h deleted file mode 100644 index 4dbf6fe7b..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h +++ /dev/null @@ -1,185 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -#ifndef QT_OPENGL_ES_2 - -QT_BEGIN_NAMESPACE - -class QOpenGLFunctions_3_3_Core; -class QOpenGLExtension_ARB_tessellation_shader; - -namespace Qt3DRender { -namespace Render { - -class Q_AUTOTEST_EXPORT GraphicsHelperGL3_3 : public GraphicsHelperInterface -{ -public: - GraphicsHelperGL3_3(); - ~GraphicsHelperGL3_3(); - - // QGraphicHelperInterface interface - void alphaTest(GLenum mode1, GLenum mode2) override; - void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; - void bindFragDataLocation(GLuint shader, const QHash &outputs) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; - void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; - void blendEquation(GLenum mode) override; - void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; - void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; - void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; - GLuint boundFrameBufferObject() override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; - bool checkFrameBufferComplete() override; - void clearBufferf(GLint drawbuffer, const QVector4D &values) override; - GLuint createFrameBufferObject() override; - void depthMask(GLenum mode) override; - void depthRange(GLdouble nearValue, GLdouble farValue) override; - void depthTest(GLenum mode) override; - void disableClipPlane(int clipPlane) override; - void disablei(GLenum cap, GLuint index) override; - void disablePrimitiveRestart() override; - void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; - char *mapBuffer(GLenum target, GLsizeiptr size) override; - GLboolean unmapBuffer(GLenum target) override; - void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; - void drawArraysIndirect(GLenum mode,void *indirect) override; - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; - void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; - void drawBuffers(GLsizei n, const int *bufs) override; - void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - void enableClipPlane(int clipPlane) override; - void enablei(GLenum cap, GLuint index) override; - void enablePrimitiveRestart(int primitiveRestartIndex) override; - void enableVertexAttributeArray(int location) override; - void frontFace(GLenum mode) override; - QSize getRenderBufferDimensions(GLuint renderBufferId) override; - QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; - void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; - void pointSize(bool programmable, GLfloat value) override; - GLint maxClipPlaneCount() override; - void memoryBarrier(QMemoryBarrier::Operations barriers) override; - QVector programUniformBlocks(GLuint programId) override; - QVector programAttributesAndLocations(GLuint programId) override; - QVector programUniformsAndLocations(GLuint programId) override; - QVector programShaderStorageBlocks(GLuint programId) override; - void releaseFrameBufferObject(GLuint frameBufferId) override; - void setMSAAEnabled(bool enable) override; - void setAlphaCoverageEnabled(bool enable) override; - void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; - void setSeamlessCubemap(bool enable) override; - void setVerticesPerPatch(GLint verticesPerPatch) override; - bool supportsFeature(Feature feature) const override; - uint uniformByteSize(const ShaderUniform &description) override; - void useProgram(GLuint programId) override; - void vertexAttribDivisor(GLuint index, GLuint divisor) override; - void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; - void readBuffer(GLenum mode) override; - void drawBuffer(GLenum mode) override; - void rasterMode(GLenum faceMode, GLenum rasterMode) override; - - void *fenceSync() override; - void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; - void waitSync(void *sync) override; - bool wasSyncSignaled(void *sync) override; - void deleteSync(void *sync) override; - - void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; - - void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; - - void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; - - void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; - - UniformType uniformTypeFromGLType(GLenum glType) override; - -private: - QOpenGLFunctions_3_3_Core *m_funcs; - QScopedPointer m_tessFuncs; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp deleted file mode 100644 index 60caed273..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp +++ /dev/null @@ -1,1442 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicshelpergl4_p.h" - -#ifndef QT_OPENGL_ES_2 -#include -#include -#include -#include -#include - -# ifndef QT_OPENGL_4_3 -# ifndef GL_PATCH_VERTICES -# define GL_PATCH_VERTICES 36466 -# endif -# define GL_ACTIVE_RESOURCES 0x92F5 -# define GL_BUFFER_BINDING 0x9302 -# define GL_BUFFER_DATA_SIZE 0x9303 -# define GL_NUM_ACTIVE_VARIABLES 0x9304 -# define GL_SHADER_STORAGE_BLOCK 0x92E6 -# define GL_UNIFORM 0x92E1 -# define GL_UNIFORM_BLOCK 0x92E2 -# define GL_UNIFORM_BLOCK_INDEX 0x8A3A -# define GL_UNIFORM_OFFSET 0x8A3B -# define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -# define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -# define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -# define GL_UNIFORM_BLOCK_BINDING 0x8A3F -# define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -# define GL_ALL_BARRIER_BITS 0xFFFFFFFF -# define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 -# define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 -# define GL_UNIFORM_BARRIER_BIT 0x00000004 -# define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 -# define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 -# define GL_COMMAND_BARRIER_BIT 0x00000040 -# define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 -# define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 -# define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 -# define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 -# define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 -# define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 -# define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 -# define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 -# define GL_IMAGE_1D 0x904C -# define GL_IMAGE_2D 0x904D -# define GL_IMAGE_3D 0x904E -# define GL_IMAGE_2D_RECT 0x904F -# define GL_IMAGE_CUBE 0x9050 -# define GL_IMAGE_BUFFER 0x9051 -# define GL_IMAGE_1D_ARRAY 0x9052 -# define GL_IMAGE_2D_ARRAY 0x9053 -# define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 -# define GL_IMAGE_2D_MULTISAMPLE 0x9055 -# define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 -# define GL_INT_IMAGE_1D 0x9057 -# define GL_INT_IMAGE_2D 0x9058 -# define GL_INT_IMAGE_3D 0x9059 -# define GL_INT_IMAGE_2D_RECT 0x905A -# define GL_INT_IMAGE_CUBE 0x905B -# define GL_INT_IMAGE_BUFFER 0x905C -# define GL_INT_IMAGE_1D_ARRAY 0x905D -# define GL_INT_IMAGE_2D_ARRAY 0x905E -# define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F -# define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 -# define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 -# define GL_UNSIGNED_INT_IMAGE_1D 0x9062 -# define GL_UNSIGNED_INT_IMAGE_2D 0x9063 -# define GL_UNSIGNED_INT_IMAGE_3D 0x9064 -# define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 -# define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 -# define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 -# define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 -# define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 -# define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A -# define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B -# define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C -# endif - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -namespace { - -GLbitfield memoryBarrierGLBitfield(QMemoryBarrier::Operations barriers) -{ - GLbitfield bits = 0; - - if (barriers.testFlag(QMemoryBarrier::All)) { - bits |= GL_ALL_BARRIER_BITS; - return bits; - } - - if (barriers.testFlag(QMemoryBarrier::VertexAttributeArray)) - bits |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::ElementArray)) - bits |= GL_ELEMENT_ARRAY_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::Uniform)) - bits |= GL_UNIFORM_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::TextureFetch)) - bits |= GL_TEXTURE_FETCH_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::ShaderImageAccess)) - bits |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::Command)) - bits |= GL_COMMAND_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::PixelBuffer)) - bits |= GL_PIXEL_BUFFER_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::TextureUpdate)) - bits |= GL_TEXTURE_UPDATE_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::BufferUpdate)) - bits |= GL_BUFFER_UPDATE_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::FrameBuffer)) - bits |= GL_FRAMEBUFFER_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::TransformFeedback)) - bits |= GL_TRANSFORM_FEEDBACK_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::AtomicCounter)) - bits |= GL_ATOMIC_COUNTER_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::ShaderStorage)) - bits |= GL_SHADER_STORAGE_BARRIER_BIT; - if (barriers.testFlag(QMemoryBarrier::QueryBuffer)) - bits |= GL_QUERY_BUFFER_BARRIER_BIT; - - return bits; -} - -} - -GraphicsHelperGL4::GraphicsHelperGL4() - : m_funcs(nullptr) -{ -} - -void GraphicsHelperGL4::initializeHelper(QOpenGLContext *context, - QAbstractOpenGLFunctions *functions) -{ - Q_UNUSED(context); - m_funcs = static_cast(functions); - const bool ok = m_funcs->initializeOpenGLFunctions(); - Q_ASSERT(ok); - Q_UNUSED(ok); -} - -void GraphicsHelperGL4::drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLsizei instances, - GLint baseVertex, - GLint baseInstance) -{ - if (baseInstance != 0) - qWarning() << "glDrawElementsInstancedBaseVertexBaseInstance is not supported with OpenGL ES 2"; - - // glDrawElements OpenGL 3.1 or greater - m_funcs->glDrawElementsInstancedBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - instances, - baseVertex); -} - -void GraphicsHelperGL4::drawArraysInstanced(GLenum primitiveType, - GLint first, - GLsizei count, - GLsizei instances) -{ - // glDrawArraysInstanced OpenGL 3.1 or greater - m_funcs->glDrawArraysInstanced(primitiveType, - first, - count, - instances); -} - -void GraphicsHelperGL4::drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) -{ - m_funcs->glDrawArraysInstancedBaseInstance(primitiveType, - first, - count, - instances, - baseInstance); -} - -void GraphicsHelperGL4::drawElements(GLenum primitiveType, - GLsizei primitiveCount, - GLint indexType, - void *indices, - GLint baseVertex) -{ - m_funcs->glDrawElementsBaseVertex(primitiveType, - primitiveCount, - indexType, - indices, - baseVertex); -} - -void GraphicsHelperGL4::drawElementsIndirect(GLenum mode, - GLenum type, - void *indirect) -{ - m_funcs->glDrawElementsIndirect(mode, type, indirect); -} - -void GraphicsHelperGL4::drawArrays(GLenum primitiveType, - GLint first, - GLsizei count) -{ - m_funcs->glDrawArrays(primitiveType, - first, - count); -} - -void GraphicsHelperGL4::drawArraysIndirect(GLenum mode, void *indirect) -{ - m_funcs->glDrawArraysIndirect(mode, indirect); -} - -void GraphicsHelperGL4::setVerticesPerPatch(GLint verticesPerPatch) -{ - m_funcs->glPatchParameteri(GL_PATCH_VERTICES, verticesPerPatch); -} - -void GraphicsHelperGL4::useProgram(GLuint programId) -{ - m_funcs->glUseProgram(programId); -} - -QVector GraphicsHelperGL4::programUniformsAndLocations(GLuint programId) -{ - QVector uniforms; - - GLint nbrActiveUniforms = 0; - m_funcs->glGetProgramInterfaceiv(programId, GL_UNIFORM, GL_ACTIVE_RESOURCES, &nbrActiveUniforms); - uniforms.reserve(nbrActiveUniforms); - char uniformName[256]; - for (GLint i = 0; i < nbrActiveUniforms; ++i) { - ShaderUniform uniform; - GLsizei uniformNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveUniform(programId, i, sizeof(uniformName) - 1, &uniformNameLength, - &uniform.m_size, &uniform.m_type, uniformName); - uniformName[sizeof(uniformName) - 1] = '\0'; - uniform.m_location = m_funcs->glGetUniformLocation(programId, uniformName); - uniform.m_name = QString::fromUtf8(uniformName, uniformNameLength); - // Work around for uniform array names that aren't returned with [0] by some drivers - if (uniform.m_size > 1 && !uniform.m_name.endsWith(QLatin1String("[0]"))) - uniform.m_name.append(QLatin1String("[0]")); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &uniform.m_blockIndex); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_OFFSET, &uniform.m_offset); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_ARRAY_STRIDE, &uniform.m_arrayStride); - m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); - uniform.m_rawByteSize = uniformByteSize(uniform); - uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; - } - - return uniforms; -} - -QVector GraphicsHelperGL4::programAttributesAndLocations(GLuint programId) -{ - QVector attributes; - GLint nbrActiveAttributes = 0; - m_funcs->glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &nbrActiveAttributes); - attributes.reserve(nbrActiveAttributes); - char attributeName[256]; - for (GLint i = 0; i < nbrActiveAttributes; ++i) { - ShaderAttribute attribute; - GLsizei attributeNameLength = 0; - // Size is 1 for scalar and more for struct or arrays - // Type is the GL Type - m_funcs->glGetActiveAttrib(programId, i, sizeof(attributeName) - 1, &attributeNameLength, - &attribute.m_size, &attribute.m_type, attributeName); - attributeName[sizeof(attributeName) - 1] = '\0'; - attribute.m_location = m_funcs->glGetAttribLocation(programId, attributeName); - attribute.m_name = QString::fromUtf8(attributeName, attributeNameLength); - attributes.append(attribute); - } - return attributes; -} - -QVector GraphicsHelperGL4::programUniformBlocks(GLuint programId) -{ - QVector blocks; - GLint nbrActiveUniformsBlocks = 0; - m_funcs->glGetProgramInterfaceiv(programId, GL_UNIFORM_BLOCK, GL_ACTIVE_RESOURCES, &nbrActiveUniformsBlocks); - blocks.reserve(nbrActiveUniformsBlocks); - for (GLint i = 0; i < nbrActiveUniformsBlocks; ++i) { - QByteArray uniformBlockName(256, '\0'); - GLsizei length = 0; - ShaderUniformBlock uniformBlock; - m_funcs->glGetProgramResourceName(programId, GL_UNIFORM_BLOCK, i, 256, &length, uniformBlockName.data()); - uniformBlock.m_name = QString::fromUtf8(uniformBlockName.left(length)); - uniformBlock.m_index = i; - GLenum prop = GL_BUFFER_BINDING; - m_funcs->glGetProgramResourceiv(programId, GL_UNIFORM_BLOCK, i, 1, &prop, 4, NULL, &uniformBlock.m_binding); - prop = GL_BUFFER_DATA_SIZE; - m_funcs->glGetProgramResourceiv(programId, GL_UNIFORM_BLOCK, i, 1, &prop, 4, NULL, &uniformBlock.m_size); - prop = GL_NUM_ACTIVE_VARIABLES; - m_funcs->glGetProgramResourceiv(programId, GL_UNIFORM_BLOCK, i, 1, &prop, 4, NULL, &uniformBlock.m_activeUniformsCount); - blocks.append(uniformBlock); - } - return blocks; -} - -QVector GraphicsHelperGL4::programShaderStorageBlocks(GLuint programId) -{ - QVector blocks; - GLint nbrActiveShaderStorageBlocks = 0; - m_funcs->glGetProgramInterfaceiv(programId, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &nbrActiveShaderStorageBlocks); - blocks.reserve(nbrActiveShaderStorageBlocks); - for (GLint i = 0; i < nbrActiveShaderStorageBlocks; ++i) { - QByteArray storageBlockName(256, '\0'); - GLsizei length = 0; - ShaderStorageBlock storageBlock; - m_funcs->glGetProgramResourceName(programId, GL_SHADER_STORAGE_BLOCK, i, 256, &length, storageBlockName.data()); - storageBlock.m_index = i; - storageBlock.m_name = QString::fromUtf8(storageBlockName.left(length)); - GLenum prop = GL_BUFFER_BINDING; - m_funcs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_binding); - prop = GL_BUFFER_DATA_SIZE; - m_funcs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_size); - prop = GL_NUM_ACTIVE_VARIABLES; - m_funcs->glGetProgramResourceiv(programId, GL_SHADER_STORAGE_BLOCK, i, 1, &prop, 4, NULL, &storageBlock.m_activeVariablesCount); - blocks.push_back(storageBlock); - } - return blocks; -} - -void GraphicsHelperGL4::vertexAttribDivisor(GLuint index, GLuint divisor) -{ - m_funcs->glVertexAttribDivisor(index, divisor); -} - -void GraphicsHelperGL4::vertexAttributePointer(GLenum shaderDataType, - GLuint index, - GLint size, - GLenum type, - GLboolean normalized, - GLsizei stride, - const GLvoid *pointer) -{ - switch (shaderDataType) { - case GL_FLOAT: - case GL_FLOAT_VEC2: - case GL_FLOAT_VEC3: - case GL_FLOAT_VEC4: - case GL_FLOAT_MAT2: - case GL_FLOAT_MAT2x3: - case GL_FLOAT_MAT2x4: - case GL_FLOAT_MAT3: - case GL_FLOAT_MAT3x2: - case GL_FLOAT_MAT3x4: - case GL_FLOAT_MAT4x2: - case GL_FLOAT_MAT4x3: - case GL_FLOAT_MAT4: - m_funcs->glVertexAttribPointer(index, size, type, normalized, stride, pointer); - break; - - case GL_INT: - case GL_INT_VEC2: - case GL_INT_VEC3: - case GL_INT_VEC4: - case GL_UNSIGNED_INT: - case GL_UNSIGNED_INT_VEC2: - case GL_UNSIGNED_INT_VEC3: - case GL_UNSIGNED_INT_VEC4: - m_funcs->glVertexAttribIPointer(index, size, type, stride, pointer); - break; - - case GL_DOUBLE: - case GL_DOUBLE_VEC2: - case GL_DOUBLE_VEC3: - case GL_DOUBLE_VEC4: - m_funcs->glVertexAttribLPointer(index, size, type, stride, pointer); - break; - - default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; - Q_UNREACHABLE(); - } -} - -void GraphicsHelperGL4::readBuffer(GLenum mode) -{ - m_funcs->glReadBuffer(mode); -} - -void GraphicsHelperGL4::drawBuffer(GLenum mode) -{ - m_funcs->glDrawBuffer(mode); -} - -void *GraphicsHelperGL4::fenceSync() -{ - return m_funcs->glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); -} - -void GraphicsHelperGL4::clientWaitSync(void *sync, GLuint64 nanoSecTimeout) -{ - qDebug() << Q_FUNC_INFO << sync << static_cast(sync); - GLenum e = m_funcs->glClientWaitSync(static_cast(sync), GL_SYNC_FLUSH_COMMANDS_BIT, nanoSecTimeout); - qDebug() << e; -} - -void GraphicsHelperGL4::waitSync(void *sync) -{ - m_funcs->glWaitSync(static_cast(sync), 0, GL_TIMEOUT_IGNORED); -} - -bool GraphicsHelperGL4::wasSyncSignaled(void *sync) -{ - GLint v = 0; - m_funcs->glGetSynciv(static_cast(sync), - GL_SYNC_STATUS, - sizeof(v), - nullptr, - &v); - return v == GL_SIGNALED; -} - -void GraphicsHelperGL4::deleteSync(void *sync) -{ - m_funcs->glDeleteSync(static_cast(sync)); -} - -void GraphicsHelperGL4::rasterMode(GLenum faceMode, GLenum rasterMode) -{ - m_funcs->glPolygonMode(faceMode, rasterMode); -} - -void GraphicsHelperGL4::glUniform1fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform1fv(location, count, values); -} - -void GraphicsHelperGL4::glUniform2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform2fv(location, count, values); -} - -void GraphicsHelperGL4::glUniform3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform3fv(location, count, values); -} - -void GraphicsHelperGL4::glUniform4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniform4fv(location, count, values); -} - -void GraphicsHelperGL4::glUniform1iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform1iv(location, count, values); -} - -void GraphicsHelperGL4::glUniform2iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform2iv(location, count, values); -} - -void GraphicsHelperGL4::glUniform3iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform3iv(location, count, values); -} - -void GraphicsHelperGL4::glUniform4iv(GLint location, GLsizei count, const GLint *values) -{ - m_funcs->glUniform4iv(location, count, values); -} - -void GraphicsHelperGL4::glUniform1uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform1uiv(location, count, values); -} - -void GraphicsHelperGL4::glUniform2uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform2uiv(location, count, values); -} - -void GraphicsHelperGL4::glUniform3uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform3uiv(location, count, values); -} - -void GraphicsHelperGL4::glUniform4uiv(GLint location, GLsizei count, const GLuint *values) -{ - m_funcs->glUniform4uiv(location, count, values); -} - -void GraphicsHelperGL4::glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2x3fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3x2fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix2x4fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4x2fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix3x4fv(location, count, false, values); -} - -void GraphicsHelperGL4::glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *values) -{ - m_funcs->glUniformMatrix4x3fv(location, count, false, values); -} - -UniformType GraphicsHelperGL4::uniformTypeFromGLType(GLenum type) -{ - switch (type) { - case GL_FLOAT: - return UniformType::Float; - case GL_FLOAT_VEC2: - return UniformType::Vec2; - case GL_FLOAT_VEC3: - return UniformType::Vec3; - case GL_FLOAT_VEC4: - return UniformType::Vec4; - case GL_FLOAT_MAT2: - return UniformType::Mat2; - case GL_FLOAT_MAT3: - return UniformType::Mat3; - case GL_FLOAT_MAT4: - return UniformType::Mat4; - case GL_FLOAT_MAT2x3: - return UniformType::Mat2x3; - case GL_FLOAT_MAT3x2: - return UniformType::Mat3x2; - case GL_FLOAT_MAT2x4: - return UniformType::Mat2x4; - case GL_FLOAT_MAT4x2: - return UniformType::Mat4x2; - case GL_FLOAT_MAT3x4: - return UniformType::Mat3x4; - case GL_FLOAT_MAT4x3: - return UniformType::Mat4x3; - case GL_INT: - return UniformType::Int; - case GL_INT_VEC2: - return UniformType::IVec2; - case GL_INT_VEC3: - return UniformType::IVec3; - case GL_INT_VEC4: - return UniformType::IVec4; - case GL_UNSIGNED_INT: - return UniformType::UInt; - case GL_UNSIGNED_INT_VEC2: - return UniformType::UIVec2; - case GL_UNSIGNED_INT_VEC3: - return UniformType::UIVec3; - case GL_UNSIGNED_INT_VEC4: - return UniformType::UIVec4; - case GL_BOOL: - return UniformType::Bool; - case GL_BOOL_VEC2: - return UniformType::BVec2; - case GL_BOOL_VEC3: - return UniformType::BVec3; - case GL_BOOL_VEC4: - return UniformType::BVec4; - - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_RECT: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_CUBE_MAP_ARRAY: - case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_SAMPLER_3D: - case GL_SAMPLER_BUFFER: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_CUBE_MAP_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: - return UniformType::Sampler; - - case GL_IMAGE_1D: - case GL_IMAGE_2D: - case GL_IMAGE_3D: - case GL_IMAGE_2D_RECT: - case GL_IMAGE_CUBE: - case GL_IMAGE_BUFFER: - case GL_IMAGE_1D_ARRAY: - case GL_IMAGE_2D_ARRAY: - case GL_IMAGE_CUBE_MAP_ARRAY: - case GL_IMAGE_2D_MULTISAMPLE: - case GL_IMAGE_2D_MULTISAMPLE_ARRAY: - case GL_INT_IMAGE_1D: - case GL_INT_IMAGE_2D: - case GL_INT_IMAGE_3D: - case GL_INT_IMAGE_2D_RECT: - case GL_INT_IMAGE_CUBE: - case GL_INT_IMAGE_BUFFER: - case GL_INT_IMAGE_1D_ARRAY: - case GL_INT_IMAGE_2D_ARRAY: - case GL_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_INT_IMAGE_2D_MULTISAMPLE: - case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_IMAGE_1D: - case GL_UNSIGNED_INT_IMAGE_2D: - case GL_UNSIGNED_INT_IMAGE_3D: - case GL_UNSIGNED_INT_IMAGE_2D_RECT: - case GL_UNSIGNED_INT_IMAGE_CUBE: - case GL_UNSIGNED_INT_IMAGE_BUFFER: - case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: - return UniformType::Image; - - default: - // TO DO: Add support for Doubles and Images - Q_UNREACHABLE(); - return UniformType::Float; - } -} - -void GraphicsHelperGL4::blendEquation(GLenum mode) -{ - m_funcs->glBlendEquation(mode); -} - -void GraphicsHelperGL4::blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) -{ - m_funcs->glBlendFunci(buf, sfactor, dfactor); -} - -void GraphicsHelperGL4::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) -{ - m_funcs->glBlendFuncSeparatei(buf, sRGB, dRGB, sAlpha, dAlpha); -} - -void GraphicsHelperGL4::alphaTest(GLenum, GLenum) -{ - qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; -} - -void GraphicsHelperGL4::depthTest(GLenum mode) -{ - m_funcs->glEnable(GL_DEPTH_TEST); - m_funcs->glDepthFunc(mode); -} - -void GraphicsHelperGL4::depthMask(GLenum mode) -{ - m_funcs->glDepthMask(mode); -} - -void GraphicsHelperGL4::depthRange(GLdouble nearValue, GLdouble farValue) -{ - m_funcs->glDepthRange(nearValue, farValue); -} - -void GraphicsHelperGL4::frontFace(GLenum mode) -{ - m_funcs->glFrontFace(mode); - -} - -void GraphicsHelperGL4::setMSAAEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_MULTISAMPLE) - : m_funcs->glDisable(GL_MULTISAMPLE); -} - -void GraphicsHelperGL4::setAlphaCoverageEnabled(bool enabled) -{ - enabled ? m_funcs->glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) - : m_funcs->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); -} - -GLuint GraphicsHelperGL4::createFrameBufferObject() -{ - GLuint id; - m_funcs->glGenFramebuffers(1, &id); - return id; -} - -void GraphicsHelperGL4::releaseFrameBufferObject(GLuint frameBufferId) -{ - m_funcs->glDeleteFramebuffers(1, &frameBufferId); -} - -void GraphicsHelperGL4::bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) -{ - switch (mode) { - case FBODraw: - m_funcs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBufferId); - return; - case FBORead: - m_funcs->glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferId); - return; - case FBOReadAndDraw: - default: - m_funcs->glBindFramebuffer(GL_FRAMEBUFFER, frameBufferId); - return; - } -} - -void GraphicsHelperGL4::bindImageTexture(GLuint imageUnit, GLuint texture, - GLint mipLevel, GLboolean layered, - GLint layer, GLenum access, GLenum format) -{ - m_funcs->glBindImageTexture(imageUnit, - texture, - mipLevel, - layered, - layer, - access, - format); -} - -GLuint GraphicsHelperGL4::boundFrameBufferObject() -{ - GLint id = 0; - m_funcs->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &id); - return id; -} - -bool GraphicsHelperGL4::checkFrameBufferComplete() -{ - return (m_funcs->glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); -} - -bool GraphicsHelperGL4::frameBufferNeedsRenderBuffer(const Attachment &attachment) -{ - Q_UNUSED(attachment); - return false; -} - -void GraphicsHelperGL4::bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) -{ - GLenum attr = GL_DEPTH_STENCIL_ATTACHMENT; - - if (attachment.m_point <= QRenderTargetOutput::Color15) - attr = GL_COLOR_ATTACHMENT0 + attachment.m_point; - else if (attachment.m_point == QRenderTargetOutput::Depth) - attr = GL_DEPTH_ATTACHMENT; - else if (attachment.m_point == QRenderTargetOutput::Stencil) - attr = GL_STENCIL_ATTACHMENT; - - texture->bind(); - QOpenGLTexture::Target target = texture->target(); - if (target == QOpenGLTexture::Target1DArray || target == QOpenGLTexture::Target2DArray || - target == QOpenGLTexture::Target2DMultisampleArray || target == QOpenGLTexture::Target3D) - m_funcs->glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMapArray) - m_funcs->glFramebufferTexture3D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel, attachment.m_layer); - else if (target == QOpenGLTexture::TargetCubeMap && attachment.m_face != QAbstractTexture::AllFaces) - m_funcs->glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attr, attachment.m_face, texture->textureId(), attachment.m_mipLevel); - else - m_funcs->glFramebufferTexture(GL_DRAW_FRAMEBUFFER, attr, texture->textureId(), attachment.m_mipLevel); - texture->release(); -} - -void GraphicsHelperGL4::bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) -{ - Q_UNUSED(renderBuffer); - Q_UNUSED(attachment); - Q_UNREACHABLE(); -} - -bool GraphicsHelperGL4::supportsFeature(GraphicsHelperInterface::Feature feature) const -{ - switch (feature) { - case MRT: - case Tessellation: - case UniformBufferObject: - case BindableFragmentOutputs: - case PrimitiveRestart: - case RenderBufferDimensionRetrieval: - case TextureDimensionRetrieval: - case ShaderStorageObject: - case Compute: - case DrawBuffersBlend: - case BlitFramebuffer: - case IndirectDrawing: - case MapBuffer: - case Fences: - case ShaderImage: - return true; - default: - return false; - } -} - -void GraphicsHelperGL4::drawBuffers(GLsizei n, const int *bufs) -{ - // Use QVarLengthArray here - QVarLengthArray drawBufs(n); - - for (int i = 0; i < n; i++) - drawBufs[i] = GL_COLOR_ATTACHMENT0 + bufs[i]; - m_funcs->glDrawBuffers(n, drawBufs.constData()); -} - -void GraphicsHelperGL4::bindFragDataLocation(GLuint shader, const QHash &outputs) -{ - for (auto it = outputs.begin(), end = outputs.end(); it != end; ++it) - m_funcs->glBindFragDataLocation(shader, it.value(), it.key().toStdString().c_str()); -} - -void GraphicsHelperGL4::bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) -{ - m_funcs->glUniformBlockBinding(programId, uniformBlockIndex, uniformBlockBinding); -} - -void GraphicsHelperGL4::bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) -{ - m_funcs->glShaderStorageBlockBinding(programId, shaderStorageBlockIndex, shaderStorageBlockBinding); -} - -void GraphicsHelperGL4::bindBufferBase(GLenum target, GLuint index, GLuint buffer) -{ - m_funcs->glBindBufferBase(target, index, buffer); -} - -void GraphicsHelperGL4::buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) -{ - char *bufferData = buffer.data(); - - switch (description.m_type) { - - case GL_FLOAT: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_FLOAT_VEC2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_FLOAT_VEC3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_FLOAT_VEC4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_FLOAT_MAT2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 2); - break; - } - - case GL_FLOAT_MAT2x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 3); - break; - } - - case GL_FLOAT_MAT2x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 2, 4); - break; - } - - case GL_FLOAT_MAT3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 9); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 3); - break; - } - - case GL_FLOAT_MAT3x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 6); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 2); - break; - } - - case GL_FLOAT_MAT3x4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 3, 4); - break; - } - - case GL_FLOAT_MAT4: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 16); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 4); - break; - } - - case GL_FLOAT_MAT4x2: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 8); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 2); - break; - } - - case GL_FLOAT_MAT4x3: { - const GLfloat *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 12); - QGraphicsUtils::fillDataMatrixArray(bufferData, data, description, 4, 3); - break; - } - - case GL_INT: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_INT_VEC2: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_INT_VEC3: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_INT_VEC4: { - const GLint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_UNSIGNED_INT: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_UNSIGNED_INT_VEC2: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_UNSIGNED_INT_VEC3: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_UNSIGNED_INT_VEC4: { - const GLuint *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_BOOL: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 1); - QGraphicsUtils::fillDataArray(bufferData, data, description, 1); - break; - } - - case GL_BOOL_VEC2: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 2); - QGraphicsUtils::fillDataArray(bufferData, data, description, 2); - break; - } - - case GL_BOOL_VEC3: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 3); - QGraphicsUtils::fillDataArray(bufferData, data, description, 3); - break; - } - - case GL_BOOL_VEC4: { - const GLboolean *data = QGraphicsUtils::valueArrayFromVariant(v, description.m_size, 4); - QGraphicsUtils::fillDataArray(bufferData, data, description, 4); - break; - } - - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_2D_RECT: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_1D_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_IMAGE_1D: - case GL_IMAGE_2D: - case GL_IMAGE_3D: - case GL_IMAGE_2D_RECT: - case GL_IMAGE_CUBE: - case GL_IMAGE_BUFFER: - case GL_IMAGE_1D_ARRAY: - case GL_IMAGE_2D_ARRAY: - case GL_IMAGE_CUBE_MAP_ARRAY: - case GL_IMAGE_2D_MULTISAMPLE: - case GL_IMAGE_2D_MULTISAMPLE_ARRAY: - case GL_INT_IMAGE_1D: - case GL_INT_IMAGE_2D: - case GL_INT_IMAGE_3D: - case GL_INT_IMAGE_2D_RECT: - case GL_INT_IMAGE_CUBE: - case GL_INT_IMAGE_BUFFER: - case GL_INT_IMAGE_1D_ARRAY: - case GL_INT_IMAGE_2D_ARRAY: - case GL_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_INT_IMAGE_2D_MULTISAMPLE: - case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_IMAGE_1D: - case GL_UNSIGNED_INT_IMAGE_2D: - case GL_UNSIGNED_INT_IMAGE_3D: - case GL_UNSIGNED_INT_IMAGE_2D_RECT: - case GL_UNSIGNED_INT_IMAGE_CUBE: - case GL_UNSIGNED_INT_IMAGE_BUFFER: - case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: { - Q_ASSERT(description.m_size == 1); - int value = v.toInt(); - QGraphicsUtils::fillDataArray(bufferData, &value, description, 1); - break; - } - - default: - qWarning() << Q_FUNC_INFO << "unsupported uniform type:" << description.m_type << "for " << description.m_name; - break; - } -} - -uint GraphicsHelperGL4::uniformByteSize(const ShaderUniform &description) -{ - uint rawByteSize = 0; - int arrayStride = qMax(description.m_arrayStride, 0); - int matrixStride = qMax(description.m_matrixStride, 0); - - switch (description.m_type) { - - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - case GL_UNSIGNED_INT_VEC2: - rawByteSize = 8; - break; - - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - case GL_UNSIGNED_INT_VEC3: - rawByteSize = 12; - break; - - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - case GL_UNSIGNED_INT_VEC4: - rawByteSize = 16; - break; - - case GL_FLOAT_MAT2: - rawByteSize = matrixStride ? 2 * matrixStride : 16; - break; - - case GL_FLOAT_MAT2x4: - rawByteSize = matrixStride ? 2 * matrixStride : 32; - break; - - case GL_FLOAT_MAT4x2: - rawByteSize = matrixStride ? 4 * matrixStride : 32; - break; - - case GL_FLOAT_MAT3: - rawByteSize = matrixStride ? 3 * matrixStride : 36; - break; - - case GL_FLOAT_MAT2x3: - rawByteSize = matrixStride ? 2 * matrixStride : 24; - break; - - case GL_FLOAT_MAT3x2: - rawByteSize = matrixStride ? 3 * matrixStride : 24; - break; - - case GL_FLOAT_MAT4: - rawByteSize = matrixStride ? 4 * matrixStride : 64; - break; - - case GL_FLOAT_MAT4x3: - rawByteSize = matrixStride ? 4 * matrixStride : 48; - break; - - case GL_FLOAT_MAT3x4: - rawByteSize = matrixStride ? 3 * matrixStride : 48; - break; - - case GL_BOOL: - rawByteSize = 1; - break; - - case GL_BOOL_VEC2: - rawByteSize = 2; - break; - - case GL_BOOL_VEC3: - rawByteSize = 3; - break; - - case GL_BOOL_VEC4: - rawByteSize = 4; - break; - - case GL_INT: - case GL_FLOAT: - case GL_UNSIGNED_INT: - case GL_SAMPLER_1D: - case GL_SAMPLER_2D: - case GL_SAMPLER_3D: - case GL_SAMPLER_CUBE: - case GL_SAMPLER_BUFFER: - case GL_SAMPLER_2D_RECT: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_3D: - case GL_INT_SAMPLER_CUBE: - case GL_INT_SAMPLER_BUFFER: - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_BUFFER: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_CUBE_SHADOW: - case GL_SAMPLER_1D_ARRAY: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - case GL_SAMPLER_1D_ARRAY_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_MULTISAMPLE: - case GL_INT_SAMPLER_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: - case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: - case GL_IMAGE_1D: - case GL_IMAGE_2D: - case GL_IMAGE_3D: - case GL_IMAGE_2D_RECT: - case GL_IMAGE_CUBE: - case GL_IMAGE_BUFFER: - case GL_IMAGE_1D_ARRAY: - case GL_IMAGE_2D_ARRAY: - case GL_IMAGE_CUBE_MAP_ARRAY: - case GL_IMAGE_2D_MULTISAMPLE: - case GL_IMAGE_2D_MULTISAMPLE_ARRAY: - case GL_INT_IMAGE_1D: - case GL_INT_IMAGE_2D: - case GL_INT_IMAGE_3D: - case GL_INT_IMAGE_2D_RECT: - case GL_INT_IMAGE_CUBE: - case GL_INT_IMAGE_BUFFER: - case GL_INT_IMAGE_1D_ARRAY: - case GL_INT_IMAGE_2D_ARRAY: - case GL_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_INT_IMAGE_2D_MULTISAMPLE: - case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: - case GL_UNSIGNED_INT_IMAGE_1D: - case GL_UNSIGNED_INT_IMAGE_2D: - case GL_UNSIGNED_INT_IMAGE_3D: - case GL_UNSIGNED_INT_IMAGE_2D_RECT: - case GL_UNSIGNED_INT_IMAGE_CUBE: - case GL_UNSIGNED_INT_IMAGE_BUFFER: - case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: - case GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY: - case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: - case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: - rawByteSize = 4; - break; - - default: { - qWarning() << Q_FUNC_INFO << "unable to deduce rawByteSize for uniform type:" << description.m_type << "for uniform" << description.m_name; - break; - } - - } - - return arrayStride ? rawByteSize * arrayStride : rawByteSize; -} - -void GraphicsHelperGL4::enableClipPlane(int clipPlane) -{ - m_funcs->glEnable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL4::disableClipPlane(int clipPlane) -{ - m_funcs->glDisable(GL_CLIP_DISTANCE0 + clipPlane); -} - -void GraphicsHelperGL4::setClipPlane(int, const QVector3D &, float) -{ - // deprecated -} - -GLint GraphicsHelperGL4::maxClipPlaneCount() -{ - GLint max = 0; - m_funcs->glGetIntegerv(GL_MAX_CLIP_DISTANCES, &max); - return max; -} - -void GraphicsHelperGL4::memoryBarrier(QMemoryBarrier::Operations barriers) -{ - m_funcs->glMemoryBarrier(memoryBarrierGLBitfield(barriers)); -} - -void GraphicsHelperGL4::enablePrimitiveRestart(int primitiveRestartIndex) -{ - m_funcs->glPrimitiveRestartIndex(primitiveRestartIndex); - m_funcs->glEnable(GL_PRIMITIVE_RESTART); -} - -void GraphicsHelperGL4::enableVertexAttributeArray(int location) -{ - m_funcs->glEnableVertexAttribArray(location); -} - -void GraphicsHelperGL4::disablePrimitiveRestart() -{ - m_funcs->glDisable(GL_PRIMITIVE_RESTART); -} - -void GraphicsHelperGL4::clearBufferf(GLint drawbuffer, const QVector4D &values) -{ - GLfloat vec[4] = {values[0], values[1], values[2], values[3]}; - m_funcs->glClearBufferfv(GL_COLOR, drawbuffer, vec); -} - -void GraphicsHelperGL4::pointSize(bool programmable, GLfloat value) -{ - if (programmable) { - m_funcs->glEnable(GL_PROGRAM_POINT_SIZE); - } else { - m_funcs->glDisable(GL_PROGRAM_POINT_SIZE); - m_funcs->glPointSize(value); - } -} - -void GraphicsHelperGL4::enablei(GLenum cap, GLuint index) -{ - m_funcs->glEnablei(cap, index); -} - -void GraphicsHelperGL4::disablei(GLenum cap, GLuint index) -{ - m_funcs->glDisablei(cap, index); -} - -void GraphicsHelperGL4::setSeamlessCubemap(bool enable) -{ - if (enable) - m_funcs->glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - else - m_funcs->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); -} - -QSize GraphicsHelperGL4::getRenderBufferDimensions(GLuint renderBufferId) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width); - m_funcs->glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height); - m_funcs->glBindRenderbuffer(GL_RENDERBUFFER, 0); - - return QSize(width, height); -} - -QSize GraphicsHelperGL4::getTextureDimensions(GLuint textureId, GLenum target, uint level) -{ - GLint width = 0; - GLint height = 0; - - m_funcs->glBindTexture(target, textureId); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width); - m_funcs->glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height); - m_funcs->glBindTexture(target, 0); - - return QSize(width, height); -} - -void GraphicsHelperGL4::dispatchCompute(GLuint wx, GLuint wy, GLuint wz) -{ - m_funcs->glDispatchCompute(wx, wy, wz); -} - -char *GraphicsHelperGL4::mapBuffer(GLenum target, GLsizeiptr size) -{ - return static_cast(m_funcs->glMapBufferRange(target, 0, size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)); -} - -GLboolean GraphicsHelperGL4::unmapBuffer(GLenum target) -{ - return m_funcs->glUnmapBuffer(target); -} - -void GraphicsHelperGL4::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) -{ - m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h deleted file mode 100644 index d3ce0d079..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -#ifndef QT_OPENGL_ES_2 - -QT_BEGIN_NAMESPACE - -class QOpenGLFunctions_4_3_Core; - -namespace Qt3DRender { -namespace Render { - -class Q_AUTOTEST_EXPORT GraphicsHelperGL4 : public GraphicsHelperInterface -{ -public: - GraphicsHelperGL4(); - - // QGraphicHelperInterface interface - void alphaTest(GLenum mode1, GLenum mode2) override; - void bindBufferBase(GLenum target, GLuint index, GLuint buffer) override; - void bindFragDataLocation(GLuint shader, const QHash &outputs) override; - bool frameBufferNeedsRenderBuffer(const Attachment &attachment) override; - void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) override; - void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) override; - void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) override; - void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) override; - void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) override; - void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override; - void blendEquation(GLenum mode) override; - void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) override; - void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) override; - void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override; - GLuint boundFrameBufferObject() override; - void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; - bool checkFrameBufferComplete() override; - void clearBufferf(GLint drawbuffer, const QVector4D &values) override; - GLuint createFrameBufferObject() override; - void depthMask(GLenum mode) override; - void depthRange(GLdouble nearValue, GLdouble farValue) override; - void depthTest(GLenum mode) override; - void disableClipPlane(int clipPlane) override; - void disablei(GLenum cap, GLuint index) override; - void disablePrimitiveRestart() override; - void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) override; - char *mapBuffer(GLenum target, GLsizeiptr size) override; - GLboolean unmapBuffer(GLenum target) override; - void drawArrays(GLenum primitiveType, GLint first, GLsizei count) override; - void drawArraysIndirect(GLenum mode,void *indirect) override; - void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) override; - void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseInstance) override; - void drawBuffers(GLsizei n, const int *bufs) override; - void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLint baseVertex = 0) override; - void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) override; - void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void *indices, GLsizei instances, GLint baseVertex = 0, GLint baseInstance = 0) override; - void enableClipPlane(int clipPlane) override; - void enablei(GLenum cap, GLuint index) override; - void enablePrimitiveRestart(int primitiveRestartIndex) override; - void enableVertexAttributeArray(int location) override; - void frontFace(GLenum mode) override; - QSize getRenderBufferDimensions(GLuint renderBufferId) override; - QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) override; - void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) override; - void pointSize(bool programmable, GLfloat value) override; - GLint maxClipPlaneCount() override; - void memoryBarrier(QMemoryBarrier::Operations barriers) override; - QVector programUniformBlocks(GLuint programId) override; - QVector programAttributesAndLocations(GLuint programId) override; - QVector programUniformsAndLocations(GLuint programId) override; - QVector programShaderStorageBlocks(GLuint programId) override; - void releaseFrameBufferObject(GLuint frameBufferId) override; - void setMSAAEnabled(bool enable) override; - void setAlphaCoverageEnabled(bool enable) override; - void setClipPlane(int clipPlane, const QVector3D &normal, float distance) override; - void setSeamlessCubemap(bool enable) override; - void setVerticesPerPatch(GLint verticesPerPatch) override; - bool supportsFeature(Feature feature) const override; - uint uniformByteSize(const ShaderUniform &description) override; - void useProgram(GLuint programId) override; - void vertexAttribDivisor(GLuint index, GLuint divisor) override; - void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) override; - void readBuffer(GLenum mode) override; - void drawBuffer(GLenum mode) override; - void rasterMode(GLenum faceMode, GLenum rasterMode) override; - - void *fenceSync() override; - void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) override; - void waitSync(void *sync) override; - bool wasSyncSignaled(void *sync) override; - void deleteSync(void *sync) override; - - void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) override; - - void glUniform1iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform2iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform3iv(GLint location, GLsizei count, const GLint *value) override; - void glUniform4iv(GLint location, GLsizei count, const GLint *value) override; - - void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) override; - void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) override; - - void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) override; - void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) override; - - UniformType uniformTypeFromGLType(GLenum glType) override; - -private: - QOpenGLFunctions_4_3_Core *m_funcs; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // !QT_OPENGL_ES_2 - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h b/src/render/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h deleted file mode 100644 index 21146c32b..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h +++ /dev/null @@ -1,203 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -struct Attachment; -class RenderBuffer; - -class GraphicsHelperInterface -{ -public: - enum Feature { - MRT = 0, - Tessellation, - UniformBufferObject, - BindableFragmentOutputs, - PrimitiveRestart, - RenderBufferDimensionRetrieval, - TextureDimensionRetrieval, - ShaderStorageObject, - Compute, - DrawBuffersBlend, - BlitFramebuffer, - IndirectDrawing, - MapBuffer, - Fences, - ShaderImage - }; - - enum FBOBindMode { - FBODraw, - FBORead, - FBOReadAndDraw - }; - - virtual ~GraphicsHelperInterface() {} - virtual void alphaTest(GLenum mode1, GLenum mode2) = 0; - virtual void bindBufferBase(GLenum target, GLuint index, GLuint buffer) = 0; - virtual void bindFragDataLocation(GLuint shader, const QHash &outputs) = 0; - virtual bool frameBufferNeedsRenderBuffer(const Attachment &attachment) = 0; - virtual void bindFrameBufferAttachment(QOpenGLTexture *texture, const Attachment &attachment) = 0; - virtual void bindFrameBufferAttachment(RenderBuffer *renderBuffer, const Attachment &attachment) = 0; - virtual void bindFrameBufferObject(GLuint frameBufferId, FBOBindMode mode) = 0; - virtual void bindImageTexture(GLuint imageUnit, GLuint texture, GLint mipLevel, GLboolean layered, GLint layer, GLenum access, GLenum format) = 0; - virtual void bindShaderStorageBlock(GLuint programId, GLuint shaderStorageBlockIndex, GLuint shaderStorageBlockBinding) = 0; - virtual void bindUniformBlock(GLuint programId, GLuint uniformBlockIndex, GLuint uniformBlockBinding) = 0; - virtual void blendEquation(GLenum mode) = 0; - virtual void blendFunci(GLuint buf, GLenum sfactor, GLenum dfactor) = 0; - virtual void blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, GLenum sAlpha, GLenum dAlpha) = 0; - virtual void blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) = 0; - virtual GLuint boundFrameBufferObject() = 0; - virtual void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) = 0; - virtual bool checkFrameBufferComplete() = 0; - virtual void clearBufferf(GLint drawbuffer, const QVector4D &values) = 0; - virtual GLuint createFrameBufferObject() = 0; - virtual void depthRange(GLdouble nearValue, GLdouble farValue) = 0; - virtual void depthMask(GLenum mode) = 0; - virtual void depthTest(GLenum mode) = 0; - virtual void disableClipPlane(int clipPlane) = 0; - virtual void disablei(GLenum cap, GLuint index) = 0; - virtual void disablePrimitiveRestart() = 0; - virtual void dispatchCompute(GLuint wx, GLuint wy, GLuint wz) = 0; - virtual char *mapBuffer(GLenum target, GLsizeiptr size) = 0; - virtual GLboolean unmapBuffer(GLenum target) = 0; - virtual void drawArrays(GLenum primitiveType, GLint first, GLsizei count) = 0; - virtual void drawArraysIndirect(GLenum mode,void *indirect) = 0; - virtual void drawArraysInstanced(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances) = 0; - virtual void drawArraysInstancedBaseInstance(GLenum primitiveType, GLint first, GLsizei count, GLsizei instances, GLsizei baseinstance) = 0; - virtual void drawBuffers(GLsizei n, const int *bufs) = 0; - virtual void drawElements(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLint baseVertex) = 0; - virtual void drawElementsIndirect(GLenum mode, GLenum type, void *indirect) = 0; - virtual void drawElementsInstancedBaseVertexBaseInstance(GLenum primitiveType, GLsizei primitiveCount, GLint indexType, void * indices, GLsizei instances, GLint baseVertex, GLint baseInstance) = 0; - virtual void enableClipPlane(int clipPlane) = 0; - virtual void enablei(GLenum cap, GLuint index) = 0; - virtual void enablePrimitiveRestart(int primitiveRestartIndex) = 0; - virtual void enableVertexAttributeArray(int location) = 0; - virtual void frontFace(GLenum mode) = 0; - virtual QSize getRenderBufferDimensions(GLuint renderBufferId) = 0; - virtual QSize getTextureDimensions(GLuint textureId, GLenum target, uint level = 0) = 0; - virtual void initializeHelper(QOpenGLContext *context, QAbstractOpenGLFunctions *functions) = 0; - virtual GLint maxClipPlaneCount() = 0; - virtual void memoryBarrier(QMemoryBarrier::Operations barriers) = 0; - virtual void pointSize(bool programmable, GLfloat value) = 0; - virtual QVector programAttributesAndLocations(GLuint programId) = 0; - virtual QVector programUniformsAndLocations(GLuint programId) = 0; - virtual QVector programUniformBlocks(GLuint programId) = 0; - virtual QVector programShaderStorageBlocks(GLuint programId) = 0; - virtual void releaseFrameBufferObject(GLuint frameBufferId) = 0; - virtual void setAlphaCoverageEnabled(bool enable) = 0; - virtual void setClipPlane(int clipPlane, const QVector3D &normal, float distance) = 0; - virtual void setMSAAEnabled(bool enable) = 0; - virtual void setSeamlessCubemap(bool enable) = 0; - virtual void setVerticesPerPatch(GLint verticesPerPatch) = 0; - virtual bool supportsFeature(Feature feature) const = 0; - virtual uint uniformByteSize(const ShaderUniform &description) = 0; - virtual void useProgram(GLuint programId) = 0; - virtual void vertexAttribDivisor(GLuint index, GLuint divisor) = 0; - virtual void vertexAttributePointer(GLenum shaderDataType, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) = 0; - virtual void readBuffer(GLenum mode) = 0; - virtual void drawBuffer(GLenum mode) = 0; - virtual void rasterMode(GLenum faceMode, GLenum rasterMode) = 0; - - virtual void *fenceSync() = 0; - virtual void clientWaitSync(void *sync, GLuint64 nanoSecTimeout) = 0; - virtual void waitSync(void *sync) = 0; - virtual bool wasSyncSignaled(void *sync) = 0; - virtual void deleteSync(void *sync) = 0; - - virtual void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) = 0; - - virtual void glUniform1iv(GLint location, GLsizei count, const GLint *value) = 0; - virtual void glUniform2iv(GLint location, GLsizei count, const GLint *value) = 0; - virtual void glUniform3iv(GLint location, GLsizei count, const GLint *value) = 0; - virtual void glUniform4iv(GLint location, GLsizei count, const GLint *value) = 0; - - virtual void glUniform1uiv(GLint location, GLsizei count, const GLuint *value) = 0; - virtual void glUniform2uiv(GLint location, GLsizei count, const GLuint *value) = 0; - virtual void glUniform3uiv(GLint location, GLsizei count, const GLuint *value) = 0; - virtual void glUniform4uiv(GLint location, GLsizei count, const GLuint *value) = 0; - - virtual void glUniformMatrix2fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix3fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix4fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix2x3fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix3x2fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix2x4fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix4x2fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix3x4fv(GLint location, GLsizei count, const GLfloat *value) = 0; - virtual void glUniformMatrix4x3fv(GLint location, GLsizei count, const GLfloat *value) = 0; - - virtual UniformType uniformTypeFromGLType(GLenum glType) = 0; -}; - - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelpers.pri b/src/render/renderers/opengl/graphicshelpers/graphicshelpers.pri deleted file mode 100644 index f2f7274d7..000000000 --- a/src/render/renderers/opengl/graphicshelpers/graphicshelpers.pri +++ /dev/null @@ -1,33 +0,0 @@ -#DEFINES += QT3D_RENDER_ASPECT_OPENGL_DEBUG - -INCLUDEPATH += $$PWD - -HEADERS += \ - $$PWD/glfence_p.h \ - $$PWD/graphicscontext_p.h \ - $$PWD/graphicshelperinterface_p.h \ - $$PWD/graphicshelperes2_p.h \ - $$PWD/graphicshelperes3_p.h \ - $$PWD/graphicshelperes3_1_p.h \ - $$PWD/graphicshelperes3_2_p.h \ - $$PWD/graphicshelpergl2_p.h \ - $$PWD/graphicshelpergl3_3_p.h \ - $$PWD/graphicshelpergl4_p.h \ - $$PWD/graphicshelpergl3_2_p.h \ - $$PWD/imagesubmissioncontext_p.h \ - $$PWD/submissioncontext_p.h \ - $$PWD/texturesubmissioncontext_p.h - -SOURCES += \ - $$PWD/graphicscontext.cpp \ - $$PWD/graphicshelperes2.cpp \ - $$PWD/graphicshelperes3.cpp \ - $$PWD/graphicshelperes3_1.cpp \ - $$PWD/graphicshelperes3_2.cpp \ - $$PWD/graphicshelpergl2.cpp \ - $$PWD/graphicshelpergl3_3.cpp \ - $$PWD/graphicshelpergl4.cpp \ - $$PWD/graphicshelpergl3_2.cpp \ - $$PWD/imagesubmissioncontext.cpp \ - $$PWD/submissioncontext.cpp \ - $$PWD/texturesubmissioncontext.cpp diff --git a/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp deleted file mode 100644 index ca600f994..000000000 --- a/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "imagesubmissioncontext_p.h" -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -// ES 3.1+ or GL 4.2+ -#ifndef GL_READ_ONLY -#define GL_READ_ONLY 0x88B8 -#endif -#ifndef GL_WRITE_ONLY -#define GL_WRITE_ONLY 0x88B9 -#endif -#ifndef GL_READ_WRITE -#define GL_READ_WRITE 0x88BA -#endif - -namespace Qt3DRender { -namespace Render { - -class GraphicsContext; -class GLTexture; - -namespace { - -GLenum glAccessEnumForShaderImageAccess(QShaderImage::Access access) -{ - switch (access) { - case QShaderImage::ReadOnly: - return GL_READ_ONLY; - case QShaderImage::WriteOnly: - return GL_WRITE_ONLY; - case QShaderImage::ReadWrite: - default: - break; - } - return GL_READ_WRITE; -} - -GLenum glImageFormatToGL(QShaderImage::ImageFormat format) -{ - // Right now we can abuse from the fact that the ImageFormat enum values - // have been assigned the same value as the GL enum - return GLenum(format); -} - -GLenum glImageFormatForShaderImageFormat(QShaderImage::ImageFormat format, - QAbstractTexture::TextureFormat textureFormat) -{ - Q_ASSERT_X(format != QShaderImage::NoFormat, Q_FUNC_INFO, "Valid image format or Automatic expected"); - - if (format != QShaderImage::Automatic) - return glImageFormatToGL(format); - - // Otherwise try to mind to best texture format - switch (textureFormat) { - case QAbstractTexture::R8_UNorm: - return glImageFormatToGL(QShaderImage::R8_UNorm); - case QAbstractTexture::RG8_UNorm: - return glImageFormatToGL(QShaderImage::RG8_UNorm); - case QAbstractTexture::RGBA8_UNorm: - return glImageFormatToGL(QShaderImage::RGBA8_UNorm); - - case QAbstractTexture::R16_UNorm: - return glImageFormatToGL(QShaderImage::R16_UNorm); - case QAbstractTexture::RG16_UNorm: - return glImageFormatToGL(QShaderImage::RG16_UNorm); - case QAbstractTexture::RGBA16_UNorm: - return glImageFormatToGL(QShaderImage::RGBA16_UNorm); - - case QAbstractTexture::R8_SNorm: - return glImageFormatToGL(QShaderImage::R8_SNorm); - case QAbstractTexture::RG8_SNorm: - return glImageFormatToGL(QShaderImage::RG8_SNorm); - case QAbstractTexture::RGBA8_SNorm: - return glImageFormatToGL(QShaderImage::RGBA8_SNorm); - - case QAbstractTexture::R16_SNorm: - return glImageFormatToGL(QShaderImage::R16_SNorm); - case QAbstractTexture::RG16_SNorm: - return glImageFormatToGL(QShaderImage::RG16_SNorm); - case QAbstractTexture::RGBA16_SNorm: - return glImageFormatToGL(QShaderImage::RGBA16_SNorm); - - case QAbstractTexture::R8U: - return glImageFormatToGL(QShaderImage::R8U); - case QAbstractTexture::RG8U: - return glImageFormatToGL(QShaderImage::RG8U); - case QAbstractTexture::RGBA8U: - return glImageFormatToGL(QShaderImage::RGBA8U); - - case QAbstractTexture::R16U: - return glImageFormatToGL(QShaderImage::R16U); - case QAbstractTexture::RG16U: - return glImageFormatToGL(QShaderImage::RG16U); - case QAbstractTexture::RGBA16U: - return glImageFormatToGL(QShaderImage::RGBA16U); - - case QAbstractTexture::R32U: - return glImageFormatToGL(QShaderImage::R32U); - case QAbstractTexture::RG32U: - return glImageFormatToGL(QShaderImage::RG32U); - case QAbstractTexture::RGBA32U: - return glImageFormatToGL(QShaderImage::RGBA32U); - - case QAbstractTexture::R8I: - return glImageFormatToGL(QShaderImage::R8I); - case QAbstractTexture::RG8I: - return glImageFormatToGL(QShaderImage::RG8I); - case QAbstractTexture::RGBA8I: - return glImageFormatToGL(QShaderImage::RGBA8I); - - case QAbstractTexture::R16I: - return glImageFormatToGL(QShaderImage::R16I); - case QAbstractTexture::RG16I: - return glImageFormatToGL(QShaderImage::RG16I); - case QAbstractTexture::RGBA16I: - return glImageFormatToGL(QShaderImage::RGBA16I); - - case QAbstractTexture::R32I: - return glImageFormatToGL(QShaderImage::R32I); - case QAbstractTexture::RG32I: - return glImageFormatToGL(QShaderImage::RG32I); - case QAbstractTexture::RGBA32I: - return glImageFormatToGL(QShaderImage::RGBA32I); - - case QAbstractTexture::R16F: - return glImageFormatToGL(QShaderImage::R16F); - case QAbstractTexture::RG16F: - return glImageFormatToGL(QShaderImage::RG16F); - case QAbstractTexture::RGBA16F: - return glImageFormatToGL(QShaderImage::RGBA16F); - - case QAbstractTexture::R32F: - return glImageFormatToGL(QShaderImage::R32F); - case QAbstractTexture::RG32F: - return glImageFormatToGL(QShaderImage::RG32F); - case QAbstractTexture::RGBA32F: - return glImageFormatToGL(QShaderImage::RGBA32F); - - case QAbstractTexture::RG11B10F: - return glImageFormatToGL(QShaderImage::RG11B10F); - case QAbstractTexture::RGB10A2: - return glImageFormatToGL(QShaderImage::RGB10A2); - case QAbstractTexture::RGB10A2U: - return glImageFormatToGL(QShaderImage::RGB10A2U); - - default: - qWarning() << "Cannot map Texture format" << textureFormat << "to a valid Image Format"; - Q_UNREACHABLE(); - return GL_NONE; - } -} - -} // anonymous - -ImageSubmissionContext::ImageSubmissionContext() - : m_ctx(nullptr) -{ -} - -void ImageSubmissionContext::initialize(GraphicsContext *context) -{ - m_ctx = context; - m_activeImages.resize(m_ctx->maxImageUnitsCount()); -} - -void ImageSubmissionContext::endDrawing() -{ - // Reduce score of all active Images - decayImageScores(); -} - -// Return Image Unit for Image -// If Image was used previously and recently, it will return the last used unit -// for that image. Otherwise it will try to return the image unit the least used. -int ImageSubmissionContext::activateImage(ShaderImage *image, GLTexture *tex) -{ - const int onUnit = assignUnitForImage(image->peerId()); - - if (onUnit < 0) { - qWarning() << "Unable to find available image unit"; - return -1; - } - - QOpenGLTexture *glTex = tex->getGLTexture(); - if (glTex == nullptr) { - qWarning() << "Unable to retrieve valid texture for Image"; - return -1; - } - - // Bind Image against Texture and resolve Image Format - m_ctx->bindImageTexture(onUnit, - glTex->textureId(), - image->mipLevel(), - image->layered(), - image->layer(), - glAccessEnumForShaderImageAccess(image->access()), - glImageFormatForShaderImageFormat(image->format(), - tex->properties().format)); - - // Store information about the Texture/Image on ActiveImage for given - // image unit - m_activeImages[onUnit].shaderImageId = image->peerId(); - m_activeImages[onUnit].texture = tex; - m_activeImages[onUnit].score = 200; - m_activeImages[onUnit].pinned = true; - - return onUnit; -} - -// Unset pinned Active Image and reduce their score -void ImageSubmissionContext::deactivateImages() -{ - for (int u = 0, m = m_activeImages.size(); u < m; ++u) { - if (m_activeImages[u].pinned) { - m_activeImages[u].pinned = false; - m_activeImages[u].score = qMax(m_activeImages[u].score - 1, 0); - return; - } - } -} - -// Reduce score of all active images (pinned or not) -void ImageSubmissionContext::decayImageScores() -{ - for (int u = 0, m = m_activeImages.size(); u < m; ++u) - m_activeImages[u].score = qMax(m_activeImages[u].score - 1, 0); -} - -int ImageSubmissionContext::assignUnitForImage(Qt3DCore::QNodeId shaderImageId) -{ - int lowestScoredUnit = -1; - int lowestScore = 0xfffffff; - - const int m = m_activeImages.size(); - for (int u = 0; u < m; ++u) { - if (m_activeImages[u].shaderImageId == shaderImageId) - return u; - } - - for (int u = 0; u < m; ++u) { - // No image is currently active on the image unit - // we save the image unit with the texture that has been on there - // the longest time while not being used - if (!m_activeImages[u].pinned) { - const int score = m_activeImages[u].score; - if (score < lowestScore) { - lowestScore = score; - lowestScoredUnit = u; - } - } - } - - if (lowestScoredUnit == -1) - qCWarning(Backend) << Q_FUNC_INFO << "No free image units!"; - - return lowestScoredUnit; -} - - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h b/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h deleted file mode 100644 index 6d39f469b..000000000 --- a/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H -#define QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class GraphicsContext; -class GLTexture; -class ShaderImage; - -class Q_AUTOTEST_EXPORT ImageSubmissionContext -{ -public: - ImageSubmissionContext(); - - void initialize(GraphicsContext *context); - void endDrawing(); - int activateImage(ShaderImage *image, GLTexture *tex); - void deactivateImages(); - -private: - void decayImageScores(); - int assignUnitForImage(Qt3DCore::QNodeId shaderImageId); - - struct ActiveImage - { - Qt3DCore::QNodeId shaderImageId; - GLTexture *texture = nullptr; - int score = 0; - bool pinned = false; - }; - QVector m_activeImages; - GraphicsContext *m_ctx; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp deleted file mode 100644 index 8afec233d..000000000 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp +++ /dev/null @@ -1,1574 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "submissioncontext_p.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(QT_OPENGL_ES_2) -#include -#include -#include -#include -#include -#include -#include -#include -#endif -#include -#include - -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -#ifndef GL_READ_FRAMEBUFFER -#define GL_READ_FRAMEBUFFER 0x8CA8 -#endif - -#ifndef GL_DRAW_FRAMEBUFFER -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#endif - -namespace Qt3DRender { -namespace Render { - - -static QHash static_contexts; - -unsigned int nextFreeContextId() -{ - for (unsigned int i=0; i < 0xffff; ++i) { - if (!static_contexts.contains(i)) - return i; - } - - qFatal("Couldn't find free context ID"); - return 0; -} - -namespace { - -GLBuffer::Type attributeTypeToGLBufferType(QAttribute::AttributeType type) -{ - switch (type) { - case QAttribute::VertexAttribute: - return GLBuffer::ArrayBuffer; - case QAttribute::IndexAttribute: - return GLBuffer::IndexBuffer; - case QAttribute::DrawIndirectAttribute: - return GLBuffer::DrawIndirectBuffer; - default: - Q_UNREACHABLE(); - } -} - -void copyGLFramebufferDataToImage(QImage &img, const uchar *srcData, uint stride, uint width, uint height, QAbstractTexture::TextureFormat format) -{ - switch (format) { - case QAbstractTexture::RGBA32F: - { - uchar *srcScanline = (uchar *)srcData + stride * (height - 1); - for (uint i = 0; i < height; ++i) { - uchar *dstScanline = img.scanLine(i); - float *pSrc = (float*)srcScanline; - for (uint j = 0; j < width; j++) { - *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+2], 1.0f)); - *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+1], 1.0f)); - *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+0], 1.0f)); - *dstScanline++ = (uchar)(255.0f * qBound(0.0f, pSrc[4*j+3], 1.0f)); - } - srcScanline -= stride; - } - } break; - default: - { - uchar* srcScanline = (uchar *)srcData + stride * (height - 1); - for (uint i = 0; i < height; ++i) { - memcpy(img.scanLine(i), srcScanline, stride); - srcScanline -= stride; - } - } break; - } -} - -// Render States Helpers -template -void applyStateHelper(const GenericState *state, SubmissionContext *gc) -{ - Q_UNUSED(state); - Q_UNUSED(gc); -} - -template<> -void applyStateHelper(const AlphaFunc *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->alphaTest(std::get<0>(values), std::get<1>(values)); -} - -template<> -void applyStateHelper(const BlendEquationArguments *state, SubmissionContext *gc) -{ - const auto values = state->values(); - // Un-indexed BlendEquationArguments -> Use normal GL1.0 functions - if (std::get<5>(values) < 0) { - if (std::get<4>(values)) { - gc->openGLContext()->functions()->glEnable(GL_BLEND); - gc->openGLContext()->functions()->glBlendFuncSeparate(std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); - } else { - gc->openGLContext()->functions()->glDisable(GL_BLEND); - } - } - // BlendEquationArguments for a particular Draw Buffer. Different behaviours for - // (1) 3.0-3.3: only enablei/disablei supported. - // (2) 4.0+: all operations supported. - // We just ignore blend func parameter for (1), so no warnings get - // printed. - else { - if (std::get<4>(values)) { - gc->enablei(GL_BLEND, std::get<5>(values)); - if (gc->supportsDrawBuffersBlend()) { - gc->blendFuncSeparatei(std::get<5>(values), std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); - } - } else { - gc->disablei(GL_BLEND, std::get<5>(values)); - } - } -} - -template<> -void applyStateHelper(const BlendEquation *state, SubmissionContext *gc) -{ - gc->blendEquation(std::get<0>(state->values())); -} - -template<> -void applyStateHelper(const MSAAEnabled *state, SubmissionContext *gc) -{ - gc->setMSAAEnabled(std::get<0>(state->values())); -} - -template<> -void applyStateHelper(const DepthRange *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->depthRange(std::get<0>(values), std::get<1>(values)); -} - -template<> -void applyStateHelper(const DepthTest *state, SubmissionContext *gc) -{ - gc->depthTest(std::get<0>(state->values())); -} - -template<> -void applyStateHelper(const RasterMode *state, SubmissionContext *gc) -{ - gc->rasterMode(std::get<0>(state->values()), std::get<1>(state->values())); -} - -template<> -void applyStateHelper(const NoDepthMask *state, SubmissionContext *gc) -{ - gc->depthMask(std::get<0>(state->values())); -} - -template<> -void applyStateHelper(const CullFace *state, SubmissionContext *gc) -{ - const auto values = state->values(); - if (std::get<0>(values) == QCullFace::NoCulling) { - gc->openGLContext()->functions()->glDisable(GL_CULL_FACE); - } else { - gc->openGLContext()->functions()->glEnable(GL_CULL_FACE); - gc->openGLContext()->functions()->glCullFace(std::get<0>(values)); - } -} - -template<> -void applyStateHelper(const FrontFace *state, SubmissionContext *gc) -{ - gc->frontFace(std::get<0>(state->values())); -} - -template<> -void applyStateHelper(const ScissorTest *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->openGLContext()->functions()->glEnable(GL_SCISSOR_TEST); - gc->openGLContext()->functions()->glScissor(std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); -} - -template<> -void applyStateHelper(const StencilTest *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->openGLContext()->functions()->glEnable(GL_STENCIL_TEST); - gc->openGLContext()->functions()->glStencilFuncSeparate(GL_FRONT, std::get<0>(values), std::get<1>(values), std::get<2>(values)); - gc->openGLContext()->functions()->glStencilFuncSeparate(GL_BACK, std::get<3>(values), std::get<4>(values), std::get<5>(values)); -} - -template<> -void applyStateHelper(const AlphaCoverage *, SubmissionContext *gc) -{ - gc->setAlphaCoverageEnabled(true); -} - -template<> -void applyStateHelper(const PointSize *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->pointSize(std::get<0>(values), std::get<1>(values)); -} - - -template<> -void applyStateHelper(const PolygonOffset *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->openGLContext()->functions()->glEnable(GL_POLYGON_OFFSET_FILL); - gc->openGLContext()->functions()->glPolygonOffset(std::get<0>(values), std::get<1>(values)); -} - -template<> -void applyStateHelper(const ColorMask *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->openGLContext()->functions()->glColorMask(std::get<0>(values), std::get<1>(values), std::get<2>(values), std::get<3>(values)); -} - -template<> -void applyStateHelper(const ClipPlane *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->enableClipPlane(std::get<0>(values)); - gc->setClipPlane(std::get<0>(values), std::get<1>(values), std::get<2>(values)); -} - -template<> -void applyStateHelper(const SeamlessCubemap *, SubmissionContext *gc) -{ - gc->setSeamlessCubemap(true); -} - -template<> -void applyStateHelper(const StencilOp *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->openGLContext()->functions()->glStencilOpSeparate(GL_FRONT, std::get<0>(values), std::get<1>(values), std::get<2>(values)); - gc->openGLContext()->functions()->glStencilOpSeparate(GL_BACK, std::get<3>(values), std::get<4>(values), std::get<5>(values)); -} - -template<> -void applyStateHelper(const StencilMask *state, SubmissionContext *gc) -{ - const auto values = state->values(); - gc->openGLContext()->functions()->glStencilMaskSeparate(GL_FRONT, std::get<0>(values)); - gc->openGLContext()->functions()->glStencilMaskSeparate(GL_BACK, std::get<1>(values)); -} - -template<> -void applyStateHelper(const Dithering *, SubmissionContext *gc) -{ - gc->openGLContext()->functions()->glEnable(GL_DITHER); -} - -#ifndef GL_LINE_SMOOTH -#define GL_LINE_SMOOTH 0x0B20 -#endif - -template<> -void applyStateHelper(const LineWidth *state, SubmissionContext *gc) -{ - const auto values = state->values(); - if (std::get<1>(values)) - gc->openGLContext()->functions()->glEnable(GL_LINE_SMOOTH); - else - gc->openGLContext()->functions()->glDisable(GL_LINE_SMOOTH); - - gc->openGLContext()->functions()->glLineWidth(std::get<0>(values)); -} - -} // anonymous - - -SubmissionContext::SubmissionContext() - : GraphicsContext() - , m_ownCurrent(true) - , m_id(nextFreeContextId()) - , m_surface(nullptr) - , m_activeShader(nullptr) - , m_renderTargetFormat(QAbstractTexture::NoFormat) - , m_currClearStencilValue(0) - , m_currClearDepthValue(1.f) - , m_currClearColorValue(0,0,0,0) - , m_material(nullptr) - , m_activeFBO(0) - , m_boundArrayBuffer(nullptr) - , m_stateSet(nullptr) - , m_renderer(nullptr) - , m_uboTempArray(QByteArray(1024, 0)) -{ - static_contexts[m_id] = this; -} - -SubmissionContext::~SubmissionContext() -{ - releaseOpenGL(); - - Q_ASSERT(static_contexts[m_id] == this); - static_contexts.remove(m_id); -} - -void SubmissionContext::initialize() -{ - GraphicsContext::initialize(); - m_textureContext.initialize(this); - m_imageContext.initialize(this); -} - -void SubmissionContext::resolveRenderTargetFormat() -{ - const QSurfaceFormat format = m_gl->format(); - const uint a = (format.alphaBufferSize() == -1) ? 0 : format.alphaBufferSize(); - const uint r = format.redBufferSize(); - const uint g = format.greenBufferSize(); - const uint b = format.blueBufferSize(); - -#define RGBA_BITS(r,g,b,a) (r | (g << 6) | (b << 12) | (a << 18)) - - const uint bits = RGBA_BITS(r,g,b,a); - switch (bits) { - case RGBA_BITS(8,8,8,8): - m_renderTargetFormat = QAbstractTexture::RGBA8_UNorm; - break; - case RGBA_BITS(8,8,8,0): - m_renderTargetFormat = QAbstractTexture::RGB8_UNorm; - break; - case RGBA_BITS(5,6,5,0): - m_renderTargetFormat = QAbstractTexture::R5G6B5; - break; - } -#undef RGBA_BITS -} - -bool SubmissionContext::beginDrawing(QSurface *surface) -{ - Q_ASSERT(surface); - Q_ASSERT(m_gl); - - m_surface = surface; - - // TO DO: Find a way to make to pause work if the window is not exposed - // if (m_surface && m_surface->surfaceClass() == QSurface::Window) { - // qDebug() << Q_FUNC_INFO << 1; - // if (!static_cast(m_surface)->isExposed()) - // return false; - // qDebug() << Q_FUNC_INFO << 2; - // } - - // Makes the surface current on the OpenGLContext - // and sets the right glHelper - m_ownCurrent = !(m_gl->surface() == m_surface); - if (m_ownCurrent && !makeCurrent(m_surface)) - return false; - - // TODO: cache surface format somewhere rather than doing this every time render surface changes - resolveRenderTargetFormat(); - -#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) - GLint err = m_gl->functions()->glGetError(); - if (err != 0) { - qCWarning(Backend) << Q_FUNC_INFO << "glGetError:" << err; - } -#endif - - if (!isInitialized()) - initialize(); - initializeHelpers(m_surface); - - // need to reset these values every frame, may get overwritten elsewhere - m_gl->functions()->glClearColor(m_currClearColorValue.redF(), m_currClearColorValue.greenF(), m_currClearColorValue.blueF(), m_currClearColorValue.alphaF()); - m_gl->functions()->glClearDepthf(m_currClearDepthValue); - m_gl->functions()->glClearStencil(m_currClearStencilValue); - - if (m_activeShader) { - m_activeShader = nullptr; - } - - m_boundArrayBuffer = nullptr; - return true; -} - -void SubmissionContext::endDrawing(bool swapBuffers) -{ - if (swapBuffers) - m_gl->swapBuffers(m_surface); - if (m_ownCurrent) - m_gl->doneCurrent(); - m_textureContext.endDrawing(); - m_imageContext.endDrawing(); -} - -void SubmissionContext::activateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, GLuint defaultFboId) -{ - GLuint fboId = defaultFboId; // Default FBO - if (renderTargetNodeId) { - // New RenderTarget - if (!m_renderTargets.contains(renderTargetNodeId)) { - if (m_defaultFBO && fboId == m_defaultFBO) { - // this is the default fbo that some platforms create (iOS), we just register it - // Insert FBO into hash - m_renderTargets.insert(renderTargetNodeId, fboId); - } else { - fboId = createRenderTarget(renderTargetNodeId, attachments); - } - } else { - fboId = updateRenderTarget(renderTargetNodeId, attachments, true); - } - } - m_activeFBO = fboId; - m_glHelper->bindFrameBufferObject(m_activeFBO, GraphicsHelperInterface::FBODraw); - // Set active drawBuffers - activateDrawBuffers(attachments); -} - -GLuint SubmissionContext::createRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments) -{ - const GLuint fboId = m_glHelper->createFrameBufferObject(); - if (fboId) { - // The FBO is created and its attachments are set once - // Insert FBO into hash - m_renderTargets.insert(renderTargetNodeId, fboId); - // Bind FBO - m_glHelper->bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); - bindFrameBufferAttachmentHelper(fboId, attachments); - } else { - qCritical("Failed to create FBO"); - } - return fboId; -} - -GLuint SubmissionContext::updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, bool isActiveRenderTarget) -{ - const GLuint fboId = m_renderTargets.value(renderTargetNodeId); - - // We need to check if one of the attachment was resized - bool needsResize = !m_renderTargetsSize.contains(fboId); // not even initialized yet? - if (!needsResize) { - // render target exists, has attachment been resized? - GLTextureManager *glTextureManager = m_renderer->glResourceManagers()->glTextureManager(); - const QSize s = m_renderTargetsSize[fboId]; - const auto attachments_ = attachments.attachments(); - for (const Attachment &attachment : attachments_) { - GLTexture *rTex = glTextureManager->lookupResource(attachment.m_textureUuid); - // ### TODO QTBUG-64757 this check is insufficient since the - // texture may have changed to another one with the same size. That - // case is not handled atm. - if (rTex) { - needsResize |= rTex->size() != s; - if (isActiveRenderTarget && attachment.m_point == QRenderTargetOutput::Color0) - m_renderTargetFormat = rTex->properties().format; - } - } - } - - if (needsResize) { - m_glHelper->bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); - bindFrameBufferAttachmentHelper(fboId, attachments); - } - - return fboId; -} - -QSize SubmissionContext::renderTargetSize(const QSize &surfaceSize) const -{ - QSize renderTargetSize; - if (m_activeFBO != m_defaultFBO) { - // For external FBOs we may not have a m_renderTargets entry. - if (m_renderTargetsSize.contains(m_activeFBO)) { - renderTargetSize = m_renderTargetsSize[m_activeFBO]; - } else if (surfaceSize.isValid()) { - renderTargetSize = surfaceSize; - } else { - // External FBO (when used with QtQuick2 Scene3D) - - // Query FBO color attachment 0 size - GLint attachmentObjectType = GL_NONE; - GLint attachment0Name = 0; - m_gl->functions()->glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, - &attachmentObjectType); - m_gl->functions()->glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, - &attachment0Name); - - if (attachmentObjectType == GL_RENDERBUFFER && m_glHelper->supportsFeature(GraphicsHelperInterface::RenderBufferDimensionRetrieval)) - renderTargetSize = m_glHelper->getRenderBufferDimensions(attachment0Name); - else if (attachmentObjectType == GL_TEXTURE && m_glHelper->supportsFeature(GraphicsHelperInterface::TextureDimensionRetrieval)) - // Assumes texture level 0 and GL_TEXTURE_2D target - renderTargetSize = m_glHelper->getTextureDimensions(attachment0Name, GL_TEXTURE_2D); - else - return renderTargetSize; - } - } else { - renderTargetSize = m_surface->size(); - if (m_surface->surfaceClass() == QSurface::Window) { - const float dpr = static_cast(m_surface)->devicePixelRatio(); - renderTargetSize *= dpr; - } - } - return renderTargetSize; -} - -QImage SubmissionContext::readFramebuffer(const QRect &rect) -{ - QImage img; - const unsigned int area = rect.width() * rect.height(); - unsigned int bytes; - GLenum format, type; - QImage::Format imageFormat; - uint stride; - - /* format value should match GL internalFormat */ - GLenum internalFormat = m_renderTargetFormat; - - switch (m_renderTargetFormat) { - case QAbstractTexture::RGBAFormat: - case QAbstractTexture::RGBA8_SNorm: - case QAbstractTexture::RGBA8_UNorm: - case QAbstractTexture::RGBA8U: - case QAbstractTexture::SRGB8_Alpha8: -#ifdef QT_OPENGL_ES_2 - format = GL_RGBA; - imageFormat = QImage::Format_RGBA8888_Premultiplied; -#else - format = GL_BGRA; - imageFormat = QImage::Format_ARGB32_Premultiplied; - internalFormat = GL_RGBA8; -#endif - type = GL_UNSIGNED_BYTE; - bytes = area * 4; - stride = rect.width() * 4; - break; - case QAbstractTexture::SRGB8: - case QAbstractTexture::RGBFormat: - case QAbstractTexture::RGB8U: - case QAbstractTexture::RGB8_UNorm: -#ifdef QT_OPENGL_ES_2 - format = GL_RGBA; - imageFormat = QImage::Format_RGBX8888; -#else - format = GL_BGRA; - imageFormat = QImage::Format_RGB32; - internalFormat = GL_RGB8; -#endif - type = GL_UNSIGNED_BYTE; - bytes = area * 4; - stride = rect.width() * 4; - break; -#ifndef QT_OPENGL_ES_2 - case QAbstractTexture::RG11B10F: - bytes = area * 4; - format = GL_RGB; - type = GL_UNSIGNED_INT_10F_11F_11F_REV; - imageFormat = QImage::Format_RGB30; - stride = rect.width() * 4; - break; - case QAbstractTexture::RGB10A2: - bytes = area * 4; - format = GL_RGBA; - type = GL_UNSIGNED_INT_2_10_10_10_REV; - imageFormat = QImage::Format_A2BGR30_Premultiplied; - stride = rect.width() * 4; - break; - case QAbstractTexture::R5G6B5: - bytes = area * 2; - format = GL_RGB; - type = GL_UNSIGNED_SHORT; - internalFormat = GL_UNSIGNED_SHORT_5_6_5_REV; - imageFormat = QImage::Format_RGB16; - stride = rect.width() * 2; - break; - case QAbstractTexture::RGBA16F: - case QAbstractTexture::RGBA16U: - case QAbstractTexture::RGBA32F: - case QAbstractTexture::RGBA32U: - bytes = area * 16; - format = GL_RGBA; - type = GL_FLOAT; - imageFormat = QImage::Format_ARGB32_Premultiplied; - stride = rect.width() * 16; - break; -#endif - default: - auto warning = qWarning(); - warning << "Unable to convert"; - QtDebugUtils::formatQEnum(warning, m_renderTargetFormat); - warning << "render target texture format to QImage."; - return img; - } - - GLint samples = 0; - m_gl->functions()->glGetIntegerv(GL_SAMPLES, &samples); - if (samples > 0 && !m_glHelper->supportsFeature(GraphicsHelperInterface::BlitFramebuffer)) { - qCWarning(Backend) << Q_FUNC_INFO << "Unable to capture multisampled framebuffer; " - "Required feature BlitFramebuffer is missing."; - return img; - } - - img = QImage(rect.width(), rect.height(), imageFormat); - - QScopedArrayPointer data(new uchar [bytes]); - - if (samples > 0) { - // resolve multisample-framebuffer to renderbuffer and read pixels from it - GLuint fbo, rb; - QOpenGLFunctions *gl = m_gl->functions(); - gl->glGenFramebuffers(1, &fbo); - gl->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); - gl->glGenRenderbuffers(1, &rb); - gl->glBindRenderbuffer(GL_RENDERBUFFER, rb); - gl->glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, rect.width(), rect.height()); - gl->glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb); - - const GLenum status = gl->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - if (status != GL_FRAMEBUFFER_COMPLETE) { - gl->glDeleteRenderbuffers(1, &rb); - gl->glDeleteFramebuffers(1, &fbo); - qCWarning(Backend) << Q_FUNC_INFO << "Copy-framebuffer not complete: " << status; - return img; - } - - m_glHelper->blitFramebuffer(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height(), - 0, 0, rect.width(), rect.height(), - GL_COLOR_BUFFER_BIT, GL_NEAREST); - gl->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); - gl->glReadPixels(0,0,rect.width(), rect.height(), format, type, data.data()); - - copyGLFramebufferDataToImage(img, data.data(), stride, rect.width(), rect.height(), m_renderTargetFormat); - - gl->glBindRenderbuffer(GL_RENDERBUFFER, rb); - gl->glDeleteRenderbuffers(1, &rb); - gl->glBindFramebuffer(GL_FRAMEBUFFER, m_activeFBO); - gl->glDeleteFramebuffers(1, &fbo); - } else { - // read pixels directly from framebuffer - m_gl->functions()->glReadPixels(rect.x(), rect.y(), rect.width(), rect.height(), format, type, data.data()); - copyGLFramebufferDataToImage(img, data.data(), stride, rect.width(), rect.height(), m_renderTargetFormat); - } - - return img; -} - -void SubmissionContext::setViewport(const QRectF &viewport, const QSize &surfaceSize) -{ - // // save for later use; this has nothing to do with the viewport but it is - // // here that we get to know the surfaceSize from the RenderView. - m_surfaceSize = surfaceSize; - - m_viewport = viewport; - QSize size = renderTargetSize(surfaceSize); - - // Check that the returned size is before calling glViewport - if (size.isEmpty()) - return; - - // Qt3D 0------------------> 1 OpenGL 1^ - // | | - // | | - // | | - // V | - // 1 0---------------------> 1 - // The Viewport is defined between 0 and 1 which allows us to automatically - // scale to the size of the provided window surface - m_gl->functions()->glViewport(m_viewport.x() * size.width(), - (1.0 - m_viewport.y() - m_viewport.height()) * size.height(), - m_viewport.width() * size.width(), - m_viewport.height() * size.height()); -} - -void SubmissionContext::releaseOpenGL() -{ - m_renderBufferHash.clear(); - - // Stop and destroy the OpenGL logger - if (m_debugLogger) { - m_debugLogger->stopLogging(); - m_debugLogger.reset(nullptr); - } -} - -// The OpenGLContext is not current on any surface at this point -void SubmissionContext::setOpenGLContext(QOpenGLContext* ctx) -{ - Q_ASSERT(ctx); - - releaseOpenGL(); - m_gl = ctx; -} - -// Called only from RenderThread -bool SubmissionContext::activateShader(GLShader *shader) -{ - if (shader->shaderProgram() != m_activeShader) { - // Ensure material uniforms are re-applied - m_material = nullptr; - - m_activeShader = shader->shaderProgram(); - if (Q_LIKELY(m_activeShader != nullptr)) { - m_activeShader->bind(); - } else { - m_glHelper->useProgram(0); - qWarning() << "No shader program found"; - return false; - } - } - return true; -} - -void SubmissionContext::bindFrameBufferAttachmentHelper(GLuint fboId, const AttachmentPack &attachments) -{ - // Set FBO attachments. These are normally textures, except that on Open GL - // ES <= 3.1 we must use a renderbuffer if a combined depth+stencil is - // desired since this cannot be achieved neither with a single texture (not - // before GLES 3.2) nor with separate textures (no suitable format for - // stencil before 3.1 with the appropriate extension). - - QSize fboSize; - GLTextureManager *glTextureManager = m_renderer->glResourceManagers()->glTextureManager(); - const auto attachments_ = attachments.attachments(); - for (const Attachment &attachment : attachments_) { - GLTexture *rTex = glTextureManager->lookupResource(attachment.m_textureUuid); - if (!m_glHelper->frameBufferNeedsRenderBuffer(attachment)) { - QOpenGLTexture *glTex = rTex ? rTex->getGLTexture() : nullptr; - if (glTex != nullptr) { - // The texture can not be rendered simultaniously by another renderer - Q_ASSERT(!rTex->isExternalRenderingEnabled()); - if (fboSize.isEmpty()) - fboSize = QSize(glTex->width(), glTex->height()); - else - fboSize = QSize(qMin(fboSize.width(), glTex->width()), qMin(fboSize.height(), glTex->height())); - m_glHelper->bindFrameBufferAttachment(glTex, attachment); - } - } else { - RenderBuffer *renderBuffer = rTex ? rTex->getOrCreateRenderBuffer() : nullptr; - if (renderBuffer) { - if (fboSize.isEmpty()) - fboSize = QSize(renderBuffer->width(), renderBuffer->height()); - else - fboSize = QSize(qMin(fboSize.width(), renderBuffer->width()), qMin(fboSize.height(), renderBuffer->height())); - m_glHelper->bindFrameBufferAttachment(renderBuffer, attachment); - } - } - } - m_renderTargetsSize.insert(fboId, fboSize); -} - -void SubmissionContext::activateDrawBuffers(const AttachmentPack &attachments) -{ - const QVector activeDrawBuffers = attachments.getGlDrawBuffers(); - - if (m_glHelper->checkFrameBufferComplete()) { - if (activeDrawBuffers.size() > 1) {// We need MRT - if (m_glHelper->supportsFeature(GraphicsHelperInterface::MRT)) { - // Set up MRT, glDrawBuffers... - m_glHelper->drawBuffers(activeDrawBuffers.size(), activeDrawBuffers.data()); - } - } - } else { - qCWarning(Backend) << "FBO incomplete"; - } -} - - -void SubmissionContext::setActiveMaterial(Material *rmat) -{ - if (m_material == rmat) - return; - - m_textureContext.deactivateTexturesWithScope(TextureSubmissionContext::TextureScopeMaterial); - m_imageContext.deactivateImages(); - m_material = rmat; -} - -void SubmissionContext::setCurrentStateSet(RenderStateSet *ss) -{ - if (ss == m_stateSet) - return; - if (ss) - applyStateSet(ss); - m_stateSet = ss; -} - -RenderStateSet *SubmissionContext::currentStateSet() const -{ - return m_stateSet; -} - -void SubmissionContext::applyState(const StateVariant &stateVariant) -{ - switch (stateVariant.type) { - - case AlphaCoverageStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - case AlphaTestMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - case BlendStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - case BlendEquationArgumentsMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - case MSAAEnabledStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case CullFaceStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case DepthWriteStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case DepthTestStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case DepthRangeMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case RasterModeMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case FrontFaceStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case ScissorStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case StencilTestStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case PointSizeMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case PolygonOffsetStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case ColorStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case ClipPlaneMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case SeamlessCubemapMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case StencilOpMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case StencilWriteStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case DitheringStateMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - - case LineWidthMask: { - applyStateHelper(static_cast(stateVariant.constState()), this); - break; - } - default: - Q_UNREACHABLE(); - } -} - -void SubmissionContext::resetMasked(qint64 maskOfStatesToReset) -{ - // TO DO -> Call gcHelper methods instead of raw GL - // QOpenGLFunctions shouldn't be used here directly - QOpenGLFunctions *funcs = m_gl->functions(); - - if (maskOfStatesToReset & ScissorStateMask) - funcs->glDisable(GL_SCISSOR_TEST); - - if (maskOfStatesToReset & BlendStateMask) - funcs->glDisable(GL_BLEND); - - if (maskOfStatesToReset & StencilWriteStateMask) - funcs->glStencilMask(0); - - if (maskOfStatesToReset & StencilTestStateMask) - funcs->glDisable(GL_STENCIL_TEST); - - if (maskOfStatesToReset & DepthRangeMask) - depthRange(0.0f, 1.0f); - - if (maskOfStatesToReset & DepthTestStateMask) - funcs->glDisable(GL_DEPTH_TEST); - - if (maskOfStatesToReset & DepthWriteStateMask) - funcs->glDepthMask(GL_TRUE); // reset to default - - if (maskOfStatesToReset & FrontFaceStateMask) - funcs->glFrontFace(GL_CCW); // reset to default - - if (maskOfStatesToReset & CullFaceStateMask) - funcs->glDisable(GL_CULL_FACE); - - if (maskOfStatesToReset & DitheringStateMask) - funcs->glDisable(GL_DITHER); - - if (maskOfStatesToReset & AlphaCoverageStateMask) - setAlphaCoverageEnabled(false); - - if (maskOfStatesToReset & PointSizeMask) - pointSize(false, 1.0f); // reset to default - - if (maskOfStatesToReset & PolygonOffsetStateMask) - funcs->glDisable(GL_POLYGON_OFFSET_FILL); - - if (maskOfStatesToReset & ColorStateMask) - funcs->glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - - if (maskOfStatesToReset & ClipPlaneMask) { - GLint max = maxClipPlaneCount(); - for (GLint i = 0; i < max; ++i) - disableClipPlane(i); - } - - if (maskOfStatesToReset & SeamlessCubemapMask) - setSeamlessCubemap(false); - - if (maskOfStatesToReset & StencilOpMask) - funcs->glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); - - if (maskOfStatesToReset & LineWidthMask) - funcs->glLineWidth(1.0f); - -#ifndef QT_OPENGL_ES_2 - if (maskOfStatesToReset & RasterModeMask) - m_glHelper->rasterMode(GL_FRONT_AND_BACK, GL_FILL); -#endif -} - -void SubmissionContext::applyStateSet(RenderStateSet *ss) -{ - RenderStateSet* previousStates = currentStateSet(); - - const StateMaskSet invOurState = ~ss->stateMask(); - // generate a mask for each set bit in previous, where we do not have - // the corresponding bit set. - - StateMaskSet stateToReset = 0; - if (previousStates) { - stateToReset = previousStates->stateMask() & invOurState; - qCDebug(RenderStates) << "previous states " << QString::number(previousStates->stateMask(), 2); - } - qCDebug(RenderStates) << " current states " << QString::number(ss->stateMask(), 2) << "inverse " << QString::number(invOurState, 2) << " -> states to change: " << QString::number(stateToReset, 2); - - // Reset states that aren't active in the current state set - resetMasked(stateToReset); - - // Apply states that weren't in the previous state or that have - // different values - const QVector statesToSet = ss->states(); - for (const StateVariant &ds : statesToSet) { - if (previousStates && previousStates->contains(ds)) - continue; - applyState(ds); - } -} - -void SubmissionContext::clearColor(const QColor &color) -{ - if (m_currClearColorValue != color) { - m_currClearColorValue = color; - m_gl->functions()->glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); - } -} - -void SubmissionContext::clearDepthValue(float depth) -{ - if (m_currClearDepthValue != depth) { - m_currClearDepthValue = depth; - m_gl->functions()->glClearDepthf(depth); - } -} - -void SubmissionContext::clearStencilValue(int stencil) -{ - if (m_currClearStencilValue != stencil) { - m_currClearStencilValue = stencil; - m_gl->functions()->glClearStencil(stencil); - } -} - -GLFence SubmissionContext::fenceSync() -{ - return m_glHelper->fenceSync(); -} - -void SubmissionContext::clientWaitSync(GLFence sync, GLuint64 nanoSecTimeout) -{ - qDebug() << Q_FUNC_INFO << sync; - m_glHelper->clientWaitSync(sync, nanoSecTimeout); -} - -void SubmissionContext::waitSync(GLFence sync) -{ - qDebug() << Q_FUNC_INFO << sync; - m_glHelper->waitSync(sync); -} - -bool SubmissionContext::wasSyncSignaled(GLFence sync) -{ - return m_glHelper->wasSyncSignaled(sync); -} - -void SubmissionContext::deleteSync(GLFence sync) -{ - m_glHelper->deleteSync(sync); -} - -// It will be easier if the QGraphicContext applies the QUniformPack -// than the other way around -bool SubmissionContext::setParameters(ShaderParameterPack ¶meterPack) -{ - static const int irradianceId = StringToInt::lookupId(QLatin1String("envLight.irradiance")); - static const int specularId = StringToInt::lookupId(QLatin1String("envLight.specular")); - // Activate textures and update TextureUniform in the pack - // with the correct textureUnit - - // Set the pinned texture of the previous material texture - // to pinable so that we should easily find an available texture unit - m_textureContext.deactivateTexturesWithScope(TextureSubmissionContext::TextureScopeMaterial); - // Update the uniforms with the correct texture unit id's - PackUniformHash &uniformValues = parameterPack.uniforms(); - - // Fill Texture Uniform Value with proper texture units - // so that they can be applied as regular uniforms in a second step - for (int i = 0; i < parameterPack.textures().size(); ++i) { - const ShaderParameterPack::NamedResource &namedTex = parameterPack.textures().at(i); - // Given a Texture QNodeId, we retrieve the associated shared GLTexture - if (uniformValues.contains(namedTex.glslNameId)) { - GLTexture *t = m_renderer->glResourceManagers()->glTextureManager()->lookupResource(namedTex.nodeId); - if (t != nullptr) { - UniformValue &texUniform = uniformValues.value(namedTex.glslNameId); - if (texUniform.valueType() == UniformValue::TextureValue) { - const int texUnit = m_textureContext.activateTexture(TextureSubmissionContext::TextureScopeMaterial, m_gl, t); - texUniform.data()[namedTex.uniformArrayIndex] = texUnit; - if (texUnit == -1) { - if (namedTex.glslNameId != irradianceId && - namedTex.glslNameId != specularId) { - // Only return false if we are not dealing with env light textures - qCWarning(Backend) << "Unable to find suitable Texture Unit"; - return false; - } - } - } - } - } - } - - // Fill Image Uniform Value with proper image units - // so that they can be applied as regular uniforms in a second step - for (int i = 0; i < parameterPack.images().size(); ++i) { - const ShaderParameterPack::NamedResource &namedTex = parameterPack.images().at(i); - // Given a Texture QNodeId, we retrieve the associated shared GLTexture - if (uniformValues.contains(namedTex.glslNameId)) { - ShaderImage *img = m_renderer->nodeManagers()->shaderImageManager()->lookupResource(namedTex.nodeId); - if (img != nullptr) { - GLTexture *t = m_renderer->glResourceManagers()->glTextureManager()->lookupResource(img->textureId()); - if (t == nullptr) { - qCWarning(Backend) << "Shader Image referencing invalid texture"; - continue; - } else { - UniformValue &imgUniform = uniformValues.value(namedTex.glslNameId); - if (imgUniform.valueType() == UniformValue::ShaderImageValue) { - const int imgUnit = m_imageContext.activateImage(img, t); - imgUniform.data()[namedTex.uniformArrayIndex] = imgUnit; - if (imgUnit == -1) { - qCWarning(Backend) << "Unable to bind Image to Texture"; - return false; - } - } - } - } - } - } - - QOpenGLShaderProgram *shader = activeShader(); - - // TO DO: We could cache the binding points somehow and only do the binding when necessary - // for SSBO and UBO - - // Bind Shader Storage block to SSBO and update SSBO - const QVector blockToSSBOs = parameterPack.shaderStorageBuffers(); - for (const BlockToSSBO b : blockToSSBOs) { - Buffer *cpuBuffer = m_renderer->nodeManagers()->bufferManager()->lookupResource(b.m_bufferID); - GLBuffer *ssbo = glBufferForRenderBuffer(cpuBuffer); - // bindShaderStorageBlock - // This is currently not required as we are introspecting the bindingIndex - // value from the shaders and not replacing them, making such a call useless - // bindShaderStorageBlock(shader->programId(), b.m_blockIndex, b.m_bindingIndex); - bindShaderStorageBlock(shader->programId(), b.m_blockIndex, b.m_bindingIndex); - // Needed to avoid conflict where the buffer would already - // be bound as a VertexArray - bindGLBuffer(ssbo, GLBuffer::ShaderStorageBuffer); - ssbo->bindBufferBase(this, b.m_bindingIndex, GLBuffer::ShaderStorageBuffer); - // TO DO: Make sure that there's enough binding points - } - - // Bind UniformBlocks to UBO and update UBO from Buffer - // TO DO: Convert ShaderData to Buffer so that we can use that generic process - const QVector blockToUBOs = parameterPack.uniformBuffers(); - int uboIndex = 0; - for (const BlockToUBO &b : blockToUBOs) { - Buffer *cpuBuffer = m_renderer->nodeManagers()->bufferManager()->lookupResource(b.m_bufferID); - GLBuffer *ubo = glBufferForRenderBuffer(cpuBuffer); - bindUniformBlock(shader->programId(), b.m_blockIndex, uboIndex); - // Needed to avoid conflict where the buffer would already - // be bound as a VertexArray - bindGLBuffer(ubo, GLBuffer::UniformBuffer); - ubo->bindBufferBase(this, uboIndex++, GLBuffer::UniformBuffer); - // TO DO: Make sure that there's enough binding points - } - - // Update uniforms in the Default Uniform Block - const PackUniformHash values = parameterPack.uniforms(); - const QVector activeUniforms = parameterPack.submissionUniforms(); - - for (const ShaderUniform &uniform : activeUniforms) { - // We can use [] as we are sure the the uniform wouldn't - // be un activeUniforms if there wasn't a matching value - const UniformValue &v = values.value(uniform.m_nameId); - - // skip invalid textures/images - if ((v.valueType() == UniformValue::TextureValue || - v.valueType() == UniformValue::ShaderImageValue) && - *v.constData() == -1) - continue; - - applyUniform(uniform, v); - } - // if not all data is valid, the next frame will be rendered immediately - return true; -} - -void SubmissionContext::enableAttribute(const VAOVertexAttribute &attr) -{ - // Bind buffer within the current VAO - GLBuffer *buf = m_renderer->glResourceManagers()->glBufferManager()->data(attr.bufferHandle); - Q_ASSERT(buf); - bindGLBuffer(buf, attr.attributeType); - - // Don't use QOpenGLShaderProgram::setAttributeBuffer() because of QTBUG-43199. - // Use the introspection data and set the attribute explicitly - m_glHelper->enableVertexAttributeArray(attr.location); - m_glHelper->vertexAttributePointer(attr.shaderDataType, - attr.location, - attr.vertexSize, - attr.dataType, - GL_TRUE, // TODO: Support normalization property on QAttribute - attr.byteStride, - reinterpret_cast(qintptr(attr.byteOffset))); - - - // Done by the helper if it supports it - if (attr.divisor != 0) - m_glHelper->vertexAttribDivisor(attr.location, attr.divisor); -} - -void SubmissionContext::disableAttribute(const SubmissionContext::VAOVertexAttribute &attr) -{ - QOpenGLShaderProgram *prog = activeShader(); - prog->disableAttributeArray(attr.location); -} - -// Note: needs to be called while VAO is bound -void SubmissionContext::specifyAttribute(const Attribute *attribute, - Buffer *buffer, - const ShaderAttribute *attributeDescription) -{ - const int location = attributeDescription->m_location; - if (location < 0) { - qCWarning(Backend) << "failed to resolve location for attribute:" << attribute->name(); - return; - } - - const GLint attributeDataType = glDataTypeFromAttributeDataType(attribute->vertexBaseType()); - const HGLBuffer glBufferHandle = m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); - Q_ASSERT(!glBufferHandle.isNull()); - const GLBuffer::Type attributeType = attributeTypeToGLBufferType(attribute->attributeType()); - - int typeSize = 0; - int attrCount = 0; - - if (attribute->vertexSize() >= 1 && attribute->vertexSize() <= 4) { - attrCount = 1; - } else if (attribute->vertexSize() == 9) { - typeSize = byteSizeFromType(attributeDataType); - attrCount = 3; - } else if (attribute->vertexSize() == 16) { - typeSize = byteSizeFromType(attributeDataType); - attrCount = 4; - } else { - Q_UNREACHABLE(); - } - - Q_ASSERT(!glBufferHandle.isNull()); - VAOVertexAttribute attr; - attr.bufferHandle = glBufferHandle; - attr.attributeType = attributeType; - attr.dataType = attributeDataType; - attr.divisor = attribute->divisor(); - attr.vertexSize = attribute->vertexSize() / attrCount; - attr.byteStride = (attribute->byteStride() != 0) ? attribute->byteStride() : (attrCount * attrCount * typeSize); - attr.shaderDataType = attributeDescription->m_type; - - for (int i = 0; i < attrCount; i++) { - attr.location = location + i; - attr.byteOffset = attribute->byteOffset() + (i * attrCount * typeSize); - - enableAttribute(attr); - - // Save this in the current emulated VAO - if (m_currentVAO) - m_currentVAO->saveVertexAttribute(attr); - } -} - -void SubmissionContext::specifyIndices(Buffer *buffer) -{ - GLBuffer *buf = glBufferForRenderBuffer(buffer); - if (!bindGLBuffer(buf, GLBuffer::IndexBuffer)) - qCWarning(Backend) << Q_FUNC_INFO << "binding index buffer failed"; - - // bound within the current VAO - // Save this in the current emulated VAO - if (m_currentVAO) - m_currentVAO->saveIndexAttribute(m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId())); -} - -void SubmissionContext::updateBuffer(Buffer *buffer) -{ - const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); - if (it != m_renderBufferHash.end()) - uploadDataToGLBuffer(buffer, m_renderer->glResourceManagers()->glBufferManager()->data(it.value())); -} - -QByteArray SubmissionContext::downloadBufferContent(Buffer *buffer) -{ - const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); - if (it != m_renderBufferHash.end()) - return downloadDataFromGLBuffer(buffer, m_renderer->glResourceManagers()->glBufferManager()->data(it.value())); - return QByteArray(); -} - -void SubmissionContext::releaseBuffer(Qt3DCore::QNodeId bufferId) -{ - auto it = m_renderBufferHash.find(bufferId); - if (it != m_renderBufferHash.end()) { - HGLBuffer glBuffHandle = it.value(); - GLBuffer *glBuff = m_renderer->glResourceManagers()->glBufferManager()->data(glBuffHandle); - - Q_ASSERT(glBuff); - // Destroy the GPU resource - glBuff->destroy(this); - // Destroy the GLBuffer instance - m_renderer->glResourceManagers()->glBufferManager()->releaseResource(bufferId); - // Remove Id - HGLBuffer entry - m_renderBufferHash.erase(it); - } -} - -bool SubmissionContext::hasGLBufferForBuffer(Buffer *buffer) -{ - const QHash::iterator it = m_renderBufferHash.find(buffer->peerId()); - return (it != m_renderBufferHash.end()); -} - -GLBuffer *SubmissionContext::glBufferForRenderBuffer(Buffer *buf) -{ - if (!m_renderBufferHash.contains(buf->peerId())) - m_renderBufferHash.insert(buf->peerId(), createGLBufferFor(buf)); - return m_renderer->glResourceManagers()->glBufferManager()->data(m_renderBufferHash.value(buf->peerId())); -} - -HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer) -{ - GLBuffer *b = m_renderer->glResourceManagers()->glBufferManager()->getOrCreateResource(buffer->peerId()); - // b.setUsagePattern(static_cast(buffer->usage())); - Q_ASSERT(b); - if (!b->create(this)) - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer creation failed"; - - return m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); -} - -bool SubmissionContext::bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type) -{ - if (type == GLBuffer::ArrayBuffer && buffer == m_boundArrayBuffer) - return true; - - if (buffer->bind(this, type)) { - if (type == GLBuffer::ArrayBuffer) - m_boundArrayBuffer = buffer; - return true; - } - return false; -} - -void SubmissionContext::uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool releaseBuffer) -{ - if (!bindGLBuffer(b, GLBuffer::ArrayBuffer)) // We're uploading, the type doesn't matter here - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer bind failed"; - // If the buffer is dirty (hence being called here) - // there are two possible cases - // * setData was called changing the whole data or functor (or the usage pattern) - // * partial buffer updates where received - - // TO DO: Handle usage pattern - QVector updates = std::move(buffer->pendingBufferUpdates()); - for (auto it = updates.begin(); it != updates.end(); ++it) { - auto update = it; - // We have a partial update - if (update->offset >= 0) { - //accumulate sequential updates as single one - int bufferSize = update->data.size(); - auto it2 = it + 1; - while ((it2 != updates.end()) - && (it2->offset - update->offset == bufferSize)) { - bufferSize += it2->data.size(); - ++it2; - } - update->data.resize(bufferSize); - while (it + 1 != it2) { - ++it; - update->data.replace(it->offset - update->offset, it->data.size(), it->data); - it->data.clear(); - } - // TO DO: based on the number of updates .., it might make sense to - // sometime use glMapBuffer rather than glBufferSubData - b->update(this, update->data.constData(), update->data.size(), update->offset); - } else { - // We have an update that was done by calling QBuffer::setData - // which is used to resize or entirely clear the buffer - // Note: we use the buffer data directly in that case - const int bufferSize = buffer->data().size(); - b->allocate(this, bufferSize, false); // orphan the buffer - b->allocate(this, buffer->data().constData(), bufferSize, false); - } - } - - if (releaseBuffer) { - b->release(this); - m_boundArrayBuffer = nullptr; - } - qCDebug(Render::Io) << "uploaded buffer size=" << buffer->data().size(); -} - -QByteArray SubmissionContext::downloadDataFromGLBuffer(Buffer *buffer, GLBuffer *b) -{ - if (!bindGLBuffer(b, GLBuffer::ArrayBuffer)) // We're downloading, the type doesn't matter here - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer bind failed"; - - QByteArray data = b->download(this, buffer->data().size()); - return data; -} - -void SubmissionContext::blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId, - Qt3DCore::QNodeId outputRenderTargetId, - QRect inputRect, QRect outputRect, - uint defaultFboId, - QRenderTargetOutput::AttachmentPoint inputAttachmentPoint, - QRenderTargetOutput::AttachmentPoint outputAttachmentPoint, - QBlitFramebuffer::InterpolationMethod interpolationMethod) -{ - GLuint inputFboId = defaultFboId; - bool inputBufferIsDefault = true; - if (!inputRenderTargetId.isNull()) { - RenderTarget *renderTarget = m_renderer->nodeManagers()->renderTargetManager()->lookupResource(inputRenderTargetId); - if (renderTarget) { - AttachmentPack attachments(renderTarget, m_renderer->nodeManagers()->attachmentManager()); - if (m_renderTargets.contains(inputRenderTargetId)) - inputFboId = updateRenderTarget(inputRenderTargetId, attachments, false); - else - inputFboId = createRenderTarget(inputRenderTargetId, attachments); - } - inputBufferIsDefault = false; - } - - GLuint outputFboId = defaultFboId; - bool outputBufferIsDefault = true; - if (!outputRenderTargetId.isNull()) { - RenderTarget *renderTarget = m_renderer->nodeManagers()->renderTargetManager()->lookupResource(outputRenderTargetId); - if (renderTarget) { - AttachmentPack attachments(renderTarget, m_renderer->nodeManagers()->attachmentManager()); - if (m_renderTargets.contains(outputRenderTargetId)) - outputFboId = updateRenderTarget(outputRenderTargetId, attachments, false); - else - outputFboId = createRenderTarget(outputRenderTargetId, attachments); - } - outputBufferIsDefault = false; - } - - // Up until this point the input and output rects are normal Qt rectangles. - // Convert them to GL rectangles (Y at bottom). - const int inputFboHeight = inputFboId == defaultFboId ? m_surfaceSize.height() : m_renderTargetsSize[inputFboId].height(); - const GLint srcX0 = inputRect.left(); - const GLint srcY0 = inputFboHeight - (inputRect.top() + inputRect.height()); - const GLint srcX1 = srcX0 + inputRect.width(); - const GLint srcY1 = srcY0 + inputRect.height(); - - const int outputFboHeight = outputFboId == defaultFboId ? m_surfaceSize.height() : m_renderTargetsSize[outputFboId].height(); - const GLint dstX0 = outputRect.left(); - const GLint dstY0 = outputFboHeight - (outputRect.top() + outputRect.height()); - const GLint dstX1 = dstX0 + outputRect.width(); - const GLint dstY1 = dstY0 + outputRect.height(); - - //Get the last bounded framebuffers - const GLuint lastDrawFboId = boundFrameBufferObject(); - - // Activate input framebuffer for reading - bindFramebuffer(inputFboId, GraphicsHelperInterface::FBORead); - - // Activate output framebuffer for writing - bindFramebuffer(outputFboId, GraphicsHelperInterface::FBODraw); - - //Bind texture - if (!inputBufferIsDefault) - readBuffer(GL_COLOR_ATTACHMENT0 + inputAttachmentPoint); - - if (!outputBufferIsDefault) { - // Note that we use glDrawBuffers, not glDrawBuffer. The - // latter is not available with GLES. - const int buf = outputAttachmentPoint; - drawBuffers(1, &buf); - } - - // Blit framebuffer - const GLenum mode = interpolationMethod ? GL_NEAREST : GL_LINEAR; - m_glHelper->blitFramebuffer(srcX0, srcY0, srcX1, srcY1, - dstX0, dstY0, dstX1, dstY1, - GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT, - mode); - - // Reset draw buffer - bindFramebuffer(lastDrawFboId, GraphicsHelperInterface::FBOReadAndDraw); - if (outputAttachmentPoint != QRenderTargetOutput::Color0) { - const int buf = QRenderTargetOutput::Color0; - drawBuffers(1, &buf); - } -} - -} // namespace Render -} // namespace Qt3DRender of namespace - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h b/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h deleted file mode 100644 index e7a31e6ce..000000000 --- a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h +++ /dev/null @@ -1,234 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H -#define QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - - -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QAbstractOpenGLFunctions; - -namespace Qt3DRender { - -namespace Render { - -class Renderer; -class GraphicsHelperInterface; -class RenderStateSet; -class Material; -class GLTexture; -class RenderCommand; -class RenderTarget; -class AttachmentPack; -class Attribute; -class Buffer; -class ShaderManager; -struct StateVariant; - -typedef QPair NamedUniformLocation; - -class Q_AUTOTEST_EXPORT SubmissionContext : public GraphicsContext -{ -public: - SubmissionContext(); - ~SubmissionContext(); - - int id() const; // unique, small integer ID of this context - void setRenderer(Renderer *renderer) { m_renderer = renderer; } - - bool beginDrawing(QSurface *surface); - void endDrawing(bool swapBuffers); - void releaseOpenGL(); - void setOpenGLContext(QOpenGLContext* ctx); - - // Viewport - void setViewport(const QRectF &viewport, const QSize &surfaceSize); - QRectF viewport() const { return m_viewport; } - - // Shaders - bool activateShader(GLShader *shader); - QOpenGLShaderProgram *activeShader() const { return m_activeShader; } - - // FBO - GLuint activeFBO() const { return m_activeFBO; } - void activateRenderTarget(const Qt3DCore::QNodeId id, const AttachmentPack &attachments, GLuint defaultFboId); - QSize renderTargetSize(const QSize &surfaceSize) const; - QImage readFramebuffer(const QRect &rect); - void blitFramebuffer(Qt3DCore::QNodeId outputRenderTargetId, Qt3DCore::QNodeId inputRenderTargetId, - QRect inputRect, - QRect outputRect, uint defaultFboId, - QRenderTargetOutput::AttachmentPoint inputAttachmentPoint, - QRenderTargetOutput::AttachmentPoint outputAttachmentPoint, - QBlitFramebuffer::InterpolationMethod interpolationMethod); - - // Attributes - void specifyAttribute(const Attribute *attribute, - Buffer *buffer, - const ShaderAttribute *attributeDescription); - void specifyIndices(Buffer *buffer); - - // Buffer - void updateBuffer(Buffer *buffer); - QByteArray downloadBufferContent(Buffer *buffer); - void releaseBuffer(Qt3DCore::QNodeId bufferId); - bool hasGLBufferForBuffer(Buffer *buffer); - GLBuffer *glBufferForRenderBuffer(Buffer *buf); - - // Parameters - bool setParameters(ShaderParameterPack ¶meterPack); - - // RenderState - void setCurrentStateSet(RenderStateSet* ss); - RenderStateSet *currentStateSet() const; - void applyState(const StateVariant &state); - - void resetMasked(qint64 maskOfStatesToReset); - void applyStateSet(RenderStateSet *ss); - - // Wrappers - void clearColor(const QColor &color); - void clearDepthValue(float depth); - void clearStencilValue(int stencil); - - - // Fences - GLFence fenceSync(); - void clientWaitSync(GLFence sync, GLuint64 nanoSecTimeout); - void waitSync(GLFence sync); - bool wasSyncSignaled(GLFence sync); - void deleteSync(GLFence sync); - -private: - void initialize(); - - // Material - Material* activeMaterial() const { return m_material; } - void setActiveMaterial(Material* rmat); - - // FBO - void bindFrameBufferAttachmentHelper(GLuint fboId, const AttachmentPack &attachments); - void activateDrawBuffers(const AttachmentPack &attachments); - void resolveRenderTargetFormat(); - GLuint createRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments); - GLuint updateRenderTarget(Qt3DCore::QNodeId renderTargetNodeId, const AttachmentPack &attachments, bool isActiveRenderTarget); - - // Buffers - HGLBuffer createGLBufferFor(Buffer *buffer); - void uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool releaseBuffer = false); - QByteArray downloadDataFromGLBuffer(Buffer *buffer, GLBuffer *b); - bool bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type); - - bool m_ownCurrent; - const unsigned int m_id; - QSurface *m_surface; - QSize m_surfaceSize; - - QOpenGLShaderProgram *m_activeShader; - - QHash m_renderBufferHash; - QHash m_renderTargets; - QHash m_renderTargetsSize; - QAbstractTexture::TextureFormat m_renderTargetFormat; - - // cache some current state, to make sure we don't issue unnecessary GL calls - int m_currClearStencilValue; - float m_currClearDepthValue; - QColor m_currClearColorValue; - - Material* m_material; - QRectF m_viewport; - GLuint m_activeFBO; - - GLBuffer *m_boundArrayBuffer; - RenderStateSet* m_stateSet; - Renderer *m_renderer; - QByteArray m_uboTempArray; - - TextureSubmissionContext m_textureContext; - ImageSubmissionContext m_imageContext; - - // Attributes - friend class OpenGLVertexArrayObject; - - struct VAOVertexAttribute - { - HGLBuffer bufferHandle; - GLBuffer::Type attributeType; - int location; - GLint dataType; - uint byteOffset; - uint vertexSize; - uint byteStride; - uint divisor; - GLenum shaderDataType; - }; - - using VAOIndexAttribute = HGLBuffer; - void enableAttribute(const VAOVertexAttribute &attr); - void disableAttribute(const VAOVertexAttribute &attr); -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H diff --git a/src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp b/src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp deleted file mode 100644 index 67d0f9976..000000000 --- a/src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "texturesubmissioncontext_p.h" - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class TextureExtRendererLocker -{ -public: - static void lock(GLTexture *tex) - { - if (!tex->isExternalRenderingEnabled()) - return; - if (s_lockHash.keys().contains(tex)) { - ++s_lockHash[tex]; - } else { - tex->externalRenderingLock()->lock(); - s_lockHash[tex] = 1; - } - } - static void unlock(GLTexture *tex) - { - if (!tex->isExternalRenderingEnabled()) - return; - if (!s_lockHash.keys().contains(tex)) - return; - - --s_lockHash[tex]; - if (s_lockHash[tex] == 0) { - s_lockHash.remove(tex); - tex->externalRenderingLock()->unlock(); - } - } -private: - static QHash s_lockHash; -}; - -QHash TextureExtRendererLocker::s_lockHash = QHash(); - - -TextureSubmissionContext::TextureSubmissionContext() -{ - -} - -TextureSubmissionContext::~TextureSubmissionContext() -{ - -} - -void TextureSubmissionContext::initialize(GraphicsContext *context) -{ - m_activeTextures.resize(context->maxTextureUnitsCount()); -} - -void TextureSubmissionContext::endDrawing() -{ - decayTextureScores(); - for (int i = 0; i < m_activeTextures.size(); ++i) - if (m_activeTextures[i].texture) - TextureExtRendererLocker::unlock(m_activeTextures[i].texture); -} - -int TextureSubmissionContext::activateTexture(TextureSubmissionContext::TextureScope scope, - QOpenGLContext *m_gl, - GLTexture *tex) -{ - // Returns the texture unit to use for the texture - // This always return a valid unit, unless there are more textures than - // texture unit available for the current material - const int onUnit = assignUnitForTexture(tex); - - // check we didn't overflow the available units - if (onUnit == -1) - return -1; - - const int sharedTextureId = tex->sharedTextureId(); - // We have a valid texture id provided by a shared context - if (sharedTextureId > 0) { - m_gl->functions()->glActiveTexture(GL_TEXTURE0 + onUnit); - const QAbstractTexture::Target target = tex->properties().target; - // For now we know that target values correspond to the GL values - m_gl->functions()->glBindTexture(target, tex->sharedTextureId()); - } else { - // Texture must have been created and updated at this point - QOpenGLTexture *glTex = tex->getGLTexture(); - if (glTex == nullptr) - return -1; - glTex->bind(uint(onUnit)); - } - if (m_activeTextures[onUnit].texture != tex) { - if (m_activeTextures[onUnit].texture) - TextureExtRendererLocker::unlock(m_activeTextures[onUnit].texture); - m_activeTextures[onUnit].texture = tex; - TextureExtRendererLocker::lock(tex); - } - -#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) - int err = m_gl->functions()->glGetError(); - if (err) - qCWarning(Backend) << "GL error after activating texture" << QString::number(err, 16) - << tex->getGLTexture()->textureId() << "on unit" << onUnit; -#endif - - m_activeTextures[onUnit].score = 200; - m_activeTextures[onUnit].pinned = true; - m_activeTextures[onUnit].scope = scope; - - return onUnit; -} - -void TextureSubmissionContext::deactivateTexturesWithScope(TextureSubmissionContext::TextureScope ts) -{ - for (int u=0; u -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLContext; - -namespace Qt3DRender { -namespace Render { - -class GraphicsContext; -class GLTexture; - -class Q_AUTOTEST_EXPORT TextureSubmissionContext -{ -public: - enum TextureScope - { - TextureScopeMaterial = 0, - TextureScopeTechnique - // per-pass for deferred rendering? - }; - - TextureSubmissionContext(); - ~TextureSubmissionContext(); - - void initialize(GraphicsContext *context); - void endDrawing(); - int activateTexture(TextureScope scope, QOpenGLContext *gl, GLTexture* tex); - void deactivateTexture(GLTexture *tex); - void deactivateTexturesWithScope(TextureScope ts); - -private: - void decayTextureScores(); - int assignUnitForTexture(GLTexture* tex); - - // active textures, indexed by texture unit - struct ActiveTexture { - GLTexture *texture = nullptr; - int score = 0; - TextureScope scope = TextureScopeMaterial; - bool pinned = false; - }; - QVector m_activeTextures; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_TEXTURESUBMISSIONCONTEXT_H diff --git a/src/render/renderers/opengl/io/glbuffer.cpp b/src/render/renderers/opengl/io/glbuffer.cpp deleted file mode 100644 index f1b860f03..000000000 --- a/src/render/renderers/opengl/io/glbuffer.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "glbuffer_p.h" -#include - -#if !defined(GL_UNIFORM_BUFFER) -#define GL_UNIFORM_BUFFER 0x8A11 -#endif -#if !defined(GL_ARRAY_BUFFER) -#define GL_ARRAY_BUFFER 0x8892 -#endif -#if !defined(GL_ELEMENT_ARRAY_BUFFER) -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#endif -#if !defined(GL_SHADER_STORAGE_BUFFER) -#define GL_SHADER_STORAGE_BUFFER 0x90D2 -#endif -#if !defined(GL_PIXEL_PACK_BUFFER) -#define GL_PIXEL_PACK_BUFFER 0x88EB -#endif -#if !defined(GL_PIXEL_UNPACK_BUFFER) -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#endif -#if !defined(GL_DRAW_INDIRECT_BUFFER) -#define GL_DRAW_INDIRECT_BUFFER 0x8F3F -#endif - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -// A UBO is created for each ShaderData Shader Pair -// That means a UBO is unique to a shader/shaderdata - -namespace { - -GLenum glBufferTypes[] = { - GL_ARRAY_BUFFER, - GL_UNIFORM_BUFFER, - GL_ELEMENT_ARRAY_BUFFER, - GL_SHADER_STORAGE_BUFFER, - GL_PIXEL_PACK_BUFFER, - GL_PIXEL_UNPACK_BUFFER, - GL_DRAW_INDIRECT_BUFFER -}; - -} // anonymous - -GLBuffer::GLBuffer() - : m_bufferId(0) - , m_isCreated(false) - , m_bound(false) - , m_lastTarget(GL_ARRAY_BUFFER) -{ -} - -bool GLBuffer::bind(GraphicsContext *ctx, Type t) -{ - if (m_bufferId == 0) - return false; - m_lastTarget = glBufferTypes[t]; - ctx->openGLContext()->functions()->glBindBuffer(m_lastTarget, m_bufferId); - m_bound = true; - return true; -} - -bool GLBuffer::release(GraphicsContext *ctx) -{ - m_bound = false; - ctx->openGLContext()->functions()->glBindBuffer(m_lastTarget, 0); - return true; -} - -bool GLBuffer::create(GraphicsContext *ctx) -{ - ctx->openGLContext()->functions()->glGenBuffers(1, &m_bufferId); - m_isCreated = true; - return m_bufferId != 0; -} - -void GLBuffer::destroy(GraphicsContext *ctx) -{ - ctx->openGLContext()->functions()->glDeleteBuffers(1, &m_bufferId); - m_isCreated = false; -} - -void GLBuffer::allocate(GraphicsContext *ctx, uint size, bool dynamic) -{ - // Either GL_STATIC_DRAW OR GL_DYNAMIC_DRAW depending on the use case - // TO DO: find a way to know how a buffer/QShaderData will be used to use the right usage - ctx->openGLContext()->functions()->glBufferData(m_lastTarget, size, NULL, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -} - -void GLBuffer::allocate(GraphicsContext *ctx, const void *data, uint size, bool dynamic) -{ - ctx->openGLContext()->functions()->glBufferData(m_lastTarget, size, data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -} - -void GLBuffer::update(GraphicsContext *ctx, const void *data, uint size, int offset) -{ - ctx->openGLContext()->functions()->glBufferSubData(m_lastTarget, offset, size, data); -} - -QByteArray GLBuffer::download(GraphicsContext *ctx, uint size) -{ - char *gpu_ptr = ctx->mapBuffer(m_lastTarget, size); - QByteArray data; - if (gpu_ptr != nullptr) { - data.resize(size); - std::copy(gpu_ptr, gpu_ptr+size, data.data()); - } - ctx->unmapBuffer(m_lastTarget); - return data; -} - -void GLBuffer::bindBufferBase(GraphicsContext *ctx, int bindingPoint, GLBuffer::Type t) -{ - ctx->bindBufferBase(glBufferTypes[t], bindingPoint, m_bufferId); -} - -void GLBuffer::bindBufferBase(GraphicsContext *ctx, int bindingPoint) -{ - ctx->bindBufferBase(m_lastTarget, bindingPoint, m_bufferId); -} - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/io/glbuffer_p.h b/src/render/renderers/opengl/io/glbuffer_p.h deleted file mode 100644 index 676fb00d9..000000000 --- a/src/render/renderers/opengl/io/glbuffer_p.h +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GLBUFFER_P_H -#define QT3DRENDER_RENDER_GLBUFFER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class GraphicsContext; - -class GLBuffer -{ -public: - GLBuffer(); - - enum Type - { - ArrayBuffer = 0, - UniformBuffer, - IndexBuffer, - ShaderStorageBuffer, - PixelPackBuffer, - PixelUnpackBuffer, - DrawIndirectBuffer - }; - - bool bind(GraphicsContext *ctx, Type t); - bool release(GraphicsContext *ctx); - bool create(GraphicsContext *ctx); - void destroy(GraphicsContext *ctx); - void allocate(GraphicsContext *ctx, uint size, bool dynamic = true); - void allocate(GraphicsContext *ctx, const void *data, uint size, bool dynamic = true); - void update(GraphicsContext *ctx, const void *data, uint size, int offset = 0); - QByteArray download(GraphicsContext *ctx, uint size); - void bindBufferBase(GraphicsContext *ctx, int bindingPoint, Type t); - void bindBufferBase(GraphicsContext *ctx, int bindingPoint); - - inline GLuint bufferId() const { return m_bufferId; } - inline bool isCreated() const { return m_isCreated; } - inline bool isBound() const { return m_bound; } - -#ifdef Q_OS_WIN - // To get MSVC to compile even though we don't need any cleanup - void cleanup() {} -#endif - -private: - GLuint m_bufferId; - bool m_isCreated; - bool m_bound; - GLenum m_lastTarget; -}; - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GLBUFFER_P_H diff --git a/src/render/renderers/opengl/io/io.pri b/src/render/renderers/opengl/io/io.pri deleted file mode 100644 index 462978c4d..000000000 --- a/src/render/renderers/opengl/io/io.pri +++ /dev/null @@ -1,8 +0,0 @@ -INCLUDEPATH += $$PWD - -SOURCES += \ - $$PWD/glbuffer.cpp - -HEADERS += \ - $$PWD/glbuffer_p.h - diff --git a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp b/src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp deleted file mode 100644 index d2a01eef4..000000000 --- a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "filtercompatibletechniquejob_p.h" -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -FilterCompatibleTechniqueJob::FilterCompatibleTechniqueJob() - : m_manager(nullptr) - , m_renderer(nullptr) -{ - SET_JOB_RUN_STAT_TYPE(this, JobTypes::FilterCompatibleTechniques, 0) -} - -void FilterCompatibleTechniqueJob::setManager(TechniqueManager *manager) -{ - m_manager = manager; -} - -TechniqueManager *FilterCompatibleTechniqueJob::manager() const -{ - return m_manager; -} - -void FilterCompatibleTechniqueJob::setRenderer(Renderer *renderer) -{ - m_renderer = renderer; -} - -Renderer *FilterCompatibleTechniqueJob::renderer() const -{ - return m_renderer; -} - -void FilterCompatibleTechniqueJob::run() -{ - Q_ASSERT(m_manager != nullptr && m_renderer != nullptr); - Q_ASSERT(m_renderer->isRunning() && m_renderer->submissionContext()->isInitialized()); - - const QVector dirtyTechniqueIds = m_manager->takeDirtyTechniques(); - for (const Qt3DCore::QNodeId techniqueId : dirtyTechniqueIds) { - Technique *technique = m_manager->lookupResource(techniqueId); - if (Q_LIKELY(technique != nullptr)) - technique->setCompatibleWithRenderer((*m_renderer->contextInfo() == *technique->graphicsApiFilter())); - } -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob_p.h b/src/render/renderers/opengl/jobs/filtercompatibletechniquejob_p.h deleted file mode 100644 index 27b3d4ed2..000000000 --- a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H -#define QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class TechniqueManager; -class Renderer; - -class Q_3DRENDERSHARED_PRIVATE_EXPORT FilterCompatibleTechniqueJob : public Qt3DCore::QAspectJob -{ -public: - FilterCompatibleTechniqueJob(); - - void setManager(TechniqueManager *managers); - TechniqueManager *manager() const; - - void setRenderer(Renderer *renderer); - Renderer *renderer() const; - - void run() override; - -private: - TechniqueManager *m_manager; - Renderer *m_renderer; -}; - -typedef QSharedPointer FilterCompatibleTechniqueJobPtr; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H diff --git a/src/render/renderers/opengl/jobs/jobs.pri b/src/render/renderers/opengl/jobs/jobs.pri deleted file mode 100644 index d80b8bfd9..000000000 --- a/src/render/renderers/opengl/jobs/jobs.pri +++ /dev/null @@ -1,17 +0,0 @@ -INCLUDEPATH += $$PWD - -SOURCES += \ - $$PWD/filtercompatibletechniquejob.cpp \ - $$PWD/materialparametergathererjob.cpp \ - $$PWD/renderviewcommandbuilderjob.cpp \ - $$PWD/renderviewcommandupdaterjob.cpp \ - $$PWD/renderviewinitializerjob.cpp \ - $$PWD/renderviewjobutils.cpp - -HEADERS += \ - $$PWD/filtercompatibletechniquejob_p.h \ - $$PWD/materialparametergathererjob_p.h \ - $$PWD/renderviewcommandbuilderjob_p.h \ - $$PWD/renderviewcommandupdaterjob_p.h \ - $$PWD/renderviewinitializerjob_p.h \ - $$PWD/renderviewjobutils_p.h diff --git a/src/render/renderers/opengl/jobs/materialparametergathererjob.cpp b/src/render/renderers/opengl/jobs/materialparametergathererjob.cpp deleted file mode 100644 index e1f8aa403..000000000 --- a/src/render/renderers/opengl/jobs/materialparametergathererjob.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "materialparametergathererjob_p.h" -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -namespace { - -int materialParameterGathererCounter = 0; -const int likelyNumberOfParameters = 24; - -} // anonymous - -MaterialParameterGathererJob::MaterialParameterGathererJob() - : Qt3DCore::QAspectJob() - , m_manager(nullptr) - , m_techniqueFilter(nullptr) - , m_renderPassFilter(nullptr) -{ - SET_JOB_RUN_STAT_TYPE(this, JobTypes::MaterialParameterGathering, materialParameterGathererCounter++) -} - -// TechniqueFilter / RenderPassFilter - -// Parameters from Material/Effect/Technique - -// Note: we could maybe improve that by having a smart update when we detect -// that a parameter value has changed. That might require way more book keeping -// which might make this solution a bit too complex - -// The fact that this can now be performed in parallel should already provide a big -// improvement -void MaterialParameterGathererJob::run() -{ - for (const HMaterial &materialHandle : qAsConst(m_handles)) { - Material *material = m_manager->materialManager()->data(materialHandle); - - if (Q_UNLIKELY(!material->isEnabled())) - continue; - - Effect *effect = m_manager->effectManager()->lookupResource(material->effect()); - Technique *technique = findTechniqueForEffect(m_manager, m_techniqueFilter, effect); - - if (Q_LIKELY(technique != nullptr)) { - RenderPassList passes = findRenderPassesForTechnique(m_manager, m_renderPassFilter, technique); - if (Q_LIKELY(passes.size() > 0)) { - // Order set: - // 1 Pass Filter - // 2 Technique Filter - // 3 Material - // 4 Effect - // 5 Technique - // 6 RenderPass - - // Add Parameters define in techniqueFilter and passFilter - // passFilter have priority over techniqueFilter - - ParameterInfoList parameters; - // Doing the reserve allows a gain of 0.5ms on some of the demo examples - parameters.reserve(likelyNumberOfParameters); - - if (m_renderPassFilter) - parametersFromParametersProvider(¶meters, m_manager->parameterManager(), - m_renderPassFilter); - if (m_techniqueFilter) - parametersFromParametersProvider(¶meters, m_manager->parameterManager(), - m_techniqueFilter); - // Get the parameters for our selected rendering setup (override what was defined in the technique/pass filter) - parametersFromMaterialEffectTechnique(¶meters, m_manager->parameterManager(), material, effect, technique); - - for (RenderPass *renderPass : passes) { - ParameterInfoList globalParameters = parameters; - parametersFromParametersProvider(&globalParameters, m_manager->parameterManager(), renderPass); - m_parameters[material->peerId()].push_back({renderPass, globalParameters}); - } - } - } - } -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/materialparametergathererjob_p.h b/src/render/renderers/opengl/jobs/materialparametergathererjob_p.h deleted file mode 100644 index 6ba060841..000000000 --- a/src/render/renderers/opengl/jobs/materialparametergathererjob_p.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H -#define QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class NodeManagers; -class TechniqueFilter; -class RenderPassFilter; -class Renderer; - -// TO be executed for each FrameGraph branch with a given RenderPassFilter/TechniqueFilter - -class Q_3DRENDERSHARED_PRIVATE_EXPORT MaterialParameterGathererJob : public Qt3DCore::QAspectJob -{ -public: - MaterialParameterGathererJob(); - - inline void setNodeManagers(NodeManagers *manager) Q_DECL_NOTHROW { m_manager = manager; } - inline void setTechniqueFilter(TechniqueFilter *techniqueFilter) Q_DECL_NOTHROW { m_techniqueFilter = techniqueFilter; } - inline void setRenderPassFilter(RenderPassFilter *renderPassFilter) Q_DECL_NOTHROW { m_renderPassFilter = renderPassFilter; } - inline const QHash> &materialToPassAndParameter() Q_DECL_NOTHROW { return m_parameters; } - inline void setHandles(const QVector &handles) Q_DECL_NOTHROW { m_handles = handles; } - - inline TechniqueFilter *techniqueFilter() const Q_DECL_NOTHROW { return m_techniqueFilter; } - inline RenderPassFilter *renderPassFilter() const Q_DECL_NOTHROW { return m_renderPassFilter; } - - void run() final; - -private: - NodeManagers *m_manager; - TechniqueFilter *m_techniqueFilter; - RenderPassFilter *m_renderPassFilter; - - // Material id to array of RenderPasse with parameters - MaterialParameterGathererData m_parameters; - QVector m_handles; -}; - -typedef QSharedPointer MaterialParameterGathererJobPtr; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H diff --git a/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp b/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp deleted file mode 100644 index 091d49ef5..000000000 --- a/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderviewcommandbuilderjob_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -namespace { -int renderViewInstanceCounter = 0; -} // anonymous - -RenderViewCommandBuilderJob::RenderViewCommandBuilderJob() - : Qt3DCore::QAspectJob() - , m_offset(0) - , m_count(0) - , m_renderView(nullptr) -{ - SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderViewCommandBuilder, renderViewInstanceCounter++) -} - -void RenderViewCommandBuilderJob::run() -{ - if (!m_renderView->noDraw()) { - if (m_count == 0) - return; - - const bool isDraw = !m_renderView->isCompute(); - if (isDraw) - m_commandData = m_renderView->buildDrawRenderCommands(m_entities, m_offset, m_count); - else - m_commandData = m_renderView->buildComputeRenderCommands(m_entities, m_offset, m_count); - } -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h b/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h deleted file mode 100644 index 556c7f241..000000000 --- a/src/render/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2019 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H -#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob -{ -public: - RenderViewCommandBuilderJob(); - - inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } - inline void setEntities(const QVector &entities, int offset, int count) - { - m_offset = offset; - m_count = count; - m_entities = entities; - } - inline EntityRenderCommandData &commandData() { return m_commandData; } - - void run() final; - -private: - int m_offset; - int m_count; - RenderView *m_renderView; - QVector m_entities; - EntityRenderCommandData m_commandData; -}; - -typedef QSharedPointer RenderViewCommandBuilderJobPtr; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H diff --git a/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp b/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp deleted file mode 100644 index 6772279d7..000000000 --- a/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderviewcommandupdaterjob_p.h" -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -namespace { -int renderViewInstanceCounter = 0; -} // anonymous - -RenderViewCommandUpdaterJob::RenderViewCommandUpdaterJob() - : Qt3DCore::QAspectJob() - , m_offset(0) - , m_count(0) - , m_renderView(nullptr) - , m_renderer(nullptr) - , m_renderables() -{ - SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderCommandUpdater, renderViewInstanceCounter++) -} - -void RenderViewCommandUpdaterJob::run() -{ - // Build RenderCommand should perform the culling as we have no way to determine - // if a child has a mesh in the view frustum while its parent isn't contained in it. - if (!m_renderView->noDraw()) { - if (m_count == 0) - return; - // Update Render Commands (Uniform Change, Depth Change) - m_renderView->updateRenderCommand(m_renderables.data(), m_offset, m_count); - } -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h b/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h deleted file mode 100644 index d7f424966..000000000 --- a/src/render/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H -#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class RenderView; -class Renderer; - -class Q_AUTOTEST_EXPORT RenderViewCommandUpdaterJob : public Qt3DCore::QAspectJob -{ -public: - RenderViewCommandUpdaterJob(); - - inline void setRenderView(RenderView *rv) Q_DECL_NOTHROW { m_renderView = rv; } - inline void setRenderer(Renderer *renderer) Q_DECL_NOTHROW { m_renderer = renderer; } - inline void setRenderables(const EntityRenderCommandDataPtr &renderables, int offset, int count) Q_DECL_NOTHROW - { - m_offset = offset; - m_count = count; - m_renderables = renderables; - } - EntityRenderCommandDataPtr renderables() const { return m_renderables; } - - QVector &commands() Q_DECL_NOTHROW { return m_commands; } - - void run() final; - -private: - int m_offset; - int m_count; - RenderView *m_renderView; - Renderer *m_renderer; - EntityRenderCommandDataPtr m_renderables; - QVector m_commands; -}; - -typedef QSharedPointer RenderViewCommandUpdaterJobPtr; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H diff --git a/src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp b/src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp deleted file mode 100644 index f0f72803c..000000000 --- a/src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderviewinitializerjob_p.h" - -#include -#include -#include -#include -#include - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -namespace { -// only accessed in ctor and dtor of RenderViewJob -// which are always being called in a non concurrent manner -int renderViewInstanceCounter = 0; -} // anonymous - -RenderViewInitializerJob::RenderViewInitializerJob() - : m_renderer(nullptr) - , m_fgLeaf(nullptr) - , m_index(0) - , m_renderView(nullptr) -{ - SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderView, renderViewInstanceCounter++) -} - -RenderViewInitializerJob::~RenderViewInitializerJob() -{ - renderViewInstanceCounter--; -} - -void RenderViewInitializerJob::run() -{ - qCDebug(Jobs) << Q_FUNC_INFO << m_index; -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - QElapsedTimer timer; - timer.start(); - qint64 gatherLightsTime; - qint64 buildCommandsTime; -#endif - - // Create a RenderView object - // The RenderView are created from a QFrameAllocator stored in the current Thread local storage - m_renderView = new RenderView; - - // RenderView should allocate heap resources using only the currentFrameAllocator - m_renderView->setRenderer(m_renderer); - - // Populate the renderview's configuration from the framegraph - setRenderViewConfigFromFrameGraphLeafNode(m_renderView, m_fgLeaf); -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) - qint64 gatherStateTime = timer.nsecsElapsed(); - timer.restart(); -#endif -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewinitializerjob_p.h b/src/render/renderers/opengl/jobs/renderviewinitializerjob_p.h deleted file mode 100644 index fb4e2c67c..000000000 --- a/src/render/renderers/opengl/jobs/renderviewinitializerjob_p.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H -#define QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class Renderer; -class FrameGraphNode; -class RenderView; - -class Q_AUTOTEST_EXPORT RenderViewInitializerJob : public Qt3DCore::QAspectJob -{ -public: - RenderViewInitializerJob(); - ~RenderViewInitializerJob(); - - inline void setRenderer(Renderer *renderer) { m_renderer = renderer; } - inline RenderView *renderView() const Q_DECL_NOTHROW { return m_renderView; } - - inline void setFrameGraphLeafNode(FrameGraphNode *fgLeaf) - { - m_fgLeaf = fgLeaf; - } - - // Sets the position in the queue of RenderViews that the - // RenderView generated by this job should be inserted. This is - // used to ensure that for example a RenderView for creating - // a shadow map texture is submitted before the RenderView that - // contains commands making use of the shadow map - inline void setSubmitOrderIndex(int index) { m_index = index; } - inline int submitOrderIndex() const { return m_index; } - - void run() override; - -private: - Renderer *m_renderer; - FrameGraphNode *m_fgLeaf; - int m_index; - RenderView *m_renderView; -}; - -typedef QSharedPointer RenderViewInitializerJobPtr; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H diff --git a/src/render/renderers/opengl/jobs/renderviewjobutils.cpp b/src/render/renderers/opengl/jobs/renderviewjobutils.cpp deleted file mode 100644 index 16d449d4a..000000000 --- a/src/render/renderers/opengl/jobs/renderviewjobutils.cpp +++ /dev/null @@ -1,574 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderviewjobutils_p.h" -#include "renderlogging_p.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -using namespace Qt3DCore; - -namespace Qt3DRender { -namespace Render { - -/*! - \internal - Walks up the framegraph tree from \a fgLeaf and builds up as much state - as possible and populates \a rv. For cases where we can't get the specific state - (e.g. because it depends upon more than just the framegraph) we store the data from - the framegraph that will be needed to later when the rest of the data becomes available -*/ -void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, const FrameGraphNode *fgLeaf) -{ - // The specific RenderPass to be used is also dependent upon the Effect and TechniqueFilter - // which is referenced by the Material which is referenced by the RenderMesh. So we can - // only store the filter info in the RenderView structure and use it to do the resolving - // when we build the RenderCommand list. - const NodeManagers *manager = rv->nodeManagers(); - const FrameGraphNode *node = fgLeaf; - - while (node) { - FrameGraphNode::FrameGraphNodeType type = node->nodeType(); - if (node->isEnabled()) - switch (type) { - case FrameGraphNode::InvalidNodeType: - // A base FrameGraphNode, can be used for grouping purposes - break; - case FrameGraphNode::CameraSelector: - // Can be set only once and we take camera nearest to the leaf node - if (!rv->renderCameraLens()) { - const CameraSelector *cameraSelector = static_cast(node); - Entity *camNode = manager->renderNodesManager()->lookupResource(cameraSelector->cameraUuid()); - if (camNode) { - CameraLens *lens = camNode->renderComponent(); - rv->setRenderCameraEntity(camNode); - if (lens && lens->isEnabled()) { - rv->setRenderCameraLens(lens); - // ViewMatrix and ProjectionMatrix are computed - // later in updateMatrices() - // since at this point the transformation matrices - // may not yet have been updated - } - } - } - break; - - case FrameGraphNode::LayerFilter: // Can be set multiple times in the tree - rv->appendLayerFilter(static_cast(node)->peerId()); - break; - - case FrameGraphNode::ProximityFilter: // Can be set multiple times in the tree - rv->appendProximityFilterId(node->peerId()); - break; - - case FrameGraphNode::RenderPassFilter: - // Can be set once - // TODO: Amalgamate all render pass filters from leaf to root - if (!rv->renderPassFilter()) - rv->setRenderPassFilter(static_cast(node)); - break; - - case FrameGraphNode::RenderTarget: { - // Can be set once and we take render target nearest to the leaf node - const RenderTargetSelector *targetSelector = static_cast(node); - QNodeId renderTargetUid = targetSelector->renderTargetUuid(); - HTarget renderTargetHandle = manager->renderTargetManager()->lookupHandle(renderTargetUid); - - // Add renderTarget Handle and build renderCommand AttachmentPack - if (!rv->renderTargetId()) { - rv->setRenderTargetId(renderTargetUid); - - RenderTarget *renderTarget = manager->renderTargetManager()->data(renderTargetHandle); - if (renderTarget) - rv->setAttachmentPack(AttachmentPack(renderTarget, manager->attachmentManager(), targetSelector->outputs())); - } - break; - } - - case FrameGraphNode::ClearBuffers: { - const ClearBuffers *cbNode = static_cast(node); - rv->addClearBuffers(cbNode); - break; - } - - case FrameGraphNode::TechniqueFilter: - // Can be set once - // TODO Amalgamate all technique filters from leaf to root - if (!rv->techniqueFilter()) - rv->setTechniqueFilter(static_cast(node)); - break; - - case FrameGraphNode::Viewport: { - // If the Viewport has already been set in a lower node - // Make it so that the new viewport is actually - // a subregion relative to that of the parent viewport - const ViewportNode *vpNode = static_cast(node); - rv->setViewport(ViewportNode::computeViewport(rv->viewport(), vpNode)); - rv->setGamma(vpNode->gamma()); - break; - } - - case FrameGraphNode::SortMethod: { - const Render::SortPolicy *sortPolicy = static_cast(node); - rv->addSortType(sortPolicy->sortTypes()); - break; - } - - case FrameGraphNode::SubtreeEnabler: - // Has no meaning here. SubtreeEnabler was used - // in a prior step to filter the list of RenderViewJobs - break; - - case FrameGraphNode::StateSet: { - const Render::StateSetNode *rStateSet = static_cast(node); - // Create global RenderStateSet for renderView if no stateSet was set before - RenderStateSet *stateSet = rv->stateSet(); - if (stateSet == nullptr && rStateSet->hasRenderStates()) { - stateSet = new RenderStateSet(); - rv->setStateSet(stateSet); - } - - // Add states from new stateSet we might be missing - // but don' t override existing states (lower StateSetNode always has priority) - if (rStateSet->hasRenderStates()) - addStatesToRenderStateSet(stateSet, rStateSet->renderStates(), manager->renderStateManager()); - break; - } - - case FrameGraphNode::NoDraw: { - rv->setNoDraw(true); - break; - } - - case FrameGraphNode::FrustumCulling: { - rv->setFrustumCulling(true); - break; - } - - case FrameGraphNode::ComputeDispatch: { - const Render::DispatchCompute *dispatchCompute = static_cast(node); - rv->setCompute(true); - rv->setComputeWorkgroups(dispatchCompute->x(), - dispatchCompute->y(), - dispatchCompute->z()); - break; - } - - case FrameGraphNode::Lighting: { - // TODO - break; - } - - case FrameGraphNode::Surface: { - // Use the surface closest to leaf node - if (rv->surface() == nullptr) { - const Render::RenderSurfaceSelector *surfaceSelector - = static_cast(node); - rv->setSurface(surfaceSelector->surface()); - rv->setSurfaceSize(surfaceSelector->renderTargetSize() * surfaceSelector->devicePixelRatio()); - rv->setDevicePixelRatio(surfaceSelector->devicePixelRatio()); - } - break; - } - - case FrameGraphNode::DebugOverlay: - rv->setShowDebugOverlay(true); - break; - - case FrameGraphNode::RenderCapture: { - auto *renderCapture = const_cast( - static_cast(node)); - if (rv->renderCaptureNodeId().isNull() && renderCapture->wasCaptureRequested()) { - rv->setRenderCaptureNodeId(renderCapture->peerId()); - rv->setRenderCaptureRequest(renderCapture->takeCaptureRequest()); - } - break; - } - - case FrameGraphNode::MemoryBarrier: { - const Render::MemoryBarrier *barrier = static_cast(node); - rv->setMemoryBarrier(barrier->waitOperations()|rv->memoryBarrier()); - break; - } - - case FrameGraphNode::BufferCapture: { - auto *bufferCapture = const_cast( - static_cast(node)); - if (bufferCapture != nullptr) - rv->setIsDownloadBuffersEnable(bufferCapture->isEnabled()); - break; - } - - case FrameGraphNode::BlitFramebuffer: { - const Render::BlitFramebuffer *blitFramebufferNode = - static_cast(node); - rv->setHasBlitFramebufferInfo(true); - BlitFramebufferInfo bfbInfo; - bfbInfo.sourceRenderTargetId = blitFramebufferNode->sourceRenderTargetId(); - bfbInfo.destinationRenderTargetId = blitFramebufferNode->destinationRenderTargetId(); - bfbInfo.sourceRect = blitFramebufferNode->sourceRect(); - bfbInfo.destinationRect = blitFramebufferNode->destinationRect(); - bfbInfo.sourceAttachmentPoint = blitFramebufferNode->sourceAttachmentPoint(); - bfbInfo.destinationAttachmentPoint = blitFramebufferNode->destinationAttachmentPoint(); - bfbInfo.interpolationMethod = blitFramebufferNode->interpolationMethod(); - rv->setBlitFrameBufferInfo(bfbInfo); - break; - } - - case FrameGraphNode::WaitFence: { - const Render::WaitFence *waitFence = static_cast(node); - rv->appendWaitFence(waitFence->data()); - break; - } - - case FrameGraphNode::SetFence: { - rv->appendInsertFenceId(node->peerId()); - break; - } - - case FrameGraphNode::NoPicking: - // Nothing to do RenderView wise for NoPicking - break; - - default: - // Should never get here - qCWarning(Backend) << "Unhandled FrameGraphNode type"; - } - - node = node->parent(); - } -} - -/*! - \internal - Searches the best matching Technique from \a effect specified. -*/ -Technique *findTechniqueForEffect(NodeManagers *manager, - const TechniqueFilter *techniqueFilter, - Effect *effect) -{ - if (!effect) - return nullptr; - - QVector matchingTechniques; - const bool hasInvalidTechniqueFilter = (techniqueFilter == nullptr || techniqueFilter->filters().isEmpty()); - - // Iterate through the techniques in the effect - const auto techniqueIds = effect->techniques(); - for (const QNodeId techniqueId : techniqueIds) { - Technique *technique = manager->techniqueManager()->lookupResource(techniqueId); - - // Should be valid, if not there likely a problem with node addition/destruction changes - Q_ASSERT(technique); - - // Check if the technique is compatible with the rendering API - // If no techniqueFilter is present, we return the technique as it satisfies OpenGL version - if (technique->isCompatibleWithRenderer() && (hasInvalidTechniqueFilter || technique->isCompatibleWithFilters(techniqueFilter->filters()))) - matchingTechniques.append(technique); - } - - if (matchingTechniques.size() == 0) // We failed to find a suitable technique to use :( - return nullptr; - - if (matchingTechniques.size() == 1) - return matchingTechniques.first(); - - // Several compatible techniques, return technique with highest major and minor version - Technique* highest = matchingTechniques.first(); - GraphicsApiFilterData filter = *highest->graphicsApiFilter(); - for (auto it = matchingTechniques.cbegin() + 1; it < matchingTechniques.cend(); ++it) { - if (filter < *(*it)->graphicsApiFilter()) { - filter = *(*it)->graphicsApiFilter(); - highest = *it; - } - } - return highest; -} - - -RenderPassList findRenderPassesForTechnique(NodeManagers *manager, - const RenderPassFilter *passFilter, - Technique *technique) -{ - Q_ASSERT(manager); - Q_ASSERT(technique); - - RenderPassList passes; - const auto passIds = technique->renderPasses(); - for (const QNodeId passId : passIds) { - RenderPass *renderPass = manager->renderPassManager()->lookupResource(passId); - - if (renderPass && renderPass->isEnabled()) { - bool foundMatch = (!passFilter || passFilter->filters().size() == 0); - - // A pass filter is present so we need to check for matching criteria - if (!foundMatch && renderPass->filterKeys().size() >= passFilter->filters().size()) { - - // Iterate through the filter criteria and look for render passes with criteria that satisfy them - const auto filterKeyIds = passFilter->filters(); - for (const QNodeId filterKeyId : filterKeyIds) { - foundMatch = false; - FilterKey *filterFilterKey = manager->filterKeyManager()->lookupResource(filterKeyId); - - const auto passFilterKeyIds = renderPass->filterKeys(); - for (const QNodeId passFilterKeyId : passFilterKeyIds) { - FilterKey *passFilterKey = manager->filterKeyManager()->lookupResource(passFilterKeyId); - if ((foundMatch = (*passFilterKey == *filterFilterKey))) - break; - } - - if (!foundMatch) { - // No match for criterion in any of the render pass' criteria - break; - } - } - } - - if (foundMatch) { - // Found a renderpass that satisfies our needs. Add it in order - passes << renderPass; - } - } - } - - return passes; -} - - -ParameterInfoList::const_iterator findParamInfo(ParameterInfoList *params, const int nameId) -{ - const ParameterInfoList::const_iterator end = params->cend(); - ParameterInfoList::const_iterator it = std::lower_bound(params->cbegin(), end, nameId); - if (it != end && it->nameId != nameId) - return end; - return it; -} - -void addParametersForIds(ParameterInfoList *params, ParameterManager *manager, - const Qt3DCore::QNodeIdVector ¶meterIds) -{ - for (const QNodeId paramId : parameterIds) { - const HParameter parameterHandle = manager->lookupHandle(paramId); - const Parameter *param = manager->data(parameterHandle); - ParameterInfoList::iterator it = std::lower_bound(params->begin(), params->end(), param->nameId()); - if (it == params->end() || it->nameId != param->nameId()) - params->insert(it, ParameterInfo(param->nameId(), parameterHandle)); - } -} - -void parametersFromMaterialEffectTechnique(ParameterInfoList *infoList, - ParameterManager *manager, - Material *material, - Effect *effect, - Technique *technique) -{ - // The parameters are taken in the following priority order: - // - // 1) Material - // 2) Effect - // 3) Technique - // - // That way a user can override defaults in Effect's and Techniques on a - // object manner and a Technique can override global defaults from the Effect. - parametersFromParametersProvider(infoList, manager, material); - parametersFromParametersProvider(infoList, manager, effect); - parametersFromParametersProvider(infoList, manager, technique); -} - -// Only add states with types we don't already have -void addStatesToRenderStateSet(RenderStateSet *stateSet, - const QVector stateIds, - RenderStateManager *manager) -{ - for (const Qt3DCore::QNodeId &stateId : stateIds) { - RenderStateNode *node = manager->lookupResource(stateId); - if (node->isEnabled() && stateSet->canAddStateOfType(node->type())) { - stateSet->addState(node->impl()); - } - } -} - -namespace { - -const QString blockArray = QStringLiteral("[%1]"); -const int qNodeIdTypeId = qMetaTypeId(); - -} - -UniformBlockValueBuilder::UniformBlockValueBuilder() - : updatedPropertiesOnly(false) - , shaderDataManager(nullptr) - , textureManager(nullptr) -{ -} - -UniformBlockValueBuilder::~UniformBlockValueBuilder() -{ -} - -void UniformBlockValueBuilder::buildActiveUniformNameValueMapHelper(ShaderData *currentShaderData, const QString &blockName, const QString &qmlPropertyName, const QVariant &value) -{ - // In the end, values are either scalar or a scalar array - // Composed elements (structs, structs array) are simplified into simple scalars - if (value.userType() == QMetaType::QVariantList) { // Array - QVariantList list = value.value(); - if (list.at(0).userType() == qNodeIdTypeId) { // Array of struct qmlPropertyName[i].structMember - for (int i = 0; i < list.size(); ++i) { - const QVariant variantElement = list.at(i); - if (list.at(i).userType() == qNodeIdTypeId) { - const auto nodeId = variantElement.value(); - ShaderData *subShaderData = shaderDataManager->lookupResource(nodeId); - if (subShaderData) { - buildActiveUniformNameValueMapStructHelper(subShaderData, - blockName + QLatin1Char('.') + qmlPropertyName + blockArray.arg(i), - QLatin1String("")); - } - // Note: we only handle ShaderData as nested container nodes here - } - } - } else { // Array of scalar/vec qmlPropertyName[0] - QString varName; - varName.reserve(blockName.length() + 1 + qmlPropertyName.length() + 3); - varName.append(blockName); - varName.append(QLatin1String(".")); - varName.append(qmlPropertyName); - varName.append(QLatin1String("[0]")); - if (uniforms.contains(varName)) { - qCDebug(Shaders) << "UBO array member " << varName << " set for update"; - activeUniformNamesToValue.insert(StringToInt::lookupId(varName), value); - } - } - } else if (value.userType() == qNodeIdTypeId) { // Struct qmlPropertyName.structMember - const auto nodeId = value.value(); - ShaderData *rSubShaderData = shaderDataManager->lookupResource(nodeId); - if (rSubShaderData) { - buildActiveUniformNameValueMapStructHelper(rSubShaderData, - blockName, - qmlPropertyName); - } else if (textureManager->contains(nodeId)) { - const auto varId = StringToInt::lookupId(blockName + QLatin1Char('.') + qmlPropertyName); - activeUniformNamesToValue.insert(varId, value); - } - } else { // Scalar / Vec - QString varName; - varName.reserve(blockName.length() + 1 + qmlPropertyName.length()); - varName.append(blockName); - varName.append(QLatin1String(".")); - varName.append(qmlPropertyName); - if (uniforms.contains(varName)) { - qCDebug(Shaders) << "UBO scalar member " << varName << " set for update"; - - // If the property needs to be transformed, we transform it here as - // the shaderdata cannot hold transformed properties for multiple - // thread contexts at once - activeUniformNamesToValue.insert(StringToInt::lookupId(varName), - currentShaderData->getTransformedProperty(qmlPropertyName, viewMatrix)); - } - } -} - -void UniformBlockValueBuilder::buildActiveUniformNameValueMapStructHelper(ShaderData *rShaderData, const QString &blockName, const QString &qmlPropertyName) -{ - const QHash &properties = rShaderData->properties(); - auto it = properties.begin(); - const auto end = properties.end(); - - while (it != end) { - QString fullBlockName; - fullBlockName.reserve(blockName.length() + 1 + qmlPropertyName.length()); - fullBlockName.append(blockName); - if (!qmlPropertyName.isEmpty()) { - fullBlockName.append(QLatin1String(".")); - fullBlockName.append(qmlPropertyName); - } - buildActiveUniformNameValueMapHelper(rShaderData, fullBlockName, - it.key(), it.value().value); - ++it; - } -} - -ParameterInfo::ParameterInfo(const int nameId, const HParameter &handle) - : nameId(nameId) - , handle(handle) -{} - -bool ParameterInfo::operator<(const ParameterInfo &other) const Q_DECL_NOEXCEPT -{ - return nameId < other.nameId; -} - -bool ParameterInfo::operator<(const int otherNameId) const Q_DECL_NOEXCEPT -{ - return nameId < otherNameId; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/jobs/renderviewjobutils_p.h b/src/render/renderers/opengl/jobs/renderviewjobutils_p.h deleted file mode 100644 index b2fa59785..000000000 --- a/src/render/renderers/opengl/jobs/renderviewjobutils_p.h +++ /dev/null @@ -1,187 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDERVIEWJOBUTILS_P_H -#define QT3DRENDER_RENDERVIEWJOBUTILS_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DCore { -class QFrameAllocator; -} - -namespace Qt3DRender { -namespace Render { - -class FrameGraphNode; -class ParameterManager; -class Effect; -class Entity; -class Material; -class RenderPass; -class RenderStateSet; -class Technique; -class RenderView; -class TechniqueFilter; -class RenderPassFilter; -class Renderer; -class NodeManagers; -class ShaderDataManager; -struct ShaderUniform; -class ShaderData; -class TextureManager; -class RenderStateManager; -class RenderStateCollection; - -Q_AUTOTEST_EXPORT void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, - const FrameGraphNode *fgLeaf); - -Q_AUTOTEST_EXPORT Technique *findTechniqueForEffect(NodeManagers *manager, - const TechniqueFilter *techniqueFilter, - Effect *effect); - -typedef QVarLengthArray RenderPassList; -Q_AUTOTEST_EXPORT RenderPassList findRenderPassesForTechnique(NodeManagers *manager, - const RenderPassFilter *passFilter, - Technique *technique); - -// Extracts the type T from a QVariant v without using QVariant::value which is slow -// Note: Assumes you are 100% sure about the type you requested -template -inline T variant_value(const QVariant &v) -{ - return *reinterpret_cast(v.data()); -} - -struct ParameterInfo -{ - explicit ParameterInfo(const int nameId = -1, const HParameter &handle = HParameter()); - - int nameId; - HParameter handle; - - bool operator<(const int otherNameId) const Q_DECL_NOEXCEPT; - bool operator<(const ParameterInfo &other) const Q_DECL_NOEXCEPT; -}; -typedef QVector ParameterInfoList; - -struct RenderPassParameterData -{ - RenderPass *pass; - ParameterInfoList parameterInfo; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, RenderPassParameterData, Q_MOVABLE_TYPE) - -using MaterialParameterGathererData = QHash>; - -Q_AUTOTEST_EXPORT void parametersFromMaterialEffectTechnique(ParameterInfoList *infoList, - ParameterManager *manager, - Material *material, - Effect *effect, - Technique *technique); - -Q_AUTOTEST_EXPORT void addParametersForIds(ParameterInfoList *params, ParameterManager *manager, - const QVector ¶meterIds); - -template -void parametersFromParametersProvider(ParameterInfoList *infoList, - ParameterManager *manager, - T *provider) -{ - addParametersForIds(infoList, manager, provider->parameters()); -} - -Q_AUTOTEST_EXPORT ParameterInfoList::const_iterator findParamInfo(ParameterInfoList *infoList, - const int nameId); - -Q_AUTOTEST_EXPORT void addStatesToRenderStateSet(RenderStateSet *stateSet, - const QVector stateIds, - RenderStateManager *manager); - -typedef QHash UniformBlockValueBuilderHash; - -struct Q_AUTOTEST_EXPORT UniformBlockValueBuilder -{ - UniformBlockValueBuilder(); - ~UniformBlockValueBuilder(); - - QT3D_ALIGNED_MALLOC_AND_FREE() - - void buildActiveUniformNameValueMapHelper(ShaderData *currentShaderData, - const QString &blockName, - const QString &qmlPropertyName, - const QVariant &value); - void buildActiveUniformNameValueMapStructHelper(ShaderData *rShaderData, - const QString &blockName, - const QString &qmlPropertyName = QString()); - - bool updatedPropertiesOnly; - QHash uniforms; - UniformBlockValueBuilderHash activeUniformNamesToValue; - ShaderDataManager *shaderDataManager; - TextureManager *textureManager; - Matrix4x4 viewMatrix; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDERVIEWJOBUTILS_P_H diff --git a/src/render/renderers/opengl/managers/gl_handle_types_p.h b/src/render/renderers/opengl/managers/gl_handle_types_p.h deleted file mode 100644 index eb25bab7f..000000000 --- a/src/render/renderers/opengl/managers/gl_handle_types_p.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2018 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H -#define QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class GLBuffer; -class GLTexture; -class OpenGLVertexArrayObject; - -typedef Qt3DCore::QHandle HGLBuffer; -typedef Qt3DCore::QHandle HVao; -typedef Qt3DCore::QHandle HGLTexture; - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H diff --git a/src/render/renderers/opengl/managers/glresourcemanagers.cpp b/src/render/renderers/opengl/managers/glresourcemanagers.cpp deleted file mode 100644 index 2b1b87925..000000000 --- a/src/render/renderers/opengl/managers/glresourcemanagers.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "glresourcemanagers_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - - -GLResourceManagers::GLResourceManagers() - : m_glBufferManager(new GLBufferManager()) - , m_glShaderManager(new GLShaderManager()) - , m_glTextureManager(new GLTextureManager()) - , m_glFenceManager(new GLFenceManager()) - , m_vaoManager(new VAOManager()) -{ -} - -GLResourceManagers::~GLResourceManagers() -{ - delete m_vaoManager; - delete m_glFenceManager; - delete m_glTextureManager; - delete m_glShaderManager; - delete m_glBufferManager; -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/managers/glresourcemanagers_p.h b/src/render/renderers/opengl/managers/glresourcemanagers_p.h deleted file mode 100644 index 8c4c46bca..000000000 --- a/src/render/renderers/opengl/managers/glresourcemanagers_p.h +++ /dev/null @@ -1,135 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H -#define QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class Q_AUTOTEST_EXPORT GLFenceManager : public QHash -{ -}; - -class Q_AUTOTEST_EXPORT VAOManager : public Qt3DCore::QResourceManager< - OpenGLVertexArrayObject, - VAOIdentifier, - Qt3DCore::NonLockingPolicy> -{ -public: - VAOManager() {} -}; - -class Q_AUTOTEST_EXPORT GLBufferManager : public Qt3DCore::QResourceManager< - GLBuffer, - Qt3DCore::QNodeId, - Qt3DCore::NonLockingPolicy> -{ -}; - -class Q_AUTOTEST_EXPORT GLTextureManager : public Qt3DCore::QResourceManager< - GLTexture, - Qt3DCore::QNodeId, - Qt3DCore::NonLockingPolicy> -{ -public: - QHash texNodeIdForGLTexture; -}; - -class Q_AUTOTEST_EXPORT GLShaderManager : public APIShaderManager -{ -public: - explicit GLShaderManager() - : APIShaderManager() - {} -}; - - -class Q_AUTOTEST_EXPORT GLResourceManagers -{ -public: - GLResourceManagers(); - ~GLResourceManagers(); - - inline VAOManager *vaoManager() const noexcept { return m_vaoManager; } - inline GLShaderManager *glShaderManager() const noexcept { return m_glShaderManager; } - inline GLTextureManager *glTextureManager() const noexcept { return m_glTextureManager; } - inline GLBufferManager *glBufferManager() const noexcept { return m_glBufferManager; } - inline GLFenceManager *glFenceManager() const noexcept { return m_glFenceManager; } - -private: - GLBufferManager *m_glBufferManager; - GLShaderManager *m_glShaderManager; - GLTextureManager *m_glTextureManager; - GLFenceManager *m_glFenceManager; - VAOManager *m_vaoManager; -}; - -} // Render - -} // Qt3DRender - -Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP) - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H diff --git a/src/render/renderers/opengl/managers/managers.pri b/src/render/renderers/opengl/managers/managers.pri deleted file mode 100644 index 56a0732b1..000000000 --- a/src/render/renderers/opengl/managers/managers.pri +++ /dev/null @@ -1,9 +0,0 @@ -INCLUDEPATH += $$PWD - -HEADERS += \ - $$PWD/gl_handle_types_p.h \ - $$PWD/glresourcemanagers_p.h - $$PWD/glshadermanager_p.h \ - -SOURCES += \ - $$PWD/glresourcemanagers.cpp diff --git a/src/render/renderers/opengl/opengl.pri b/src/render/renderers/opengl/opengl.pri deleted file mode 100644 index ad9d5c79a..000000000 --- a/src/render/renderers/opengl/opengl.pri +++ /dev/null @@ -1,15 +0,0 @@ - -include (renderer/renderer.pri) -include (jobs/jobs.pri) -include (io/io.pri) -include (textures/textures.pri) -include (graphicshelpers/graphicshelpers.pri) -include (renderstates/renderstates.pri) -include (managers/managers.pri) - -!integrity: include (debug/debug.pri) - -gcov { - QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage - QMAKE_LFLAGS += -fprofile-arcs -ftest-coverage -} diff --git a/src/render/renderers/opengl/renderer/glshader.cpp b/src/render/renderers/opengl/renderer/glshader.cpp deleted file mode 100644 index a6f118d65..000000000 --- a/src/render/renderers/opengl/renderer/glshader.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "glshader_p.h" -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -GLShader::GLShader() - : m_isLoaded(false) - , m_graphicsContext(nullptr) -{ - m_shaderCode.resize(static_cast(QShaderProgram::Compute) + 1); -} - -void GLShader::setGraphicsContext(GraphicsContext *context) -{ - QMutexLocker lock(&m_mutex); - m_graphicsContext = context; - if (m_graphicsContext) { - m_contextConnection = QObject::connect(m_graphicsContext->openGLContext(), - &QOpenGLContext::aboutToBeDestroyed, - [this] { setGraphicsContext(nullptr); }); - } -} - -GraphicsContext *GLShader::graphicsContext() -{ - QMutexLocker lock(&m_mutex); - return m_graphicsContext; -} - - -QVector GLShader::uniformsNames() const -{ - return m_uniformsNames; -} - -QVector GLShader::attributesNames() const -{ - return m_attributesNames; -} - -QVector GLShader::uniformBlockNames() const -{ - return m_uniformBlockNames; -} - -QVector GLShader::storageBlockNames() const -{ - return m_shaderStorageBlockNames; -} - -QVector GLShader::shaderCode() const -{ - return m_shaderCode; -} - -QHash GLShader::activeUniformsForUniformBlock(int blockIndex) const -{ - return m_uniformBlockIndexToShaderUniforms.value(blockIndex); -} - -ShaderUniformBlock GLShader::uniformBlockForBlockIndex(int blockIndex) -{ - for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { - if (m_uniformBlocks[i].m_index == blockIndex) { - return m_uniformBlocks[i]; - } - } - return ShaderUniformBlock(); -} - -ShaderUniformBlock GLShader::uniformBlockForBlockNameId(int blockNameId) -{ - for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { - if (m_uniformBlocks[i].m_nameId == blockNameId) { - return m_uniformBlocks[i]; - } - } - return ShaderUniformBlock(); -} - -ShaderUniformBlock GLShader::uniformBlockForBlockName(const QString &blockName) -{ - for (int i = 0, m = m_uniformBlocks.size(); i < m; ++i) { - if (m_uniformBlocks[i].m_name == blockName) { - return m_uniformBlocks[i]; - } - } - return ShaderUniformBlock(); -} - -ShaderStorageBlock GLShader::storageBlockForBlockIndex(int blockIndex) -{ - for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { - if (m_shaderStorageBlocks[i].m_index == blockIndex) - return m_shaderStorageBlocks[i]; - } - return ShaderStorageBlock(); -} - -ShaderStorageBlock GLShader::storageBlockForBlockNameId(int blockNameId) -{ - for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { - if (m_shaderStorageBlocks[i].m_nameId == blockNameId) - return m_shaderStorageBlocks[i]; - } - return ShaderStorageBlock(); -} - -ShaderStorageBlock GLShader::storageBlockForBlockName(const QString &blockName) -{ - for (int i = 0, m = m_shaderStorageBlockNames.size(); i < m; ++i) { - if (m_shaderStorageBlocks[i].m_name == blockName) - return m_shaderStorageBlocks[i]; - } - return ShaderStorageBlock(); -} - -void GLShader::prepareUniforms(ShaderParameterPack &pack) -{ - const PackUniformHash &values = pack.uniforms(); - - auto it = values.keys.cbegin(); - const auto end = values.keys.cend(); - - while (it != end) { - // Find if there's a uniform with the same name id - for (const ShaderUniform &uniform : qAsConst(m_uniforms)) { - if (uniform.m_nameId == *it) { - pack.setSubmissionUniform(uniform); - break; - } - } - ++it; - } -} - -void GLShader::setFragOutputs(const QHash &fragOutputs) -{ - { - QMutexLocker lock(&m_mutex); - m_fragOutputs = fragOutputs; - } -// updateDNA(); -} - -const QHash GLShader::fragOutputs() const -{ - QMutexLocker lock(&m_mutex); - return m_fragOutputs; -} - -void GLShader::initializeUniforms(const QVector &uniformsDescription) -{ - m_uniforms = uniformsDescription; - m_uniformsNames.resize(uniformsDescription.size()); - m_uniformsNamesIds.reserve(uniformsDescription.size()); - m_standardUniformNamesIds.reserve(5); - QHash activeUniformsInDefaultBlock; - - static const QVector standardUniformNameIds = { - Shader::modelMatrixNameId, - Shader::viewMatrixNameId, - Shader::projectionMatrixNameId, - Shader::modelViewMatrixNameId, - Shader::viewProjectionMatrixNameId, - Shader::modelViewProjectionNameId, - Shader::mvpNameId, - Shader::inverseModelMatrixNameId, - Shader::inverseViewMatrixNameId, - Shader::inverseProjectionMatrixNameId, - Shader::inverseModelViewNameId, - Shader::inverseViewProjectionMatrixNameId, - Shader::inverseModelViewProjectionNameId, - Shader::modelNormalMatrixNameId, - Shader::modelViewNormalNameId, - Shader::viewportMatrixNameId, - Shader::inverseViewportMatrixNameId, - Shader::aspectRatioNameId, - Shader::exposureNameId, - Shader::gammaNameId, - Shader::timeNameId, - Shader::eyePositionNameId, - Shader::skinningPaletteNameId, - }; - - for (int i = 0, m = uniformsDescription.size(); i < m; i++) { - m_uniformsNames[i] = m_uniforms[i].m_name; - const int nameId = StringToInt::lookupId(m_uniformsNames[i]); - m_uniforms[i].m_nameId = nameId; - - // Is the uniform a Qt3D "Standard" uniform or a user defined one? - if (standardUniformNameIds.contains(nameId)) - m_standardUniformNamesIds.push_back(nameId); - else - m_uniformsNamesIds.push_back(nameId); - - if (uniformsDescription[i].m_blockIndex == -1) { // Uniform is in default block - qCDebug(Shaders) << "Active Uniform in Default Block " << uniformsDescription[i].m_name << uniformsDescription[i].m_blockIndex; - activeUniformsInDefaultBlock.insert(uniformsDescription[i].m_name, uniformsDescription[i]); - } - } - m_uniformBlockIndexToShaderUniforms.insert(-1, activeUniformsInDefaultBlock); -} - -void GLShader::initializeAttributes(const QVector &attributesDescription) -{ - m_attributes = attributesDescription; - m_attributesNames.resize(attributesDescription.size()); - m_attributeNamesIds.resize(attributesDescription.size()); - for (int i = 0, m = attributesDescription.size(); i < m; i++) { - m_attributesNames[i] = attributesDescription[i].m_name; - m_attributes[i].m_nameId = StringToInt::lookupId(m_attributesNames[i]); - m_attributeNamesIds[i] = m_attributes[i].m_nameId; - qCDebug(Shaders) << "Active Attribute " << attributesDescription[i].m_name; - } -} - -void GLShader::initializeUniformBlocks(const QVector &uniformBlockDescription) -{ - m_uniformBlocks = uniformBlockDescription; - m_uniformBlockNames.resize(uniformBlockDescription.size()); - m_uniformBlockNamesIds.resize(uniformBlockDescription.size()); - for (int i = 0, m = uniformBlockDescription.size(); i < m; ++i) { - m_uniformBlockNames[i] = m_uniformBlocks[i].m_name; - m_uniformBlockNamesIds[i] = StringToInt::lookupId(m_uniformBlockNames[i]); - m_uniformBlocks[i].m_nameId = m_uniformBlockNamesIds[i]; - qCDebug(Shaders) << "Initializing Uniform Block {" << m_uniformBlockNames[i] << "}"; - - // Find all active uniforms for the shader block - QVector::const_iterator uniformsIt = m_uniforms.cbegin(); - const QVector::const_iterator uniformsEnd = m_uniforms.cend(); - - QVector::const_iterator uniformNamesIt = m_uniformsNames.cbegin(); - const QVector::const_iterator uniformNamesEnd = m_attributesNames.cend(); - - QHash activeUniformsInBlock; - - while (uniformsIt != uniformsEnd && uniformNamesIt != uniformNamesEnd) { - if (uniformsIt->m_blockIndex == uniformBlockDescription[i].m_index) { - QString uniformName = *uniformNamesIt; - if (!m_uniformBlockNames[i].isEmpty() && !uniformName.startsWith(m_uniformBlockNames[i])) - uniformName = m_uniformBlockNames[i] + QLatin1Char('.') + *uniformNamesIt; - activeUniformsInBlock.insert(uniformName, *uniformsIt); - qCDebug(Shaders) << "Active Uniform Block " << uniformName << " in block " << m_uniformBlockNames[i] << " at index " << uniformsIt->m_blockIndex; - } - ++uniformsIt; - ++uniformNamesIt; - } - m_uniformBlockIndexToShaderUniforms.insert(uniformBlockDescription[i].m_index, activeUniformsInBlock); - } -} - -void GLShader::initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription) -{ - m_shaderStorageBlocks = shaderStorageBlockDescription; - m_shaderStorageBlockNames.resize(shaderStorageBlockDescription.size()); - m_shaderStorageBlockNamesIds.resize(shaderStorageBlockDescription.size()); - - for (int i = 0, m = shaderStorageBlockDescription.size(); i < m; ++i) { - m_shaderStorageBlockNames[i] = m_shaderStorageBlocks[i].m_name; - m_shaderStorageBlockNamesIds[i] = StringToInt::lookupId(m_shaderStorageBlockNames[i]); - m_shaderStorageBlocks[i].m_nameId =m_shaderStorageBlockNamesIds[i]; - qCDebug(Shaders) << "Initializing Shader Storage Block {" << m_shaderStorageBlockNames[i] << "}"; - } -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/glshader_p.h b/src/render/renderers/opengl/renderer/glshader_p.h deleted file mode 100644 index dec085291..000000000 --- a/src/render/renderers/opengl/renderer/glshader_p.h +++ /dev/null @@ -1,160 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GLSHADER_P_H -#define QT3DRENDER_RENDER_GLSHADER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - - -#include -#include -#include -#include - - -QT_BEGIN_NAMESPACE - -class QOpenGLShaderProgram; - -namespace Qt3DRender { - -namespace Render { - -class Q_AUTOTEST_EXPORT GLShader -{ -public: - GLShader(); - - void setGraphicsContext(GraphicsContext *context); - GraphicsContext *graphicsContext(); - - bool isLoaded() const { return m_isLoaded; } - void setLoaded(bool loaded) { m_isLoaded = loaded; } - - void prepareUniforms(ShaderParameterPack &pack); - - void setFragOutputs(const QHash &fragOutputs); - const QHash fragOutputs() const; - - inline QVector uniformsNamesIds() const { return m_uniformsNamesIds; } - inline QVector standardUniformNameIds() const { return m_standardUniformNamesIds; } - inline QVector uniformBlockNamesIds() const { return m_uniformBlockNamesIds; } - inline QVector storageBlockNamesIds() const { return m_shaderStorageBlockNamesIds; } - inline QVector attributeNamesIds() const { return m_attributeNamesIds; } - - QVector uniformsNames() const; - QVector attributesNames() const; - QVector uniformBlockNames() const; - QVector storageBlockNames() const; - - inline QVector uniforms() const { return m_uniforms; } - inline QVector attributes() const { return m_attributes; } - inline QVector uniformBlocks() const { return m_uniformBlocks; } - inline QVector storageBlocks() const { return m_shaderStorageBlocks; } - - QHash activeUniformsForUniformBlock(int blockIndex) const; - - ShaderUniformBlock uniformBlockForBlockIndex(int blockNameId); - ShaderUniformBlock uniformBlockForBlockNameId(int blockIndex); - ShaderUniformBlock uniformBlockForBlockName(const QString &blockName); - - ShaderStorageBlock storageBlockForBlockIndex(int blockIndex); - ShaderStorageBlock storageBlockForBlockNameId(int blockNameId); - ShaderStorageBlock storageBlockForBlockName(const QString &blockName); - - QOpenGLShaderProgram *shaderProgram() { return &m_shader; } - - void setShaderCode(const QVector shaderCode) { m_shaderCode = shaderCode; } - QVector shaderCode() const; - -private: - bool m_isLoaded; - QOpenGLShaderProgram m_shader; - GraphicsContext *m_graphicsContext; - - QVector m_uniformsNames; - QVector m_uniformsNamesIds; - QVector m_standardUniformNamesIds; - QVector m_uniforms; - - QVector m_attributesNames; - QVector m_attributeNamesIds; - QVector m_attributes; - - QVector m_uniformBlockNames; - QVector m_uniformBlockNamesIds; - QVector m_uniformBlocks; - QHash > m_uniformBlockIndexToShaderUniforms; - - QVector m_shaderStorageBlockNames; - QVector m_shaderStorageBlockNamesIds; - QVector m_shaderStorageBlocks; - - QHash m_fragOutputs; - QVector m_shaderCode; - - // Private so that only GraphicContext can call it - void initializeUniforms(const QVector &uniformsDescription); - void initializeAttributes(const QVector &attributesDescription); - void initializeUniformBlocks(const QVector &uniformBlockDescription); - void initializeShaderStorageBlocks(const QVector &shaderStorageBlockDescription); - - friend class GraphicsContext; - - mutable QMutex m_mutex; - QMetaObject::Connection m_contextConnection; -}; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GLSHADER_P_H diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp b/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp deleted file mode 100644 index 25a850a79..000000000 --- a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "openglvertexarrayobject_p.h" -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -OpenGLVertexArrayObject::OpenGLVertexArrayObject() - : m_ctx(nullptr) - , m_specified(false) - , m_supportsVao(false) -{} - -void OpenGLVertexArrayObject::bind() -{ - Q_ASSERT(m_ctx); - if (m_supportsVao) { - Q_ASSERT(!m_vao.isNull()); - Q_ASSERT(m_vao->isCreated()); - m_vao->bind(); - } else { - // Unbind any other VAO that may have been bound and not released correctly - if (m_ctx->m_currentVAO != nullptr && m_ctx->m_currentVAO != this) - m_ctx->m_currentVAO->release(); - - m_ctx->m_currentVAO = this; - // We need to specify array and vertex attributes - for (const SubmissionContext::VAOVertexAttribute &attr : qAsConst(m_vertexAttributes)) - m_ctx->enableAttribute(attr); - if (!m_indexAttribute.isNull()) - m_ctx->bindGLBuffer(m_ctx->m_renderer->glResourceManagers()->glBufferManager()->data(m_indexAttribute), - GLBuffer::IndexBuffer); - } -} - -void OpenGLVertexArrayObject::release() -{ - Q_ASSERT(m_ctx); - if (m_supportsVao) { - Q_ASSERT(!m_vao.isNull()); - Q_ASSERT(m_vao->isCreated()); - m_vao->release(); - } else { - if (m_ctx->m_currentVAO == this) { - for (const SubmissionContext::VAOVertexAttribute &attr : qAsConst(m_vertexAttributes)) - m_ctx->disableAttribute(attr); - m_ctx->m_currentVAO = nullptr; - } - } -} - -// called from Render thread -void OpenGLVertexArrayObject::create(SubmissionContext *ctx, const VAOIdentifier &key) -{ - QMutexLocker lock(&m_mutex); - - Q_ASSERT(!m_ctx && !m_vao); - - m_ctx = ctx; - m_supportsVao = m_ctx->supportsVAO(); - if (m_supportsVao) { - m_vao.reset(new QOpenGLVertexArrayObject()); - m_vao->create(); - } - m_owners = key; -} - -VAOIdentifier OpenGLVertexArrayObject::key() const -{ - return m_owners; -} - -// called from Render thread -void OpenGLVertexArrayObject::destroy() -{ - QMutexLocker locker(&m_mutex); - - Q_ASSERT(m_ctx); - cleanup(); -} - -void OpenGLVertexArrayObject::cleanup() -{ - m_vao.reset(); - m_ctx = nullptr; - m_specified = false; - m_supportsVao = false; - m_indexAttribute = SubmissionContext::VAOIndexAttribute(); - m_vertexAttributes.clear(); -} - -// called from job -bool OpenGLVertexArrayObject::isAbandoned(GeometryManager *geomMgr, GLShaderManager *shaderMgr) -{ - QMutexLocker lock(&m_mutex); - - if (!m_ctx) - return false; - - const bool geometryExists = (geomMgr->data(m_owners.first) != nullptr); - const bool shaderExists = (shaderMgr->lookupResource(m_owners.second) != nullptr); - - return !geometryExists || !shaderExists; -} - -void OpenGLVertexArrayObject::saveVertexAttribute(const SubmissionContext::VAOVertexAttribute &attr) -{ - // Remove any vertexAttribute already at location - for (auto i = m_vertexAttributes.size() - 1; i >= 0; --i) { - if (m_vertexAttributes.at(i).location == attr.location) { - m_vertexAttributes.removeAt(i); - break; - } - } - m_vertexAttributes.push_back(attr); -} - - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h b/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h deleted file mode 100644 index 362c699da..000000000 --- a/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef OPENGLVERTEXARRAYOBJECT_H -#define OPENGLVERTEXARRAYOBJECT_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -class GeometryManager; -class GLShaderManager; - -typedef QPair VAOIdentifier; - -class OpenGLVertexArrayObject -{ -public: - OpenGLVertexArrayObject(); - - void bind(); - void release(); - - void create(SubmissionContext *ctx, const VAOIdentifier &key); - VAOIdentifier key() const; - void destroy(); - void cleanup(); - - bool isAbandoned(GeometryManager *geomMgr, GLShaderManager *shaderMgr); - - QOpenGLVertexArrayObject *vao() { return m_vao.data(); } - const QOpenGLVertexArrayObject *vao() const { return m_vao.data(); } - - void setSpecified(bool b) { m_specified = b; } - bool isSpecified() const { return m_specified; } - - -private: - QMutex m_mutex; - SubmissionContext *m_ctx; - QScopedPointer m_vao; - bool m_specified; - bool m_supportsVao; - VAOIdentifier m_owners; - - friend class SubmissionContext; - - void saveVertexAttribute(const SubmissionContext::VAOVertexAttribute &attr); - inline void saveIndexAttribute(HGLBuffer glBufferHandle) { m_indexAttribute = glBufferHandle; } - - QVector m_vertexAttributes; - SubmissionContext::VAOIndexAttribute m_indexAttribute; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // OPENGLVERTEXARRAYOBJECT_H diff --git a/src/render/renderers/opengl/renderer/rendercommand.cpp b/src/render/renderers/opengl/renderer/rendercommand.cpp deleted file mode 100644 index c6d42fde1..000000000 --- a/src/render/renderers/opengl/renderer/rendercommand.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "rendercommand_p.h" - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -RenderCommand::RenderCommand() - : m_glShader(nullptr) - , m_stateSet(nullptr) - , m_depth(0.0f) - , m_changeCost(0) - , m_type(RenderCommand::Draw) - , m_primitiveCount(0) - , m_primitiveType(QGeometryRenderer::Triangles) - , m_restartIndexValue(-1) - , m_firstInstance(0) - , m_firstVertex(0) - , m_verticesPerPatch(0) - , m_instanceCount(0) - , m_indexOffset(0) - , m_indexAttributeByteOffset(0) - , m_indexAttributeDataType(GL_UNSIGNED_SHORT) - , m_indirectAttributeByteOffset(0) - , m_drawIndexed(false) - , m_drawIndirect(false) - , m_primitiveRestartEnabled(false) - , m_isValid(false) -{ - m_workGroups[0] = 0; - m_workGroups[1] = 0; - m_workGroups[2] = 0; -} - -bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept -{ - return (a.m_vao == b.m_vao && a.m_glShader == b.m_glShader && a.m_material == b.m_material && - a.m_stateSet == b.m_stateSet && a.m_geometry == b.m_geometry && a.m_geometryRenderer == b.m_geometryRenderer && - a.m_indirectDrawBuffer == b.m_indirectDrawBuffer && a.m_activeAttributes == b.m_activeAttributes && - a.m_depth == b.m_depth && a.m_changeCost == b.m_changeCost && a.m_shaderId == b.m_shaderId && - a.m_workGroups[0] == b.m_workGroups[0] && a.m_workGroups[1] == b.m_workGroups[1] && a.m_workGroups[2] == b.m_workGroups[2] && - a.m_primitiveCount == b.m_primitiveCount && a.m_primitiveType == b.m_primitiveType && a.m_restartIndexValue == b.m_restartIndexValue && - a.m_firstInstance == b.m_firstInstance && a.m_firstVertex == b.m_firstVertex && a.m_verticesPerPatch == b.m_verticesPerPatch && - a.m_instanceCount == b.m_instanceCount && a.m_indexOffset == b.m_indexOffset && a.m_indexAttributeByteOffset == b.m_indexAttributeByteOffset && - a.m_drawIndexed == b.m_drawIndexed && a.m_drawIndirect == b.m_drawIndirect && a.m_primitiveRestartEnabled == b.m_primitiveRestartEnabled && - a.m_isValid == b.m_isValid && a.m_computeCommand == b.m_computeCommand); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/rendercommand_p.h b/src/render/renderers/opengl/renderer/rendercommand_p.h deleted file mode 100644 index 44e34ecfb..000000000 --- a/src/render/renderers/opengl/renderer/rendercommand_p.h +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERCOMMAND_H -#define QT3DRENDER_RENDER_RENDERCOMMAND_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLVertexArrayObject; - -namespace Qt3DRender { - -namespace Render { - -class RenderStateSet; -using RenderStateSetPtr = QSharedPointer; -class GLShader; - -class Q_AUTOTEST_EXPORT RenderCommand -{ -public: - RenderCommand(); - - HVao m_vao; // VAO used during the submission step to store all states and VBOs - HMaterial m_material; // Purely used to ease sorting (minimize stage changes, binding changes ....) - GLShader *m_glShader; // GL Shader to be used at render time - Qt3DCore::QNodeId m_shaderId; // Shader for given pass and mesh - ShaderParameterPack m_parameterPack; // Might need to be reworked so as to be able to destroy the - // Texture while submission is happening. - RenderStateSetPtr m_stateSet; - - HGeometry m_geometry; - HGeometryRenderer m_geometryRenderer; - - HBuffer m_indirectDrawBuffer; // Reference to indirect draw buffer (valid only m_drawIndirect == true) - HComputeCommand m_computeCommand; - - // A QAttribute pack might be interesting - // This is a temporary fix in the meantime, to remove the hacked methods in Technique - QVector m_activeAttributes; - - float m_depth; - int m_changeCost; - - enum CommandType { - Draw, - Compute - }; - - CommandType m_type; - int m_workGroups[3]; - - // Values filled for draw calls by Renderer (in prepare Submission) - GLsizei m_primitiveCount; - QGeometryRenderer::PrimitiveType m_primitiveType; - int m_restartIndexValue; - int m_firstInstance; - int m_firstVertex; - int m_verticesPerPatch; - int m_instanceCount; - int m_indexOffset; - uint m_indexAttributeByteOffset; - GLint m_indexAttributeDataType; - uint m_indirectAttributeByteOffset; - bool m_drawIndexed; - bool m_drawIndirect; - bool m_primitiveRestartEnabled; - bool m_isValid; -}; - -Q_AUTOTEST_EXPORT bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept; - -inline bool operator!=(const RenderCommand &lhs, const RenderCommand &rhs) noexcept -{ return !operator==(lhs, rhs); } - -struct EntityRenderCommandData -{ - QVector entities; - QVector commands; - QVector passesData; - - void reserve(int size) - { - entities.reserve(size); - commands.reserve(size); - passesData.reserve(size); - } - - inline int size() const { return entities.size(); } - - inline void push_back(Entity *e, const RenderCommand &c, const RenderPassParameterData &p) - { - entities.push_back(e); - commands.push_back(c); - passesData.push_back(p); - } - - inline void push_back(Entity *e, RenderCommand &&c, RenderPassParameterData &&p) - { - entities.push_back(e); - commands.push_back(std::move(c)); - passesData.push_back(std::move(p)); - } - - EntityRenderCommandData &operator+=(EntityRenderCommandData &&t) - { - entities += std::move(t.entities); - commands += std::move(t.commands); - passesData += std::move(t.passesData); - return *this; - } - -}; - -using EntityRenderCommandDataPtr = QSharedPointer; - - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERCOMMAND_H diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/render/renderers/opengl/renderer/renderer.cpp deleted file mode 100644 index 680040f54..000000000 --- a/src/render/renderers/opengl/renderer/renderer.cpp +++ /dev/null @@ -1,2458 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderer_p.h" - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifndef Q_OS_INTEGRITY -#include -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -QT_BEGIN_NAMESPACE - -// Crashes on AMD Radeon drivers on Windows. Disable for now. -//#define SHADER_LOADING_IN_COMMAND_THREAD - -using namespace Qt3DCore; - -namespace Qt3DRender { -namespace Render { - -namespace { - -class SyncLightsGatherer -{ -public: - explicit SyncLightsGatherer(LightGathererPtr gatherJob, - RendererCache *cache) - : m_gatherJob(gatherJob) - , m_cache(cache) - { - } - - void operator()() - { - QMutexLocker lock(m_cache->mutex()); - m_cache->gatheredLights = m_gatherJob->lights(); - m_cache->environmentLight = m_gatherJob->takeEnvironmentLight(); - } - -private: - LightGathererPtr m_gatherJob; - RendererCache *m_cache; -}; - -class SyncRenderableEntities -{ -public: - explicit SyncRenderableEntities(RenderableEntityFilterPtr gatherJob, - RendererCache *cache) - : m_gatherJob(gatherJob) - , m_cache(cache) - { - } - - void operator()() - { - QVector selectedEntities = m_gatherJob->filteredEntities(); - std::sort(selectedEntities.begin(), selectedEntities.end()); - - QMutexLocker lock(m_cache->mutex()); - m_cache->renderableEntities = selectedEntities; - } - -private: - RenderableEntityFilterPtr m_gatherJob; - RendererCache *m_cache; -}; - -class SyncComputableEntities -{ -public: - explicit SyncComputableEntities(ComputableEntityFilterPtr gatherJob, - RendererCache *cache) - : m_gatherJob(gatherJob) - , m_cache(cache) - { - } - - void operator()() - { - QVector selectedEntities = m_gatherJob->filteredEntities(); - std::sort(selectedEntities.begin(), selectedEntities.end()); - - QMutexLocker lock(m_cache->mutex()); - m_cache->computeEntities = selectedEntities; - } - -private: - ComputableEntityFilterPtr m_gatherJob; - RendererCache *m_cache; -}; - -} // anonymous - - -/*! - \internal - - Renderer shutdown procedure: - - Since the renderer relies on the surface and OpenGLContext to perform its cleanup, - it is shutdown when the surface is set to nullptr - - When the surface is set to nullptr this will request the RenderThread to terminate - and will prevent createRenderBinJobs from returning a set of jobs as there is nothing - more to be rendered. - - In turn, this will call shutdown which will make the OpenGL context current one last time - to allow cleanups requiring a call to QOpenGLContext::currentContext to execute properly. - At the end of that function, the GraphicsContext is set to null. - - At this point though, the QAspectThread is still running its event loop and will only stop - a short while after. - */ - -Renderer::Renderer(QRenderAspect::RenderType type) - : m_services(nullptr) - , m_nodesManager(nullptr) - , m_renderSceneRoot(nullptr) - , m_defaultRenderStateSet(nullptr) - , m_submissionContext(nullptr) - , m_renderQueue(new RenderQueue()) - , m_renderThread(type == QRenderAspect::Threaded ? new RenderThread(this) : nullptr) - , m_vsyncFrameAdvanceService(new VSyncFrameAdvanceService(m_renderThread != nullptr)) - , m_waitForInitializationToBeCompleted(0) - , m_hasBeenInitializedMutex() - , m_pickEventFilter(new PickEventFilter()) - , m_exposed(0) - , m_lastFrameCorrect(0) - , m_glContext(nullptr) - , m_shareContext(nullptr) - , m_pickBoundingVolumeJob(PickBoundingVolumeJobPtr::create()) - , m_rayCastingJob(RayCastingJobPtr::create()) - , m_time(0) - , m_settings(nullptr) - , m_updateShaderDataTransformJob(Render::UpdateShaderDataTransformJobPtr::create()) - , m_cleanupJob(Render::FrameCleanupJobPtr::create()) - , m_worldTransformJob(Render::UpdateWorldTransformJobPtr::create()) - , m_expandBoundingVolumeJob(Render::ExpandBoundingVolumeJobPtr::create()) - , m_calculateBoundingVolumeJob(Render::CalculateBoundingVolumeJobPtr::create()) - , m_updateWorldBoundingVolumeJob(Render::UpdateWorldBoundingVolumeJobPtr::create()) - , m_updateTreeEnabledJob(Render::UpdateTreeEnabledJobPtr::create()) - , m_sendBufferCaptureJob(Render::SendBufferCaptureJobPtr::create()) - , m_updateSkinningPaletteJob(Render::UpdateSkinningPaletteJobPtr::create()) - , m_updateLevelOfDetailJob(Render::UpdateLevelOfDetailJobPtr::create()) - , m_updateMeshTriangleListJob(Render::UpdateMeshTriangleListJobPtr::create()) - , m_filterCompatibleTechniqueJob(Render::FilterCompatibleTechniqueJobPtr::create()) - , m_updateEntityLayersJob(Render::UpdateEntityLayersJobPtr::create()) - , m_lightGathererJob(Render::LightGathererPtr::create()) - , m_renderableEntityFilterJob(Render::RenderableEntityFilterPtr::create()) - , m_computableEntityFilterJob(Render::ComputableEntityFilterPtr::create()) - , m_bufferGathererJob(SynchronizerJobPtr::create([this] { lookForDirtyBuffers(); }, JobTypes::DirtyBufferGathering)) - , m_vaoGathererJob(SynchronizerJobPtr::create([this] { lookForAbandonedVaos(); }, JobTypes::DirtyVaoGathering)) - , m_textureGathererJob(SynchronizerJobPtr::create([this] { lookForDirtyTextures(); }, JobTypes::DirtyTextureGathering)) - , m_sendSetFenceHandlesToFrontendJob(SynchronizerJobPtr::create([this] { sendSetFenceHandlesToFrontend(); }, JobTypes::SendSetFenceHandlesToFrontend)) - , m_introspectShaderJob(SynchronizerPostFramePtr::create([this] { reloadDirtyShaders(); }, - [this] (Qt3DCore::QAspectManager *m) { sendShaderChangesToFrontend(m); }, - JobTypes::DirtyShaderGathering)) - , m_syncLoadingJobs(SynchronizerJobPtr::create([] {}, JobTypes::SyncLoadingJobs)) - , m_cacheRenderableEntitiesJob(SynchronizerJobPtr::create(SyncRenderableEntities(m_renderableEntityFilterJob, &m_cache), - JobTypes::EntityComponentTypeFiltering)) - , m_cacheComputableEntitiesJob(SynchronizerJobPtr::create(SyncComputableEntities(m_computableEntityFilterJob, &m_cache), - JobTypes::EntityComponentTypeFiltering)) - , m_cacheLightsJob(SynchronizerJobPtr::create(SyncLightsGatherer(m_lightGathererJob, &m_cache), - JobTypes::EntityComponentTypeFiltering)) - , m_ownedContext(false) - , m_offscreenHelper(nullptr) - , m_glResourceManagers(nullptr) - , m_commandExecuter(new Qt3DRender::Debug::CommandExecuter(this)) - , m_shouldSwapBuffers(true) - , m_imGuiRenderer(nullptr) - , m_jobsInLastFrame(0) -{ - // Set renderer as running - it will wait in the context of the - // RenderThread for RenderViews to be submitted - m_running.fetchAndStoreOrdered(1); - if (m_renderThread) - m_renderThread->waitForStart(); - - // Create jobs to update transforms and bounding volumes - // We can only update bounding volumes once all world transforms are known - m_updateWorldBoundingVolumeJob->addDependency(m_worldTransformJob); - m_updateWorldBoundingVolumeJob->addDependency(m_calculateBoundingVolumeJob); - m_expandBoundingVolumeJob->addDependency(m_updateWorldBoundingVolumeJob); - m_updateShaderDataTransformJob->addDependency(m_worldTransformJob); - m_pickBoundingVolumeJob->addDependency(m_expandBoundingVolumeJob); - m_rayCastingJob->addDependency(m_expandBoundingVolumeJob); - // m_calculateBoundingVolumeJob's dependency on m_updateTreeEnabledJob is set in renderBinJobs - - // Ensures all skeletons are loaded before we try to update them - m_updateSkinningPaletteJob->addDependency(m_syncLoadingJobs); - - // All world stuff depends on the RenderEntity's localBoundingVolume - m_updateLevelOfDetailJob->addDependency(m_updateMeshTriangleListJob); - m_pickBoundingVolumeJob->addDependency(m_updateMeshTriangleListJob); - m_rayCastingJob->addDependency(m_updateMeshTriangleListJob); - - m_introspectShaderJob->addDependency(m_filterCompatibleTechniqueJob); - - m_cacheLightsJob->addDependency(m_lightGathererJob); - m_cacheRenderableEntitiesJob->addDependency(m_renderableEntityFilterJob); - m_cacheComputableEntitiesJob->addDependency(m_computableEntityFilterJob); - - m_filterCompatibleTechniqueJob->setRenderer(this); - - m_defaultRenderStateSet = new RenderStateSet; - m_defaultRenderStateSet->addState(StateVariant::createState(GL_LESS)); - m_defaultRenderStateSet->addState(StateVariant::createState(GL_BACK)); - m_defaultRenderStateSet->addState(StateVariant::createState(true, true, true, true)); -} - -Renderer::~Renderer() -{ - Q_ASSERT(m_running.fetchAndStoreOrdered(0) == 0); - if (m_renderThread) - Q_ASSERT(m_renderThread->isFinished()); - - delete m_renderQueue; - delete m_defaultRenderStateSet; - delete m_glResourceManagers; - - if (!m_ownedContext) - QObject::disconnect(m_contextConnection); - -#ifndef Q_OS_INTEGRITY - delete m_imGuiRenderer; -#endif -} - -void Renderer::dumpInfo() const -{ - qDebug() << Q_FUNC_INFO << "t =" << m_time; - - const ShaderManager *shaderManager = m_nodesManager->shaderManager(); - qDebug() << "=== Shader Manager ==="; - qDebug() << *shaderManager; - - const TextureManager *textureManager = m_nodesManager->textureManager(); - qDebug() << "=== Texture Manager ==="; - qDebug() << *textureManager; - - const TextureImageManager *textureImageManager = m_nodesManager->textureImageManager(); - qDebug() << "=== Texture Image Manager ==="; - qDebug() << *textureImageManager; -} - -qint64 Renderer::time() const -{ - return m_time; -} - -void Renderer::setTime(qint64 time) -{ - m_time = time; -} - -void Renderer::setJobsInLastFrame(int jobsInLastFrame) -{ - m_jobsInLastFrame = jobsInLastFrame; -} - -void Renderer::setNodeManagers(NodeManagers *managers) -{ - m_nodesManager = managers; - m_glResourceManagers = new GLResourceManagers(); - m_scene2DResourceAccessor.reset(new ResourceAccessor(this, m_nodesManager)); - - m_updateShaderDataTransformJob->setManagers(m_nodesManager); - m_cleanupJob->setManagers(m_nodesManager); - m_calculateBoundingVolumeJob->setManagers(m_nodesManager); - m_expandBoundingVolumeJob->setManagers(m_nodesManager); - m_worldTransformJob->setManagers(m_nodesManager); - m_pickBoundingVolumeJob->setManagers(m_nodesManager); - m_rayCastingJob->setManagers(m_nodesManager); - m_updateWorldBoundingVolumeJob->setManager(m_nodesManager->renderNodesManager()); - m_updateLevelOfDetailJob->setManagers(m_nodesManager); - m_updateSkinningPaletteJob->setManagers(m_nodesManager); - m_updateMeshTriangleListJob->setManagers(m_nodesManager); - m_filterCompatibleTechniqueJob->setManager(m_nodesManager->techniqueManager()); - m_updateEntityLayersJob->setManager(m_nodesManager); - m_updateTreeEnabledJob->setManagers(m_nodesManager); - m_sendBufferCaptureJob->setManagers(m_nodesManager); - m_lightGathererJob->setManager(m_nodesManager->renderNodesManager()); - m_renderableEntityFilterJob->setManager(m_nodesManager->renderNodesManager()); - m_computableEntityFilterJob->setManager(m_nodesManager->renderNodesManager()); -} - -void Renderer::setServices(QServiceLocator *services) -{ - m_services = services; - - m_nodesManager->sceneManager()->setDownloadService(m_services->downloadHelperService()); -} - -NodeManagers *Renderer::nodeManagers() const -{ - return m_nodesManager; -} - -/*! - \internal - - Return context which can be used to share resources safely - with qt3d main render context. -*/ -QOpenGLContext *Renderer::shareContext() const -{ - QMutexLocker lock(&m_shareContextMutex); - return m_shareContext ? m_shareContext - : (m_submissionContext->openGLContext() - ? m_submissionContext->openGLContext()->shareContext() - : nullptr); -} - -// Executed in the reloadDirtyShader job -void Renderer::loadShader(Shader *shader, HShader shaderHandle) -{ - Q_UNUSED(shader); - if (!m_dirtyShaders.contains(shaderHandle)) - m_dirtyShaders.push_back(shaderHandle); -} - -void Renderer::setOpenGLContext(QOpenGLContext *context) -{ - m_glContext = context; -} - -void Renderer::setScreen(QScreen *scr) -{ - m_screen = scr; -} - -QScreen *Renderer::screen() const -{ - return m_screen; -} - -bool Renderer::accessOpenGLTexture(Qt3DCore::QNodeId nodeId, - QOpenGLTexture **texture, - QMutex **lock, - bool readonly) -{ - Texture *tex = m_nodesManager->textureManager()->lookupResource(nodeId); - if (!tex) - return false; - - GLTexture *glTex = m_glResourceManagers->glTextureManager()->lookupResource(tex->peerId()); - if (!glTex) - return false; - - if (glTex->isDirty()) - return false; - - if (!readonly) - glTex->setExternalRenderingEnabled(true); - - GLTexture::TextureUpdateInfo texInfo = glTex->createOrUpdateGLTexture(); - *texture = texInfo.texture; - - if (!readonly) - *lock = glTex->externalRenderingLock(); - - return true; -} - -QSharedPointer Renderer::resourceAccessor() const -{ - return m_scene2DResourceAccessor; -} - -// Called in RenderThread context by the run method of RenderThread -// RenderThread has locked the mutex already and unlocks it when this -// method termintates -void Renderer::initialize() -{ - QMutexLocker lock(&m_hasBeenInitializedMutex); - m_submissionContext.reset(new SubmissionContext); - m_submissionContext->setRenderer(this); - - QOpenGLContext* ctx = m_glContext; - - { - QMutexLocker lock(&m_shareContextMutex); - // If we are using our own context (not provided by QtQuick), - // we need to create it - if (!m_glContext) { - ctx = new QOpenGLContext; - if (m_screen) - ctx->setScreen(m_screen); - ctx->setShareContext(qt_gl_global_share_context()); - - // TO DO: Shouldn't we use the highest context available and trust - // QOpenGLContext to fall back on the best lowest supported ? - const QByteArray debugLoggingMode = qgetenv("QT3DRENDER_DEBUG_LOGGING"); - - if (!debugLoggingMode.isEmpty()) { - QSurfaceFormat sf = ctx->format(); - sf.setOption(QSurfaceFormat::DebugContext); - ctx->setFormat(sf); - } - - // Create OpenGL context - if (ctx->create()) - qCDebug(Backend) << "OpenGL context created with actual format" << ctx->format(); - else - qCWarning(Backend) << Q_FUNC_INFO << "OpenGL context creation failed"; - m_ownedContext = true; - - QObject::connect(m_glContext, &QOpenGLContext::aboutToBeDestroyed, - [this] { m_frameProfiler.reset(); }); - } else { - // Context is not owned by us, so we need to know if it gets destroyed - m_contextConnection = QObject::connect(m_glContext, &QOpenGLContext::aboutToBeDestroyed, - [this] { releaseGraphicsResources(); }); - } - - qCDebug(Backend) << "Qt3D shared context:" << ctx->shareContext(); - qCDebug(Backend) << "Qt global shared context:" << qt_gl_global_share_context(); - - if (!ctx->shareContext()) { - m_shareContext = new QOpenGLContext; - if (ctx->screen()) - m_shareContext->setScreen(ctx->screen()); - m_shareContext->setFormat(ctx->format()); - m_shareContext->setShareContext(ctx); - m_shareContext->create(); - } - - // Note: we don't have a surface at this point - // The context will be made current later on (at render time) - m_submissionContext->setOpenGLContext(ctx); - - // Store the format used by the context and queue up creating an - // offscreen surface in the main thread so that it is available - // for use when we want to shutdown the renderer. We need to create - // the offscreen surface on the main thread because on some platforms - // (MS Windows), an offscreen surface is just a hidden QWindow. - m_format = ctx->format(); - QMetaObject::invokeMethod(m_offscreenHelper, "createOffscreenSurface"); - } - - // Awake setScenegraphRoot in case it was waiting - m_waitForInitializationToBeCompleted.release(1); - // Allow the aspect manager to proceed - m_vsyncFrameAdvanceService->proceedToNextFrame(); - - // Force initial refresh - markDirty(AllDirty, nullptr); -} - -/*! - * \internal - * - * Signals for the renderer to stop rendering. If a threaded renderer is in use, - * the render thread will call releaseGraphicsResources() just before the thread exits. - * If rendering synchronously, this function will call releaseGraphicsResources(). - */ -void Renderer::shutdown() -{ - // Ensure we have waited to be fully initialized before trying to shut down - // (in case initialization is taking place at the same time) - QMutexLocker lock(&m_hasBeenInitializedMutex); - - qCDebug(Backend) << Q_FUNC_INFO << "Requesting renderer shutdown"; - m_running.storeRelaxed(0); - - // We delete any renderqueue that we may not have had time to render - // before the surface was destroyed - QMutexLocker lockRenderQueue(m_renderQueue->mutex()); - qDeleteAll(m_renderQueue->nextFrameQueue()); - m_renderQueue->reset(); - lockRenderQueue.unlock(); - - if (!m_renderThread) { - releaseGraphicsResources(); - } else { - // Wake up the render thread in case it is waiting for some renderviews - // to be ready. The isReadyToSubmit() function checks for a shutdown - // having been requested. - m_submitRenderViewsSemaphore.release(1); - m_renderThread->wait(); - } - - // Destroy internal managers - // This needs to be done before the nodeManager is destroy - // as the internal resources might somehow rely on nodeManager resources - delete m_glResourceManagers; - m_glResourceManagers = nullptr; -} - -/*! - \internal - - When using a threaded renderer this function is called in the context of the - RenderThread to do any shutdown and cleanup that needs to be performed in the - thread where the OpenGL context lives. - - When using Scene3D or anything that provides a custom QOpenGLContext (not - owned by Qt3D) this function is called whenever the signal - QOpenGLContext::aboutToBeDestroyed is emitted. In that case this function - is called in the context of the emitter's thread. -*/ -void Renderer::releaseGraphicsResources() -{ - // We may get called twice when running inside of a Scene3D. Once when Qt Quick - // wants to shutdown, and again when the render aspect gets unregistered. So - // check that we haven't already cleaned up before going any further. - if (!m_submissionContext) - return; - - // Try to temporarily make the context current so we can free up any resources - QMutexLocker locker(&m_offscreenSurfaceMutex); - QOffscreenSurface *offscreenSurface = m_offscreenHelper->offscreenSurface(); - if (!offscreenSurface) { - qWarning() << "Failed to make context current: OpenGL resources will not be destroyed"; - // We still need to delete the submission context - m_submissionContext.reset(nullptr); - return; - } - - QOpenGLContext *context = m_submissionContext->openGLContext(); - Q_ASSERT(context); - - if (context->thread() == QThread::currentThread() && context->makeCurrent(offscreenSurface)) { - - // Clean up the graphics context and any resources - const QVector activeTexturesHandles = m_glResourceManagers->glTextureManager()->activeHandles(); - for (const HGLTexture &textureHandle : activeTexturesHandles) { - GLTexture *tex = m_glResourceManagers->glTextureManager()->data(textureHandle); - tex->destroy(); - } - - // Do the same thing with buffers - const QVector activeBuffers = m_glResourceManagers->glBufferManager()->activeHandles(); - for (const HGLBuffer &bufferHandle : activeBuffers) { - GLBuffer *buffer = m_glResourceManagers->glBufferManager()->data(bufferHandle); - buffer->destroy(m_submissionContext.data()); - } - - // Do the same thing with shaders - const QVector shaders = m_glResourceManagers->glShaderManager()->takeActiveResources(); - qDeleteAll(shaders); - - // Do the same thing with VAOs - const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); - for (const HVao &vaoHandle : activeVaos) { - OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(vaoHandle); - vao->destroy(); - } - - m_frameProfiler.reset(); - context->doneCurrent(); - } else { - qWarning() << "Failed to make context current: OpenGL resources will not be destroyed"; - } - - if (m_ownedContext) - delete context; - if (m_shareContext) - delete m_shareContext; - - m_submissionContext.reset(nullptr); - qCDebug(Backend) << Q_FUNC_INFO << "Renderer properly shutdown"; -} - -void Renderer::setSurfaceExposed(bool exposed) -{ - qCDebug(Backend) << "Window exposed: " << exposed; - m_exposed.fetchAndStoreOrdered(exposed); -} - -Render::FrameGraphNode *Renderer::frameGraphRoot() const -{ - Q_ASSERT(m_settings); - if (m_nodesManager && m_nodesManager->frameGraphManager() && m_settings) - return m_nodesManager->frameGraphManager()->lookupNode(m_settings->activeFrameGraphID()); - return nullptr; -} - -// QAspectThread context -// Order of execution : -// 1) RenderThread is created -> release 1 of m_waitForInitializationToBeCompleted when started -// 2) setSceneRoot waits to acquire initialization -// 3) submitRenderView -> check for surface -// -> make surface current + create proper glHelper if needed -void Renderer::setSceneRoot(Entity *sgRoot) -{ - Q_ASSERT(sgRoot); - - // If initialization hasn't been completed we must wait - m_waitForInitializationToBeCompleted.acquire(); - - m_renderSceneRoot = sgRoot; - if (!m_renderSceneRoot) - qCWarning(Backend) << "Failed to build render scene"; - m_renderSceneRoot->dump(); - qCDebug(Backend) << Q_FUNC_INFO << "DUMPING SCENE"; - - // Set the scene root on the jobs - m_worldTransformJob->setRoot(m_renderSceneRoot); - m_expandBoundingVolumeJob->setRoot(m_renderSceneRoot); - m_calculateBoundingVolumeJob->setRoot(m_renderSceneRoot); - m_cleanupJob->setRoot(m_renderSceneRoot); - m_pickBoundingVolumeJob->setRoot(m_renderSceneRoot); - m_rayCastingJob->setRoot(m_renderSceneRoot); - m_updateLevelOfDetailJob->setRoot(m_renderSceneRoot); - m_updateSkinningPaletteJob->setRoot(m_renderSceneRoot); - m_updateTreeEnabledJob->setRoot(m_renderSceneRoot); - - // Set all flags to dirty - m_dirtyBits.marked |= AbstractRenderer::AllDirty; -} - -void Renderer::registerEventFilter(QEventFilterService *service) -{ - qCDebug(Backend) << Q_FUNC_INFO << QThread::currentThread(); - service->registerEventFilter(m_pickEventFilter.data(), 1024); -} - -void Renderer::setSettings(RenderSettings *settings) -{ - m_settings = settings; -} - -RenderSettings *Renderer::settings() const -{ - return m_settings; -} - -void Renderer::render() -{ - // Traversing the framegraph tree from root to lead node - // Allows us to define the rendering set up - // Camera, RenderTarget ... - - // Utimately the renderer should be a framework - // For the processing of the list of renderviews - - // Matrice update, bounding volumes computation ... - // Should be jobs - - // namespace Qt3DCore has 2 distincts node trees - // One scene description - // One framegraph description - - while (m_running.loadRelaxed() > 0) { - doRender(); - // TO DO: Restore windows exposed detection - // Probably needs to happens some place else though - } -} - -// Either called by render if Qt3D is in charge of the RenderThread -// or by QRenderAspectPrivate::renderSynchronous (for Scene3D) -void Renderer::doRender(bool swapBuffers) -{ - Renderer::ViewSubmissionResultData submissionData; - bool hasCleanedQueueAndProceeded = false; - bool preprocessingComplete = false; - bool beganDrawing = false; - - // Blocking until RenderQueue is full - const bool canSubmit = isReadyToSubmit(); - m_shouldSwapBuffers = swapBuffers; - - // Lock the mutex to protect access to the renderQueue while we look for its state - QMutexLocker locker(m_renderQueue->mutex()); - const bool queueIsComplete = m_renderQueue->isFrameQueueComplete(); - const bool queueIsEmpty = m_renderQueue->targetRenderViewCount() == 0; - - // When using synchronous rendering (QtQuick) - // We are not sure that the frame queue is actually complete - // Since a call to render may not be synched with the completions - // of the RenderViewJobs - // In such a case we return early, waiting for a next call with - // the frame queue complete at this point - - // RenderQueue is complete (but that means it may be of size 0) - if (canSubmit && (queueIsComplete && !queueIsEmpty)) { - const QVector renderViews = m_renderQueue->nextFrameQueue(); - QTaskLogger submissionStatsPart1(m_services->systemInformation(), - {JobTypes::FrameSubmissionPart1, 0}, - QTaskLogger::Submission); - QTaskLogger submissionStatsPart2(m_services->systemInformation(), - {JobTypes::FrameSubmissionPart2, 0}, - QTaskLogger::Submission); - - if (canRender()) { - { // Scoped to destroy surfaceLock - QSurface *surface = nullptr; - for (const Render::RenderView *rv: renderViews) { - surface = rv->surface(); - if (surface) - break; - } - - SurfaceLocker surfaceLock(surface); - const bool surfaceIsValid = (surface && surfaceLock.isSurfaceValid()); - if (surfaceIsValid) { - // Reset state for each draw if we don't have complete control of the context - if (!m_ownedContext) - m_submissionContext->setCurrentStateSet(nullptr); - beganDrawing = m_submissionContext->beginDrawing(surface); - if (beganDrawing) { - // 1) Execute commands for buffer uploads, texture updates, shader loading first - updateGLResources(); - // 2) Update VAO and copy data into commands to allow concurrent submission - prepareCommandsSubmission(renderViews); - preprocessingComplete = true; - - // Purge shader which aren't used any longer - static int callCount = 0; - ++callCount; - const int shaderPurgePeriod = 600; - if (callCount % shaderPurgePeriod == 0) - m_glResourceManagers->glShaderManager()->purge(); - } - } - } - // 2) Proceed to next frame and start preparing frame n + 1 - m_renderQueue->reset(); - locker.unlock(); // Done protecting RenderQueue - m_vsyncFrameAdvanceService->proceedToNextFrame(); - hasCleanedQueueAndProceeded = true; - - // Only try to submit the RenderViews if the preprocessing was successful - // This part of the submission is happening in parallel to the RV building for the next frame - if (preprocessingComplete) { - submissionStatsPart1.end(submissionStatsPart2.restart()); - - // 3) Submit the render commands for frame n (making sure we never reference something that could be changing) - // Render using current device state and renderer configuration - submissionData = submitRenderViews(renderViews); - - // Perform any required cleanup of the Graphics resources (Buffers deleted, Shader deleted...) - cleanGraphicsResources(); - } - } - - // Execute the pending shell commands - m_commandExecuter->performAsynchronousCommandExecution(renderViews); - - // Delete all the RenderViews which will clear the allocators - // that were used for their allocation - qDeleteAll(renderViews); - - if (preprocessingComplete && activeProfiler()) - m_frameProfiler->writeResults(); - } - - // If hasCleanedQueueAndProceeded isn't true this implies that something went wrong - // with the rendering and/or the renderqueue is incomplete from some reason - // or alternatively it could be complete but empty (RenderQueue of size 0) - - if (!hasCleanedQueueAndProceeded) { - // RenderQueue was full but something bad happened when - // trying to render it and therefore proceedToNextFrame was not called - // Note: in this case the renderQueue mutex is still locked - - // Reset the m_renderQueue so that we won't try to render - // with a queue used by a previous frame with corrupted content - // if the current queue was correctly submitted - m_renderQueue->reset(); - - // We allow the RenderTickClock service to proceed to the next frame - // In turn this will allow the aspect manager to request a new set of jobs - // to be performed for each aspect - m_vsyncFrameAdvanceService->proceedToNextFrame(); - } - - // Perform the last swapBuffers calls after the proceedToNextFrame - // as this allows us to gain a bit of time for the preparation of the - // next frame - // Finish up with last surface used in the list of RenderViews - if (beganDrawing) { - SurfaceLocker surfaceLock(submissionData.surface); - // Finish up with last surface used in the list of RenderViews - const bool swapBuffers = submissionData.lastBoundFBOId == m_submissionContext->defaultFBO() - && surfaceLock.isSurfaceValid() - && m_shouldSwapBuffers; - m_submissionContext->endDrawing(swapBuffers); - } -} - -// Called by RenderViewJobs -// When the frameQueue is complete and we are using a renderThread -// we allow the render thread to proceed -void Renderer::enqueueRenderView(Render::RenderView *renderView, int submitOrder) -{ - QMutexLocker locker(m_renderQueue->mutex()); // Prevent out of order execution - // We cannot use a lock free primitive here because: - // - QVector is not thread safe - // - Even if the insert is made correctly, the isFrameComplete call - // could be invalid since depending on the order of execution - // the counter could be complete but the renderview not yet added to the - // buffer depending on whichever order the cpu decides to process this - const bool isQueueComplete = m_renderQueue->queueRenderView(renderView, submitOrder); - locker.unlock(); // We're done protecting the queue at this point - if (isQueueComplete) { - if (m_renderThread && m_running.loadRelaxed()) - Q_ASSERT(m_submitRenderViewsSemaphore.available() == 0); - m_submitRenderViewsSemaphore.release(1); - } -} - -bool Renderer::canRender() const - -{ - // Make sure that we've not been told to terminate - if (m_renderThread && !m_running.loadRelaxed()) { - qCDebug(Rendering) << "RenderThread termination requested whilst waiting"; - return false; - } - - // TO DO: Check if all surfaces have been destroyed... - // It may be better if the last window to be closed trigger a call to shutdown - // Rather than having checks for the surface everywhere - - return true; -} - -Profiling::FrameProfiler *Renderer::activeProfiler() const -{ - if (m_services && m_services->systemInformation()->isGraphicsTraceEnabled()) { - if (m_frameProfiler.isNull()) - m_frameProfiler.reset(new Profiling::FrameProfiler(m_services->systemInformation())); - - return m_frameProfiler.data(); - } - - return nullptr; -} - -bool Renderer::isReadyToSubmit() -{ - // Make sure that we've been told to render before rendering - // Prevent ouf of order execution - m_submitRenderViewsSemaphore.acquire(1); - - // Check if shutdown has been requested - if (m_running.loadRelaxed() == 0) - return false; - - // The semaphore should only - // be released when the frame queue is complete and there's - // something to render - // The case of shutdown should have been handled just before - Q_ASSERT(m_renderQueue->isFrameQueueComplete()); - return true; -} - -// Main thread -QVariant Renderer::executeCommand(const QStringList &args) -{ - return m_commandExecuter->executeCommand(args); -} - -/*! - \internal - Called in the context of the aspect thread from QRenderAspect::onRegistered -*/ -void Renderer::setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) -{ - QMutexLocker locker(&m_offscreenSurfaceMutex); - m_offscreenHelper = helper; -} - -QSurfaceFormat Renderer::format() -{ - return m_format; -} - -// When this function is called, we must not be processing the commands for frame n+1 -void Renderer::prepareCommandsSubmission(const QVector &renderViews) -{ - OpenGLVertexArrayObject *vao = nullptr; - QHash updatedTable; - - for (RenderView *rv: renderViews) { - QVector &commands = rv->commands(); - for (RenderCommand &command : commands) { - // Update/Create VAO - if (command.m_type == RenderCommand::Draw) { - Geometry *rGeometry = m_nodesManager->data(command.m_geometry); - GeometryRenderer *rGeometryRenderer = m_nodesManager->data(command.m_geometryRenderer); - GLShader *shader = command.m_glShader; - - // We should never have inserted a command for which these are null - // in the first place - Q_ASSERT(rGeometry && rGeometryRenderer && shader); - - // The VAO should be created only once for a QGeometry and a ShaderProgram - // Manager should have a VAO Manager that are indexed by QMeshData and Shader - // RenderCommand should have a handle to the corresponding VAO for the Mesh and Shader - HVao vaoHandle; - - // Create VAO or return already created instance associated with command shader/geometry - // (VAO is emulated if not supported) - createOrUpdateVAO(&command, &vaoHandle, &vao); - command.m_vao = vaoHandle; - - // Avoids redoing the same thing for the same VAO - if (!updatedTable.contains(vaoHandle)) { - updatedTable.insert(vaoHandle, true); - - // Do we have any attributes that are dirty ? - const bool requiresPartialVAOUpdate = requiresVAOAttributeUpdate(rGeometry, &command); - - // If true, we need to reupload all attributes to set the VAO - // Otherwise only dirty attributes will be updates - const bool requiresFullVAOUpdate = (!vao->isSpecified()) || (rGeometry->isDirty() || rGeometryRenderer->isDirty()); - - // Append dirty Geometry to temporary vector - // so that its dirtiness can be unset later - if (rGeometry->isDirty()) - m_dirtyGeometry.push_back(rGeometry); - - if (!command.m_activeAttributes.isEmpty() && (requiresFullVAOUpdate || requiresPartialVAOUpdate)) { - Profiling::GLTimeRecorder recorder(Profiling::VAOUpload, activeProfiler()); - // Activate shader - m_submissionContext->activateShader(shader); - // Bind VAO - vao->bind(); - // Update or set Attributes and Buffers for the given rGeometry and Command - // Note: this fills m_dirtyAttributes as well - if (updateVAOWithAttributes(rGeometry, &command, shader, requiresFullVAOUpdate)) - vao->setSpecified(true); - } - } - - // Unset dirtiness on rGeometryRenderer only - // The rGeometry may be shared by several rGeometryRenderer - // so we cannot unset its dirtiness at this point - if (rGeometryRenderer->isDirty()) - rGeometryRenderer->unsetDirty(); - - // Prepare the ShaderParameterPack based on the active uniforms of the shader - shader->prepareUniforms(command.m_parameterPack); - - } else if (command.m_type == RenderCommand::Compute) { - GLShader *shader = command.m_glShader; - Q_ASSERT(shader); - - // Prepare the ShaderParameterPack based on the active uniforms of the shader - shader->prepareUniforms(command.m_parameterPack); - } - } - } - - // Make sure we leave nothing bound - if (vao) - vao->release(); - - // Unset dirtiness on Geometry and Attributes - // Note: we cannot do it in the loop above as we want to be sure that all - // the VAO which reference the geometry/attributes are properly updated - for (Attribute *attribute : qAsConst(m_dirtyAttributes)) - attribute->unsetDirty(); - m_dirtyAttributes.clear(); - - for (Geometry *geometry : qAsConst(m_dirtyGeometry)) - geometry->unsetDirty(); - m_dirtyGeometry.clear(); -} - -// Executed in a job -void Renderer::lookForAbandonedVaos() -{ - const QVector activeVaos = m_glResourceManagers->vaoManager()->activeHandles(); - for (HVao handle : activeVaos) { - OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(handle); - - // Make sure to only mark VAOs for deletion that were already created - // (ignore those that might be currently under construction in the render thread) - if (vao && vao->isAbandoned(m_nodesManager->geometryManager(), m_glResourceManagers->glShaderManager())) { - m_abandonedVaosMutex.lock(); - m_abandonedVaos.push_back(handle); - m_abandonedVaosMutex.unlock(); - } - } -} - -// Executed in a job -void Renderer::lookForDirtyBuffers() -{ - const QVector activeBufferHandles = m_nodesManager->bufferManager()->activeHandles(); - for (const HBuffer &handle: activeBufferHandles) { - Buffer *buffer = m_nodesManager->bufferManager()->data(handle); - if (buffer->isDirty()) - m_dirtyBuffers.push_back(handle); - } -} - -// Called in prepareSubmission -void Renderer::lookForDownloadableBuffers() -{ - m_downloadableBuffers.clear(); - const QVector activeBufferHandles = m_nodesManager->bufferManager()->activeHandles(); - for (const HBuffer &handle : activeBufferHandles) { - Buffer *buffer = m_nodesManager->bufferManager()->data(handle); - if (buffer->access() & QBuffer::Read) - m_downloadableBuffers.push_back(buffer->peerId()); - } -} - -// Executed in a job -void Renderer::lookForDirtyTextures() -{ - // To avoid having Texture or TextureImage maintain relationships between - // one another, we instead perform a lookup here to check if a texture - // image has been updated to then notify textures referencing the image - // that they need to be updated - TextureImageManager *imageManager = m_nodesManager->textureImageManager(); - const QVector activeTextureImageHandles = imageManager->activeHandles(); - Qt3DCore::QNodeIdVector dirtyImageIds; - for (const HTextureImage &handle: activeTextureImageHandles) { - TextureImage *image = imageManager->data(handle); - if (image->isDirty()) { - dirtyImageIds.push_back(image->peerId()); - image->unsetDirty(); - } - } - - TextureManager *textureManager = m_nodesManager->textureManager(); - const QVector activeTextureHandles = textureManager->activeHandles(); - for (const HTexture &handle: activeTextureHandles) { - Texture *texture = textureManager->data(handle); - const QNodeIdVector imageIds = texture->textureImageIds(); - - // Does the texture reference any of the dirty texture images? - for (const QNodeId imageId: imageIds) { - if (dirtyImageIds.contains(imageId)) { - texture->addDirtyFlag(Texture::DirtyImageGenerators); - break; - } - } - - // Dirty meaning that something has changed on the texture - // either properties, parameters, shared texture id, generator or a texture image - if (texture->dirtyFlags() != Texture::NotDirty) - m_dirtyTextures.push_back(handle); - // Note: texture dirty flags are reset when actually updating the - // textures in updateGLResources() as resetting flags here would make - // us lose information about what was dirty exactly. - } -} - -// Executed in a job -void Renderer::reloadDirtyShaders() -{ - Q_ASSERT(isRunning()); - const QVector activeTechniques = m_nodesManager->techniqueManager()->activeHandles(); - const QVector activeBuilders = m_nodesManager->shaderBuilderManager()->activeHandles(); - for (const HTechnique &techniqueHandle : activeTechniques) { - Technique *technique = m_nodesManager->techniqueManager()->data(techniqueHandle); - // If api of the renderer matches the one from the technique - if (technique->isCompatibleWithRenderer()) { - const auto passIds = technique->renderPasses(); - for (const QNodeId &passId : passIds) { - RenderPass *renderPass = m_nodesManager->renderPassManager()->lookupResource(passId); - HShader shaderHandle = m_nodesManager->shaderManager()->lookupHandle(renderPass->shaderProgram()); - Shader *shader = m_nodesManager->shaderManager()->data(shaderHandle); - - ShaderBuilder *shaderBuilder = nullptr; - for (const HShaderBuilder &builderHandle : activeBuilders) { - ShaderBuilder *builder = m_nodesManager->shaderBuilderManager()->data(builderHandle); - if (builder->shaderProgramId() == shader->peerId()) { - shaderBuilder = builder; - break; - } - } - - if (shaderBuilder) { - shaderBuilder->setGraphicsApi(*technique->graphicsApiFilter()); - - for (int i = 0; i <= QShaderProgram::Compute; i++) { - const auto shaderType = static_cast(i); - if (!shaderBuilder->shaderGraph(shaderType).isValid()) - continue; - - if (shaderBuilder->isShaderCodeDirty(shaderType)) { - shaderBuilder->generateCode(shaderType); - m_shaderBuilderUpdates.append(shaderBuilder->takePendingUpdates()); - } - - const auto code = shaderBuilder->shaderCode(shaderType); - shader->setShaderCode(shaderType, code); - } - } - - if (shader != nullptr && shader->isDirty()) - loadShader(shader, shaderHandle); - } - } - } -} - -// Executed in job (in main thread when jobs are done) -void Renderer::sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager) -{ - Q_ASSERT(isRunning()); - - // Sync Shader - const QVector activeShaders = m_nodesManager->shaderManager()->activeHandles(); - for (const HShader &handle :activeShaders) { - Shader *s = m_nodesManager->shaderManager()->data(handle); - if (s->requiresFrontendSync()) { - QShaderProgram *frontend = static_cast(manager->lookupNode(s->peerId())); - QShaderProgramPrivate *dFrontend = static_cast(QNodePrivate::get(frontend)); - s->unsetRequiresFrontendSync(); - dFrontend->setStatus(s->status()); - dFrontend->setLog(s->log()); - } - } - - // Sync ShaderBuilder - const QVector shaderBuilderUpdates = std::move(m_shaderBuilderUpdates); - for (const ShaderBuilderUpdate &update : shaderBuilderUpdates) { - QShaderProgramBuilder *builder = static_cast(manager->lookupNode(update.builderId)); - QShaderProgramBuilderPrivate *dBuilder = static_cast(QNodePrivate::get(builder)); - dBuilder->setShaderCode(update.shaderCode, update.shaderType); - } -} - -// Executed in a job (in main thread when jobs are done) -void Renderer::sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager) -{ - const QVector> updateTextureProperties = std::move(m_updatedTextureProperties); - for (const auto &pair : updateTextureProperties) { - const Qt3DCore::QNodeIdVector targetIds = pair.second; - for (const Qt3DCore::QNodeId &targetId: targetIds) { - // Lookup texture - Texture *t = m_nodesManager->textureManager()->lookupResource(targetId); - // If backend texture is Dirty, some property has changed and the properties we are - // about to send are already outdate - if (t == nullptr || t->dirtyFlags() != Texture::NotDirty) - continue; - - QAbstractTexture *texture = static_cast(manager->lookupNode(targetId)); - if (!texture) - continue; - const TextureProperties &properties = pair.first.properties; - - const bool blocked = texture->blockNotifications(true); - texture->setWidth(properties.width); - texture->setHeight(properties.height); - texture->setDepth(properties.depth); - texture->setLayers(properties.layers); - texture->setFormat(properties.format); - texture->blockNotifications(blocked); - - QAbstractTexturePrivate *dTexture = static_cast(QNodePrivate::get(texture)); - - dTexture->setStatus(properties.status); - dTexture->setHandleType(pair.first.handleType); - dTexture->setHandle(pair.first.handle); - } - } -} - -// Executed in a job -void Renderer::sendSetFenceHandlesToFrontend() -{ - const QVector> updatedSetFence = std::move(m_updatedSetFences); - FrameGraphManager *fgManager = m_nodesManager->frameGraphManager(); - for (const auto &pair : updatedSetFence) { - FrameGraphNode *fgNode = fgManager->lookupNode(pair.first); - if (fgNode != nullptr) { // Node could have been deleted before we got a chance to notify it - Q_ASSERT(fgNode->nodeType() == FrameGraphNode::SetFence); - SetFence *setFenceNode = static_cast(fgNode); - setFenceNode->setHandleType(QSetFence::OpenGLFenceId); - setFenceNode->setHandle(QVariant::fromValue(pair.second)); - } - } -} - -// Executed in a job (in main thread when jobs done) -void Renderer::sendDisablesToFrontend(Qt3DCore::QAspectManager *manager) -{ - // SubtreeEnabled - const auto updatedDisables = std::move(m_updatedDisableSubtreeEnablers); - for (const auto &nodeId : updatedDisables) { - QSubtreeEnabler *frontend = static_cast(manager->lookupNode(nodeId)); - frontend->setEnabled(false); - } - - // Compute Commands - const QVector activeCommands = m_nodesManager->computeJobManager()->activeHandles(); - for (const HComputeCommand &handle :activeCommands) { - ComputeCommand *c = m_nodesManager->computeJobManager()->data(handle); - if (c->hasReachedFrameCount()) { - QComputeCommand *frontend = static_cast(manager->lookupNode(c->peerId())); - frontend->setEnabled(false); - c->resetHasReachedFrameCount(); - } - } -} - -// Render Thread (or QtQuick RenderThread when using Scene3D) -// Scene3D: When using Scene3D rendering, we can't assume that when -// updateGLResources is called, the resource handles points to still existing -// objects. This is because Scene3D calls doRender independently of whether all -// jobs have completed or not which in turn calls proceedToNextFrame under some -// conditions. Such conditions are usually met on startup to avoid deadlocks. -// proceedToNextFrame triggers the syncChanges calls for the next frame, which -// may contain destruction changes targeting resources. When the above -// happens, this can result in the dirtyResource vectors containing handles of -// objects that may already have been destroyed -void Renderer::updateGLResources() -{ - { - // Update active fence objects: - // - Destroy fences that have reached their signaled state - GLFenceManager *fenceManager = m_glResourceManagers->glFenceManager(); - const auto end = fenceManager->end(); - auto it = fenceManager->begin(); - while (it != end) { - const GLFence fence = it.value(); - if (m_submissionContext->wasSyncSignaled(fence)) { - // Fence was signaled, we delete it - // before removing the entry from the manager - m_submissionContext->deleteSync(fence); - it = fenceManager->erase(it); - } else { - ++it; - } - } - } - - { - Profiling::GLTimeRecorder recorder(Profiling::BufferUpload, activeProfiler()); - const QVector dirtyBufferHandles = std::move(m_dirtyBuffers); - for (const HBuffer &handle: dirtyBufferHandles) { - Buffer *buffer = m_nodesManager->bufferManager()->data(handle); - - // Can be null when using Scene3D rendering - if (buffer == nullptr) - continue; - - // Forces creation if it doesn't exit - // Also note the binding point doesn't really matter here, we just upload data - if (!m_submissionContext->hasGLBufferForBuffer(buffer)) - m_submissionContext->glBufferForRenderBuffer(buffer); - // Update the glBuffer data - m_submissionContext->updateBuffer(buffer); - buffer->unsetDirty(); - } - } - -#ifndef SHADER_LOADING_IN_COMMAND_THREAD - { - Profiling::GLTimeRecorder recorder(Profiling::ShaderUpload, activeProfiler()); - const QVector dirtyShaderHandles = std::move(m_dirtyShaders); - ShaderManager *shaderManager = m_nodesManager->shaderManager(); - for (const HShader &handle: dirtyShaderHandles) { - Shader *shader = shaderManager->data(handle); - - // Can be null when using Scene3D rendering - if (shader == nullptr) - continue; - - // Compile shader - m_submissionContext->loadShader(shader, shaderManager, m_glResourceManagers->glShaderManager()); - } - } -#endif - - { - Profiling::GLTimeRecorder recorder(Profiling::TextureUpload, activeProfiler()); - const QVector activeTextureHandles = std::move(m_dirtyTextures); - for (const HTexture &handle: activeTextureHandles) { - Texture *texture = m_nodesManager->textureManager()->data(handle); - - // Can be null when using Scene3D rendering - if (texture == nullptr) - continue; - - // Create or Update GLTexture (the GLTexture instance is created if required - // and all things that can take place without a GL context are done here) - updateTexture(texture); - } - // We want to upload textures data at this point as the SubmissionThread and - // AspectThread are locked ensuring no races between Texture/TextureImage and - // GLTexture - if (m_submissionContext != nullptr) { - GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); - const QVector glTextureHandles = glTextureManager->activeHandles(); - // Upload texture data - for (const HGLTexture &glTextureHandle : glTextureHandles) { - GLTexture *glTexture = glTextureManager->data(glTextureHandle); - - // We create/update the actual GL texture using the GL context at this point - const GLTexture::TextureUpdateInfo info = glTexture->createOrUpdateGLTexture(); - - // GLTexture creation provides us width/height/format ... information - // for textures which had not initially specified these information (TargetAutomatic...) - // Gather these information and store them to be distributed by a change next frame - const QNodeIdVector referenceTextureIds = { glTextureManager->texNodeIdForGLTexture.value(glTexture) }; - // Store properties and referenceTextureIds - if (info.wasUpdated) { - Texture::TextureUpdateInfo updateInfo; - updateInfo.properties = info.properties; - updateInfo.handleType = QAbstractTexture::OpenGLTextureId; - updateInfo.handle = info.texture ? QVariant(info.texture->textureId()) : QVariant(); - m_updatedTextureProperties.push_back({updateInfo, referenceTextureIds}); - } - } - } - - // Record ids of texture to cleanup while we are still blocking the aspect thread - m_textureIdsToCleanup += m_nodesManager->textureManager()->takeTexturesIdsToCleanup(); - } - - // Record list of buffer that might need uploading - lookForDownloadableBuffers(); -} - -// Render Thread -void Renderer::updateTexture(Texture *texture) -{ - // Check that the current texture images are still in place, if not, do not update - const bool isValid = texture->isValid(m_nodesManager->textureImageManager()); - if (!isValid) { - qWarning() << Q_FUNC_INFO << "QTexture referencing invalid QTextureImages"; - return; - } - - // All textures are unique, if you instanciate twice the exact same texture - // this will create 2 identical GLTextures, no sharing will take place - - // Try to find the associated GLTexture for the backend Texture - GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); - GLTexture *glTexture = glTextureManager->lookupResource(texture->peerId()); - - // No GLTexture associated yet -> create it - if (glTexture == nullptr) { - glTexture = glTextureManager->getOrCreateResource(texture->peerId()); - glTextureManager->texNodeIdForGLTexture.insert(glTexture, texture->peerId()); - } - - // Update GLTexture to match Texture instance - const Texture::DirtyFlags dirtyFlags = texture->dirtyFlags(); - if (dirtyFlags.testFlag(Texture::DirtySharedTextureId)) - glTexture->setSharedTextureId(texture->sharedTextureId()); - - if (dirtyFlags.testFlag(Texture::DirtyProperties)) - glTexture->setProperties(texture->properties()); - - if (dirtyFlags.testFlag(Texture::DirtyParameters)) - glTexture->setParameters(texture->parameters()); - - // Will make the texture requestUpload - if (dirtyFlags.testFlag(Texture::DirtyImageGenerators)) { - const QNodeIdVector textureImageIds = texture->textureImageIds(); - QVector images; - images.reserve(textureImageIds.size()); - // TODO: Move this into GLTexture directly - for (const QNodeId textureImageId : textureImageIds) { - const TextureImage *img = m_nodesManager->textureImageManager()->lookupResource(textureImageId); - if (img == nullptr) { - qWarning() << Q_FUNC_INFO << "invalid TextureImage handle"; - } else { - GLTexture::Image glImg {img->dataGenerator(), img->layer(), img->mipLevel(), img->face()}; - images.push_back(glImg); - } - } - glTexture->setImages(images); - } - - // Will make the texture requestUpload - if (dirtyFlags.testFlag(Texture::DirtyDataGenerator)) - glTexture->setGenerator(texture->dataGenerator()); - - // Will make the texture requestUpload - if (dirtyFlags.testFlag(Texture::DirtyPendingDataUpdates)) - glTexture->addTextureDataUpdates(texture->takePendingTextureDataUpdates()); - - // Unset the dirty flag on the texture - texture->unsetDirty(); -} - -// Render Thread -void Renderer::cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId) -{ - GLTextureManager *glTextureManager = m_glResourceManagers->glTextureManager(); - GLTexture *glTexture = glTextureManager->lookupResource(cleanedUpTextureId); - - // Destroying the GLTexture implicitely also destroy the GL resources - if (glTexture != nullptr) { - glTextureManager->releaseResource(cleanedUpTextureId); - glTextureManager->texNodeIdForGLTexture.remove(glTexture); - } -} - -// Render Thread -void Renderer::cleanupShader(const Shader *shader) -{ - GLShaderManager *glShaderManager = m_glResourceManagers->glShaderManager(); - GLShader *glShader = glShaderManager->lookupResource(shader->peerId()); - - if (glShader != nullptr) - glShaderManager->abandon(glShader, shader); -} - -// Called by SubmitRenderView -void Renderer::downloadGLBuffers() -{ - const QVector downloadableHandles = std::move(m_downloadableBuffers); - for (const Qt3DCore::QNodeId &bufferId : downloadableHandles) { - BufferManager *bufferManager = m_nodesManager->bufferManager(); - BufferManager::ReadLocker locker(const_cast(bufferManager)); - Buffer *buffer = bufferManager->lookupResource(bufferId); - // Buffer could have been destroyed at this point - if (!buffer) - continue; - // locker is protecting us from the buffer being destroy while we're looking - // up its content - const QByteArray content = m_submissionContext->downloadBufferContent(buffer); - m_sendBufferCaptureJob->addRequest(QPair(bufferId, content)); - } -} - -// Happens in RenderThread context when all RenderViewJobs are done -// Returns the id of the last bound FBO -Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector &renderViews) -{ - QElapsedTimer timer; - quint64 queueElapsed = 0; - timer.start(); - - const int renderViewsCount = renderViews.size(); - quint64 frameElapsed = queueElapsed; - m_lastFrameCorrect.storeRelaxed(1); // everything fine until now..... - - qCDebug(Memory) << Q_FUNC_INFO << "rendering frame "; - - // We might not want to render on the default FBO - uint lastBoundFBOId = m_submissionContext->boundFrameBufferObject(); - QSurface *surface = nullptr; - QSurface *previousSurface = nullptr; - for (const Render::RenderView *rv: renderViews) { - previousSurface = rv->surface(); - if (previousSurface) - break; - } - QSurface *lastUsedSurface = nullptr; - - bool imGuiOverlayShown = false; - for (int i = 0; i < renderViewsCount; ++i) { - // Initialize GraphicsContext for drawing - // If the RenderView has a RenderStateSet defined - const RenderView *renderView = renderViews.at(i); - - // Check if using the same surface as the previous RenderView. - // If not, we have to free up the context from the previous surface - // and make the context current on the new surface - surface = renderView->surface(); - SurfaceLocker surfaceLock(surface); - - // TO DO: Make sure that the surface we are rendering too has not been unset - - // For now, if we do not have a surface, skip this renderview - // TODO: Investigate if it's worth providing a fallback offscreen surface - // to use when surface is null. Or if we should instead expose an - // offscreensurface to Qt3D. - if (!surface || !surfaceLock.isSurfaceValid()) { - m_lastFrameCorrect.storeRelaxed(0); - continue; - } - - lastUsedSurface = surface; - const bool surfaceHasChanged = surface != previousSurface; - - if (surfaceHasChanged && previousSurface) { - const bool swapBuffers = lastBoundFBOId == m_submissionContext->defaultFBO() - && surfaceLock.isSurfaceValid() - && m_shouldSwapBuffers; - // We only call swap buffer if we are sure the previous surface is still valid - m_submissionContext->endDrawing(swapBuffers); - } - - if (surfaceHasChanged) { - // If we can't make the context current on the surface, skip to the - // next RenderView. We won't get the full frame but we may get something - if (!m_submissionContext->beginDrawing(surface)) { - qWarning() << "Failed to make OpenGL context current on surface"; - m_lastFrameCorrect.storeRelaxed(0); - continue; - } - - previousSurface = surface; - lastBoundFBOId = m_submissionContext->boundFrameBufferObject(); - } - - // Apply Memory Barrier if needed - if (renderView->memoryBarrier() != QMemoryBarrier::None) - m_submissionContext->memoryBarrier(renderView->memoryBarrier()); - - - // Insert Fence into command stream if needed - const Qt3DCore::QNodeIdVector insertFenceIds = renderView->insertFenceIds(); - GLFenceManager *fenceManager = m_glResourceManagers->glFenceManager(); - for (const Qt3DCore::QNodeId insertFenceId : insertFenceIds) { - // If the fence is not in the manager, then it hasn't been inserted - // into the command stream yet. - if (fenceManager->find(insertFenceId) == fenceManager->end()) { - // Insert fence into command stream - GLFence glFence = m_submissionContext->fenceSync(); - // Record glFence - fenceManager->insert(insertFenceId, glFence); - // Add entry for notification changes to be sent - m_updatedSetFences.push_back({insertFenceId, glFence}); - } - // If it is in the manager, then it hasn't been signaled yet, - // nothing we can do but try at the next frame - } - - // Wait for fences if needed - const QVector waitFences = renderView->waitFences(); - for (const QWaitFenceData &waitFence : waitFences) { - // TO DO - if (waitFence.handleType != QWaitFence::OpenGLFenceId) { - qWarning() << "WaitFence handleType should be OpenGLFenceId when using the Qt 3D OpenGL renderer"; - continue; - } - GLFence fence = reinterpret_cast(waitFence.handle.value()); - if (fence == nullptr) - continue; - - if (waitFence.waitOnCPU) { - m_submissionContext->clientWaitSync(fence, - waitFence.timeout); - } else { - m_submissionContext->waitSync(fence); - } - } - - // Note: the RenderStateSet is allocated once per RV if needed - // and it contains a list of StateVariant value types - RenderStateSet *renderViewStateSet = renderView->stateSet(); - - { - Profiling::GLTimeRecorder recorder(Profiling::StateUpdate, activeProfiler()); - // Set the RV state if not null, - if (renderViewStateSet != nullptr) - m_submissionContext->setCurrentStateSet(renderViewStateSet); - else - m_submissionContext->setCurrentStateSet(m_defaultRenderStateSet); - } - - // Set RenderTarget ... - // Activate RenderTarget - { - Profiling::GLTimeRecorder recorder(Profiling::RenderTargetUpdate, activeProfiler()); - m_submissionContext->activateRenderTarget(renderView->renderTargetId(), - renderView->attachmentPack(), - lastBoundFBOId); - } - - { - Profiling::GLTimeRecorder recorder(Profiling::ClearBuffer, activeProfiler()); - // set color, depth, stencil clear values (only if needed) - auto clearBufferTypes = renderView->clearTypes(); - if (clearBufferTypes & QClearBuffers::ColorBuffer) { - const QVector4D vCol = renderView->globalClearColorBufferInfo().clearColor; - m_submissionContext->clearColor(QColor::fromRgbF(vCol.x(), vCol.y(), vCol.z(), vCol.w())); - } - if (clearBufferTypes & QClearBuffers::DepthBuffer) - m_submissionContext->clearDepthValue(renderView->clearDepthValue()); - if (clearBufferTypes & QClearBuffers::StencilBuffer) - m_submissionContext->clearStencilValue(renderView->clearStencilValue()); - - // Clear BackBuffer - m_submissionContext->clearBackBuffer(clearBufferTypes); - - // if there are ClearColors set for different draw buffers, - // clear each of these draw buffers individually now - const QVector clearDrawBuffers = renderView->specificClearColorBufferInfo(); - for (const ClearBufferInfo &clearBuffer : clearDrawBuffers) - m_submissionContext->clearBufferf(clearBuffer.drawBufferIndex, clearBuffer.clearColor); - } - - // Set the Viewport - m_submissionContext->setViewport(renderView->viewport(), renderView->surfaceSize()); - - // Execute the render commands - if (!executeCommandsSubmission(renderView)) - m_lastFrameCorrect.storeRelaxed(0); // something went wrong; make sure to render the next frame! - - // executeCommandsSubmission takes care of restoring the stateset to the value - // of gc->currentContext() at the moment it was called (either - // renderViewStateSet or m_defaultRenderStateSet) - if (!renderView->renderCaptureNodeId().isNull()) { - const QRenderCaptureRequest request = renderView->renderCaptureRequest(); - const QSize size = m_submissionContext->renderTargetSize(renderView->surfaceSize()); - QRect rect(QPoint(0, 0), size); - if (!request.rect.isEmpty()) - rect = rect.intersected(request.rect); - QImage image; - if (!rect.isEmpty()) { - // Bind fbo as read framebuffer - m_submissionContext->bindFramebuffer(m_submissionContext->activeFBO(), GraphicsHelperInterface::FBORead); - image = m_submissionContext->readFramebuffer(rect); - } else { - qWarning() << "Requested capture rectangle is outside framebuffer"; - } - Render::RenderCapture *renderCapture = - static_cast(m_nodesManager->frameGraphManager()->lookupNode(renderView->renderCaptureNodeId())); - renderCapture->addRenderCapture(request.captureId, image); - if (!m_pendingRenderCaptureSendRequests.contains(renderView->renderCaptureNodeId())) - m_pendingRenderCaptureSendRequests.push_back(renderView->renderCaptureNodeId()); - } - - if (renderView->isDownloadBuffersEnable()) - downloadGLBuffers(); - - // Perform BlitFramebuffer operations - if (renderView->hasBlitFramebufferInfo()) { - const auto &blitFramebufferInfo = renderView->blitFrameBufferInfo(); - const QNodeId inputTargetId = blitFramebufferInfo.sourceRenderTargetId; - const QNodeId outputTargetId = blitFramebufferInfo.destinationRenderTargetId; - const QRect inputRect = blitFramebufferInfo.sourceRect; - const QRect outputRect = blitFramebufferInfo.destinationRect; - const QRenderTargetOutput::AttachmentPoint inputAttachmentPoint = blitFramebufferInfo.sourceAttachmentPoint; - const QRenderTargetOutput::AttachmentPoint outputAttachmentPoint = blitFramebufferInfo.destinationAttachmentPoint; - const QBlitFramebuffer::InterpolationMethod interpolationMethod = blitFramebufferInfo.interpolationMethod; - m_submissionContext->blitFramebuffer(inputTargetId, outputTargetId, inputRect, outputRect, lastBoundFBOId, - inputAttachmentPoint, outputAttachmentPoint, - interpolationMethod); - } - -#ifndef Q_OS_INTEGRITY - if (!imGuiOverlayShown && renderView->showDebugOverlay()) { - imGuiOverlayShown = true; - if (!m_imGuiRenderer) { - m_imGuiRenderer = new Debug::ImGuiRenderer(this); - if (m_settings) - m_imGuiRenderer->setCapabilities(m_settings->capabilities()); - } - - { - QMutexLocker l(&m_frameEventsMutex); - for (auto &keyEvent: m_frameKeyEvents) - m_imGuiRenderer->processEvent(&keyEvent); - for (auto &mouseEvent: m_frameMouseEvents) - m_imGuiRenderer->processEvent(&mouseEvent.second); - } - m_imGuiRenderer->renderDebugOverlay(renderViews, renderView, m_jobsInLastFrame); - } -#endif - - frameElapsed = timer.elapsed() - frameElapsed; - qCDebug(Rendering) << Q_FUNC_INFO << "Submitted Renderview " << i + 1 << "/" << renderViewsCount << "in " << frameElapsed << "ms"; - frameElapsed = timer.elapsed(); - } - - // Bind lastBoundFBOId back. Needed also in threaded mode. - // lastBoundFBOId != m_graphicsContext->activeFBO() when the last FrameGraph leaf node/renderView - // contains RenderTargetSelector/RenderTarget - if (lastBoundFBOId != m_submissionContext->activeFBO()) - m_submissionContext->bindFramebuffer(lastBoundFBOId, GraphicsHelperInterface::FBOReadAndDraw); - - // Reset state and call doneCurrent if the surface - // is valid and was actually activated - if (lastUsedSurface && m_submissionContext->hasValidGLHelper()) { - // Reset state to the default state if the last stateset is not the - // defaultRenderStateSet - if (m_submissionContext->currentStateSet() != m_defaultRenderStateSet) - m_submissionContext->setCurrentStateSet(m_defaultRenderStateSet); - } - - queueElapsed = timer.elapsed() - queueElapsed; - qCDebug(Rendering) << Q_FUNC_INFO << "Submission of Queue in " << queueElapsed << "ms <=> " << queueElapsed / renderViewsCount << "ms per RenderView <=> Avg " << 1000.0f / (queueElapsed * 1.0f/ renderViewsCount * 1.0f) << " RenderView/s"; - qCDebug(Rendering) << Q_FUNC_INFO << "Submission Completed in " << timer.elapsed() << "ms"; - - // Stores the necessary information to safely perform - // the last swap buffer call - ViewSubmissionResultData resultData; - resultData.lastBoundFBOId = lastBoundFBOId; - resultData.surface = lastUsedSurface; - return resultData; -} - -void Renderer::markDirty(BackendNodeDirtySet changes, BackendNode *node) -{ - Q_UNUSED(node) - m_dirtyBits.marked |= changes; -} - -Renderer::BackendNodeDirtySet Renderer::dirtyBits() -{ - return m_dirtyBits.marked; -} - -#if defined(QT_BUILD_INTERNAL) -void Renderer::clearDirtyBits(BackendNodeDirtySet changes) -{ - m_dirtyBits.remaining &= ~changes; - m_dirtyBits.marked &= ~changes; -} -#endif - -bool Renderer::shouldRender() const -{ - // Only render if something changed during the last frame, or the last frame - // was not rendered successfully (or render-on-demand is disabled) - return (m_settings->renderPolicy() == QRenderSettings::Always - || m_dirtyBits.marked != 0 - || m_dirtyBits.remaining != 0 - || !m_lastFrameCorrect.loadRelaxed()); -} - -void Renderer::skipNextFrame() -{ - Q_ASSERT(m_settings->renderPolicy() != QRenderSettings::Always); - - // make submitRenderViews() actually run - m_renderQueue->setNoRender(); - m_submitRenderViewsSemaphore.release(1); -} - -void Renderer::jobsDone(Qt3DCore::QAspectManager *manager) -{ - // called in main thread once all jobs are done running - - // sync captured renders to frontend - const QVector pendingCaptureIds = std::move(m_pendingRenderCaptureSendRequests); - for (const Qt3DCore::QNodeId &id : qAsConst(pendingCaptureIds)) { - auto *backend = static_cast - (m_nodesManager->frameGraphManager()->lookupNode(id)); - backend->syncRenderCapturesToFrontend(manager); - } - - // Do we need to notify any texture about property changes? - if (m_updatedTextureProperties.size() > 0) - sendTextureChangesToFrontend(manager); - - sendDisablesToFrontend(manager); -} - -// Jobs we may have to run even if no rendering will happen -QVector Renderer::preRenderingJobs() -{ - { - QMutexLocker l(&m_frameEventsMutex); - m_frameMouseEvents = m_pickEventFilter->pendingMouseEvents(); - m_frameKeyEvents = m_pickEventFilter->pendingKeyEvents(); - } - - // Set values on picking jobs - RenderSettings *renderSetting = settings(); - if (renderSetting != nullptr) { - m_pickBoundingVolumeJob->setRenderSettings(renderSetting); - m_pickBoundingVolumeJob->setFrameGraphRoot(frameGraphRoot()); - m_pickBoundingVolumeJob->setMouseEvents(m_frameMouseEvents); - m_pickBoundingVolumeJob->setKeyEvents(m_frameKeyEvents); - - m_rayCastingJob->setRenderSettings(renderSetting); - m_rayCastingJob->setFrameGraphRoot(frameGraphRoot()); - } - - QVector jobs; - - // Do we need to notify frontend about fence change? - if (m_updatedSetFences.size() > 0) - jobs.push_back(m_sendSetFenceHandlesToFrontendJob); - - if (m_sendBufferCaptureJob->hasRequests()) - jobs.push_back(m_sendBufferCaptureJob); - - jobs.append(pickBoundingVolumeJob()); - jobs.append(rayCastingJob()); - - return jobs; -} - -// Waits to be told to create jobs for the next frame -// Called by QRenderAspect jobsToExecute context of QAspectThread -// Returns all the jobs (and with proper dependency chain) required -// for the rendering of the scene -QVector Renderer::renderBinJobs() -{ - QVector renderBinJobs; - // Create the jobs to build the frame - const QVector bufferJobs = createRenderBufferJobs(); - - // Remove previous dependencies - m_calculateBoundingVolumeJob->removeDependency(QWeakPointer()); - m_cleanupJob->removeDependency(QWeakPointer()); - - // Set dependencies - for (const QAspectJobPtr &bufferJob : bufferJobs) - m_calculateBoundingVolumeJob->addDependency(bufferJob); - - m_updateLevelOfDetailJob->setFrameGraphRoot(frameGraphRoot()); - - const BackendNodeDirtySet dirtyBitsForFrame = m_dirtyBits.marked | m_dirtyBits.remaining; - m_dirtyBits.marked = {}; - m_dirtyBits.remaining = {}; - BackendNodeDirtySet notCleared = {}; - - // Add jobs - const bool entitiesEnabledDirty = dirtyBitsForFrame & AbstractRenderer::EntityEnabledDirty; - if (entitiesEnabledDirty) { - renderBinJobs.push_back(m_updateTreeEnabledJob); - // This dependency is added here because we clear all dependencies - // at the start of this function. - m_calculateBoundingVolumeJob->addDependency(m_updateTreeEnabledJob); - } - - if (dirtyBitsForFrame & AbstractRenderer::TransformDirty) { - renderBinJobs.push_back(m_worldTransformJob); - renderBinJobs.push_back(m_updateWorldBoundingVolumeJob); - renderBinJobs.push_back(m_updateShaderDataTransformJob); - } - - if (dirtyBitsForFrame & AbstractRenderer::GeometryDirty || - dirtyBitsForFrame & AbstractRenderer::BuffersDirty) { - renderBinJobs.push_back(m_calculateBoundingVolumeJob); - renderBinJobs.push_back(m_updateMeshTriangleListJob); - } - - if (dirtyBitsForFrame & AbstractRenderer::GeometryDirty || - dirtyBitsForFrame & AbstractRenderer::TransformDirty) { - renderBinJobs.push_back(m_expandBoundingVolumeJob); - } - - // TO DO: Conditionally add if skeletons dirty - renderBinJobs.push_back(m_syncLoadingJobs); - m_updateSkinningPaletteJob->setDirtyJoints(m_nodesManager->jointManager()->dirtyJoints()); - renderBinJobs.push_back(m_updateSkinningPaletteJob); - renderBinJobs.push_back(m_updateLevelOfDetailJob); - renderBinJobs.push_back(m_cleanupJob); - renderBinJobs.append(bufferJobs); - - // Jobs to prepare GL Resource upload - renderBinJobs.push_back(m_vaoGathererJob); - - if (dirtyBitsForFrame & AbstractRenderer::BuffersDirty) - renderBinJobs.push_back(m_bufferGathererJob); - - if (dirtyBitsForFrame & AbstractRenderer::TexturesDirty) - renderBinJobs.push_back(m_textureGathererJob); - - - // Layer cache is dependent on layers, layer filters (hence FG structure - // changes) and the enabled flag on entities - const bool frameGraphDirty = dirtyBitsForFrame & AbstractRenderer::FrameGraphDirty; - const bool layersDirty = dirtyBitsForFrame & AbstractRenderer::LayersDirty; - const bool layersCacheNeedsToBeRebuilt = layersDirty || entitiesEnabledDirty || frameGraphDirty; - const bool shadersDirty = dirtyBitsForFrame & AbstractRenderer::ShadersDirty; - const bool materialDirty = dirtyBitsForFrame & AbstractRenderer::MaterialDirty; - const bool lightsDirty = dirtyBitsForFrame & AbstractRenderer::LightsDirty; - const bool computeableDirty = dirtyBitsForFrame & AbstractRenderer::ComputeDirty; - const bool renderableDirty = dirtyBitsForFrame & AbstractRenderer::GeometryDirty; - const bool materialCacheNeedsToBeRebuilt = shadersDirty || materialDirty || frameGraphDirty; - const bool renderCommandsDirty = materialCacheNeedsToBeRebuilt || renderableDirty || computeableDirty; - - // Rebuild Entity Layers list if layers are dirty - if (layersDirty) - renderBinJobs.push_back(m_updateEntityLayersJob); - - if (renderableDirty) { - renderBinJobs.push_back(m_renderableEntityFilterJob); - renderBinJobs.push_back(m_cacheRenderableEntitiesJob); - } - - if (computeableDirty) { - renderBinJobs.push_back(m_computableEntityFilterJob); - renderBinJobs.push_back(m_cacheComputableEntitiesJob); - } - - if (lightsDirty) { - renderBinJobs.push_back(m_lightGathererJob); - renderBinJobs.push_back(m_cacheLightsJob); - } - - QMutexLocker lock(m_renderQueue->mutex()); - if (m_renderQueue->wasReset()) { // Have we rendered yet? (Scene3D case) - // Traverse the current framegraph. For each leaf node create a - // RenderView and set its configuration then create a job to - // populate the RenderView with a set of RenderCommands that get - // their details from the RenderNodes that are visible to the - // Camera selected by the framegraph configuration - if (frameGraphDirty) { - FrameGraphVisitor visitor(m_nodesManager->frameGraphManager()); - m_frameGraphLeaves = visitor.traverse(frameGraphRoot()); - // Remove leaf nodes that no longer exist from cache - const QList keys = m_cache.leafNodeCache.keys(); - for (FrameGraphNode *leafNode : keys) { - if (!m_frameGraphLeaves.contains(leafNode)) - m_cache.leafNodeCache.remove(leafNode); - } - - // Handle single shot subtree enablers - const auto subtreeEnablers = visitor.takeEnablersToDisable(); - for (auto *node : subtreeEnablers) - m_updatedDisableSubtreeEnablers.push_back(node->peerId()); - } - - const int fgBranchCount = m_frameGraphLeaves.size(); - for (int i = 0; i < fgBranchCount; ++i) { - FrameGraphNode *leaf = m_frameGraphLeaves.at(i); - RenderViewBuilder builder(leaf, i, this); - // If we have a new RV (wasn't in the cache before, then it contains no cached data) - const bool isNewRV = !m_cache.leafNodeCache.contains(leaf); - builder.setLayerCacheNeedsToBeRebuilt(layersCacheNeedsToBeRebuilt || isNewRV); - builder.setMaterialGathererCacheNeedsToBeRebuilt(materialCacheNeedsToBeRebuilt || isNewRV); - builder.setRenderCommandCacheNeedsToBeRebuilt(renderCommandsDirty || isNewRV); - - builder.prepareJobs(); - renderBinJobs.append(builder.buildJobHierachy()); - } - - // Set target number of RenderViews - m_renderQueue->setTargetRenderViewCount(fgBranchCount); - } else { - // FilterLayerEntityJob is part of the RenderViewBuilder jobs and must be run later - // if none of those jobs are started this frame - notCleared |= AbstractRenderer::EntityEnabledDirty; - notCleared |= AbstractRenderer::FrameGraphDirty; - notCleared |= AbstractRenderer::LayersDirty; - } - - if (isRunning() && m_submissionContext->isInitialized()) { - if (dirtyBitsForFrame & AbstractRenderer::TechniquesDirty ) - renderBinJobs.push_back(m_filterCompatibleTechniqueJob); - if (dirtyBitsForFrame & AbstractRenderer::ShadersDirty) - renderBinJobs.push_back(m_introspectShaderJob); - } else { - notCleared |= AbstractRenderer::TechniquesDirty; - notCleared |= AbstractRenderer::ShadersDirty; - } - - m_dirtyBits.remaining = dirtyBitsForFrame & notCleared; - - return renderBinJobs; -} - -QAspectJobPtr Renderer::pickBoundingVolumeJob() -{ - return m_pickBoundingVolumeJob; -} - -QAspectJobPtr Renderer::rayCastingJob() -{ - return m_rayCastingJob; -} - -QAspectJobPtr Renderer::syncLoadingJobs() -{ - return m_syncLoadingJobs; -} - -QAspectJobPtr Renderer::expandBoundingVolumeJob() -{ - return m_expandBoundingVolumeJob; -} - -QAbstractFrameAdvanceService *Renderer::frameAdvanceService() const -{ - return static_cast(m_vsyncFrameAdvanceService.data()); -} - -// Called by executeCommands -void Renderer::performDraw(RenderCommand *command) -{ - // Indirect Draw Calls - if (command->m_drawIndirect) { - - // Bind the indirect draw buffer - Buffer *indirectDrawBuffer = m_nodesManager->bufferManager()->data(command->m_indirectDrawBuffer); - if (Q_UNLIKELY(indirectDrawBuffer == nullptr)) { - qWarning() << "Invalid Indirect Draw Buffer - failed to retrieve Buffer"; - return; - } - - // Get GLBuffer from Buffer; - GLBuffer *indirectDrawGLBuffer = m_submissionContext->glBufferForRenderBuffer(indirectDrawBuffer); - if (Q_UNLIKELY(indirectDrawGLBuffer == nullptr)) { - qWarning() << "Invalid Indirect Draw Buffer - failed to retrieve GLBuffer"; - return; - } - - // Bind GLBuffer - const bool successfullyBound = indirectDrawGLBuffer->bind(m_submissionContext.data(), GLBuffer::DrawIndirectBuffer); - - if (Q_LIKELY(successfullyBound)) { - // TO DO: Handle multi draw variants if attribute count > 1 - if (command->m_drawIndexed) { - m_submissionContext->drawElementsIndirect(command->m_primitiveType, - command->m_indexAttributeDataType, - reinterpret_cast(quintptr(command->m_indirectAttributeByteOffset))); - } else { - m_submissionContext->drawArraysIndirect(command->m_primitiveType, - reinterpret_cast(quintptr(command->m_indirectAttributeByteOffset))); - } - } else { - qWarning() << "Failed to bind IndirectDrawBuffer"; - } - - } else { // Direct Draw Calls - - // TO DO: Add glMulti Draw variants - if (command->m_primitiveType == QGeometryRenderer::Patches) - m_submissionContext->setVerticesPerPatch(command->m_verticesPerPatch); - - if (command->m_primitiveRestartEnabled) - m_submissionContext->enablePrimitiveRestart(command->m_restartIndexValue); - - // TO DO: Add glMulti Draw variants - if (command->m_drawIndexed) { - Profiling::GLTimeRecorder recorder(Profiling::DrawElement, activeProfiler()); - m_submissionContext->drawElementsInstancedBaseVertexBaseInstance(command->m_primitiveType, - command->m_primitiveCount, - command->m_indexAttributeDataType, - reinterpret_cast(quintptr(command->m_indexAttributeByteOffset)), - command->m_instanceCount, - command->m_indexOffset, - command->m_firstInstance); - } else { - Profiling::GLTimeRecorder recorder(Profiling::DrawArray, activeProfiler()); - m_submissionContext->drawArraysInstancedBaseInstance(command->m_primitiveType, - command->m_firstVertex, - command->m_primitiveCount, - command->m_instanceCount, - command->m_firstInstance); - } - } - -#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) - int err = m_submissionContext->openGLContext()->functions()->glGetError(); - if (err) - qCWarning(Rendering) << "GL error after drawing mesh:" << QString::number(err, 16); -#endif - - if (command->m_primitiveRestartEnabled) - m_submissionContext->disablePrimitiveRestart(); -} - -void Renderer::performCompute(const RenderView *, RenderCommand *command) -{ - { - Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler()); - GLShader *shader = m_glResourceManagers->glShaderManager()->lookupResource(command->m_shaderId); - m_submissionContext->activateShader(shader); - } - { - Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler()); - m_submissionContext->setParameters(command->m_parameterPack); - } - { - Profiling::GLTimeRecorder recorder(Profiling::DispatchCompute, activeProfiler()); - m_submissionContext->dispatchCompute(command->m_workGroups[0], - command->m_workGroups[1], - command->m_workGroups[2]); - } - // HACK: Reset the compute flag to dirty - m_dirtyBits.marked |= AbstractRenderer::ComputeDirty; - -#if defined(QT3D_RENDER_ASPECT_OPENGL_DEBUG) - int err = m_submissionContext->openGLContext()->functions()->glGetError(); - if (err) - qCWarning(Rendering) << "GL error after drawing mesh:" << QString::number(err, 16); -#endif -} - -void Renderer::createOrUpdateVAO(RenderCommand *command, - HVao *previousVaoHandle, - OpenGLVertexArrayObject **vao) -{ - const VAOIdentifier vaoKey(command->m_geometry, command->m_shaderId); - - VAOManager *vaoManager = m_glResourceManagers->vaoManager(); - command->m_vao = vaoManager->lookupHandle(vaoKey); - - if (command->m_vao.isNull()) { - qCDebug(Rendering) << Q_FUNC_INFO << "Allocating new VAO"; - command->m_vao = vaoManager->getOrAcquireHandle(vaoKey); - vaoManager->data(command->m_vao)->create(m_submissionContext.data(), vaoKey); - } - - if (*previousVaoHandle != command->m_vao) { - *previousVaoHandle = command->m_vao; - *vao = vaoManager->data(command->m_vao); - } - Q_ASSERT(*vao); -} - -// Called by RenderView->submit() in RenderThread context -// Returns true, if all RenderCommands were sent to the GPU -bool Renderer::executeCommandsSubmission(const RenderView *rv) -{ - bool allCommandsIssued = true; - - // Render drawing commands - QVector commands = rv->commands(); - - // Use the graphicscontext to submit the commands to the underlying - // graphics API (OpenGL) - - // Save the RenderView base stateset - RenderStateSet *globalState = m_submissionContext->currentStateSet(); - OpenGLVertexArrayObject *vao = nullptr; - - for (RenderCommand &command : commands) { - - if (command.m_type == RenderCommand::Compute) { // Compute Call - performCompute(rv, &command); - } else { // Draw Command - // Check if we have a valid command that can be drawn - if (!command.m_isValid) { - allCommandsIssued = false; - continue; - } - - vao = m_glResourceManagers->vaoManager()->data(command.m_vao); - - // something may have went wrong when initializing the VAO - if (!vao->isSpecified()) { - allCommandsIssued = false; - continue; - } - - { - Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler()); - //// We activate the shader here - GLShader *shader = command.m_glShader; - if (!m_submissionContext->activateShader(shader)) { - allCommandsIssued = false; - continue; - } - } - - { - Profiling::GLTimeRecorder recorder(Profiling::VAOUpdate, activeProfiler()); - // Bind VAO - vao->bind(); - } - - { - Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler()); - //// Update program uniforms - if (!m_submissionContext->setParameters(command.m_parameterPack)) { - allCommandsIssued = false; - // If we have failed to set uniform (e.g unable to bind a texture) - // we won't perform the draw call which could show invalid content - continue; - } - } - - //// OpenGL State - // TO DO: Make states not dependendent on their backend node for this step - // Set state - RenderStateSet *localState = command.m_stateSet.data(); - - - { - Profiling::GLTimeRecorder recorder(Profiling::StateUpdate, activeProfiler()); - // Merge the RenderCommand state with the globalState of the RenderView - // Or restore the globalState if no stateSet for the RenderCommand - if (localState != nullptr) { - command.m_stateSet->merge(globalState); - m_submissionContext->setCurrentStateSet(localState); - } else { - m_submissionContext->setCurrentStateSet(globalState); - } - } - // All Uniforms for a pass are stored in the QUniformPack of the command - // Uniforms for Effect, Material and Technique should already have been correctly resolved - // at that point - - //// Draw Calls - performDraw(&command); - } - } // end of RenderCommands loop - - // We cache the VAO and release it only at the end of the exectute frame - // We try to minimize VAO binding between RenderCommands - if (vao) - vao->release(); - - // Reset to the state we were in before executing the render commands - m_submissionContext->setCurrentStateSet(globalState); - - return allCommandsIssued; -} - -bool Renderer::updateVAOWithAttributes(Geometry *geometry, - const RenderCommand *command, - GLShader *shader, - bool forceUpdate) -{ - m_dirtyAttributes.reserve(m_dirtyAttributes.size() + geometry->attributes().size()); - const auto attributeIds = geometry->attributes(); - - for (QNodeId attributeId : attributeIds) { - // TO DO: Improvement we could store handles and use the non locking policy on the attributeManager - Attribute *attribute = m_nodesManager->attributeManager()->lookupResource(attributeId); - - if (attribute == nullptr) - return false; - - Buffer *buffer = m_nodesManager->bufferManager()->lookupResource(attribute->bufferId()); - - // Buffer update was already performed at this point - // Just make sure the attribute reference a valid buffer - if (buffer == nullptr) - return false; - - // Index Attribute - bool attributeWasDirty = false; - if (attribute->attributeType() == QAttribute::IndexAttribute) { - if ((attributeWasDirty = attribute->isDirty()) == true || forceUpdate) - m_submissionContext->specifyIndices(buffer); - // Vertex Attribute - } else if (command->m_activeAttributes.contains(attribute->nameId())) { - if ((attributeWasDirty = attribute->isDirty()) == true || forceUpdate) { - // Find the location for the attribute - const QVector shaderAttributes = shader->attributes(); - const ShaderAttribute *attributeDescription = nullptr; - for (const ShaderAttribute &shaderAttribute : shaderAttributes) { - if (shaderAttribute.m_nameId == attribute->nameId()) { - attributeDescription = &shaderAttribute; - break; - } - } - if (!attributeDescription || attributeDescription->m_location < 0) - return false; - m_submissionContext->specifyAttribute(attribute, buffer, attributeDescription); - } - } - - // Append attribute to temporary vector so that its dirtiness - // can be cleared at the end of the frame - if (attributeWasDirty) - m_dirtyAttributes.push_back(attribute); - - // Note: We cannot call unsertDirty on the Attribute at this - // point as we don't know if the attributes are being shared - // with other geometry / geometryRenderer in which case they still - // should remain dirty so that VAO for these commands are properly - // updated - } - - return true; -} - -bool Renderer::requiresVAOAttributeUpdate(Geometry *geometry, - const RenderCommand *command) const -{ - const auto attributeIds = geometry->attributes(); - - for (QNodeId attributeId : attributeIds) { - // TO DO: Improvement we could store handles and use the non locking policy on the attributeManager - Attribute *attribute = m_nodesManager->attributeManager()->lookupResource(attributeId); - - if (attribute == nullptr) - continue; - - if ((attribute->attributeType() == QAttribute::IndexAttribute && attribute->isDirty()) || - (command->m_activeAttributes.contains(attribute->nameId()) && attribute->isDirty())) - return true; - } - return false; -} - -// Erase graphics related resources that may become unused after a frame -void Renderer::cleanGraphicsResources() -{ - // Clean buffers - const QVector buffersToRelease = m_nodesManager->bufferManager()->takeBuffersToRelease(); - for (Qt3DCore::QNodeId bufferId : buffersToRelease) - m_submissionContext->releaseBuffer(bufferId); - - // When Textures are cleaned up, their id is saved so that they can be - // cleaned up in the render thread - const QVector cleanedUpTextureIds = std::move(m_textureIdsToCleanup); - for (const Qt3DCore::QNodeId textureCleanedUpId: cleanedUpTextureIds) - cleanupTexture(textureCleanedUpId); - - // Delete abandoned VAOs - m_abandonedVaosMutex.lock(); - const QVector abandonedVaos = std::move(m_abandonedVaos); - m_abandonedVaosMutex.unlock(); - for (const HVao &vaoHandle : abandonedVaos) { - // might have already been destroyed last frame, but added by the cleanup job before, so - // check if the VAO is really still existent - OpenGLVertexArrayObject *vao = m_glResourceManagers->vaoManager()->data(vaoHandle); - if (vao) { - vao->destroy(); - // We remove VAO from manager using its VAOIdentifier - m_glResourceManagers->vaoManager()->release(vaoHandle); - } - } - - // Abandon GL shaders when a Shader node is destroyed Note: We are sure - // that when this gets executed, all scene changes have been received and - // shader nodes updated - const QVector cleanedUpShaderIds = m_nodesManager->shaderManager()->takeShaderIdsToCleanup(); - for (const Qt3DCore::QNodeId shaderCleanedUpId: cleanedUpShaderIds) { - cleanupShader(m_nodesManager->shaderManager()->lookupResource(shaderCleanedUpId)); - // We can really release the texture at this point - m_nodesManager->shaderManager()->releaseResource(shaderCleanedUpId); - } -} - -const GraphicsApiFilterData *Renderer::contextInfo() const -{ - return m_submissionContext->contextInfo(); -} - -SubmissionContext *Renderer::submissionContext() const -{ - return m_submissionContext.data(); -} - -// Returns a vector of jobs to be performed for dirty buffers -// 1 dirty buffer == 1 job, all job can be performed in parallel -QVector Renderer::createRenderBufferJobs() const -{ - const QVector dirtyBuffers = m_nodesManager->bufferManager()->takeDirtyBuffers(); - QVector dirtyBuffersJobs; - dirtyBuffersJobs.reserve(dirtyBuffers.size()); - - for (const QNodeId bufId : dirtyBuffers) { - Render::HBuffer bufferHandle = m_nodesManager->lookupHandle(bufId); - if (!bufferHandle.isNull()) { - // Create new buffer job - auto job = Render::LoadBufferJobPtr::create(bufferHandle); - job->setNodeManager(m_nodesManager); - dirtyBuffersJobs.push_back(job); - } - } - - return dirtyBuffersJobs; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/renderer.pri b/src/render/renderers/opengl/renderer/renderer.pri deleted file mode 100644 index 3e2f9fde9..000000000 --- a/src/render/renderers/opengl/renderer/renderer.pri +++ /dev/null @@ -1,24 +0,0 @@ -INCLUDEPATH += $$PWD - -SOURCES += \ - $$PWD/openglvertexarrayobject.cpp \ - $$PWD/rendercommand.cpp \ - $$PWD/renderer.cpp \ - $$PWD/renderqueue.cpp \ - $$PWD/renderview.cpp \ - $$PWD/renderviewbuilder.cpp \ - $$PWD/shaderparameterpack.cpp \ - $$PWD/glshader.cpp - -HEADERS += \ - $$PWD/openglvertexarrayobject_p.h \ - $$PWD/renderercache_p.h \ - $$PWD/rendercommand_p.h \ - $$PWD/renderer_p.h \ - $$PWD/renderqueue_p.h \ - $$PWD/renderview_p.h \ - $$PWD/renderviewbuilder_p.h \ - $$PWD/shaderparameterpack_p.h \ - $$PWD/shadervariables_p.h \ - $$PWD/glshader_p.h - diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/render/renderers/opengl/renderer/renderer_p.h deleted file mode 100644 index e8929e67a..000000000 --- a/src/render/renderers/opengl/renderer/renderer_p.h +++ /dev/null @@ -1,477 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERER_H -#define QT3DRENDER_RENDER_RENDERER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#if defined(QT_BUILD_INTERNAL) -class tst_Renderer; -#endif - -QT_BEGIN_NAMESPACE - -class QSurface; -class QMouseEvent; -class QScreen; - -namespace Qt3DCore { -class QEntity; -class QFrameAllocator; -class QEventFilterService; -} - -namespace Qt3DRender { - -class QCamera; -class QMaterial; -class QShaderProgram; -class QMesh; -class QRenderPass; -class QAbstractShapeMesh; -struct GraphicsApiFilterData; -class QSceneImporter; - -namespace Debug { -class CommandExecuter; -} - -namespace Render { - -namespace Profiling { -class FrameProfiler; -} - -class CameraLens; -class SubmissionContext; -class FrameGraphNode; -class Material; -class Technique; -class Shader; -class Entity; -class RenderCommand; -class RenderQueue; -class RenderView; -class Effect; -class RenderPass; -class RenderThread; -class RenderStateSet; -class VSyncFrameAdvanceService; -class PickEventFilter; -class NodeManagers; -class GLResourceManagers; -class GLShader; -class ResourceAccessor; - -class UpdateLevelOfDetailJob; -typedef QSharedPointer UpdateLevelOfDetailJobPtr; - -using SynchronizerJobPtr = GenericLambdaJobPtr>; -using SynchronizerPostFramePtr = GenericLambdaJobAndPostFramePtr, std::function>; - -template -class FilterEntityByComponentJob; -template -using FilterEntityByComponentJobPtr = QSharedPointer>; -using ComputableEntityFilterPtr = FilterEntityByComponentJobPtr; -using RenderableEntityFilterPtr = FilterEntityByComponentJobPtr; - -namespace Debug { -class ImGuiRenderer; -} - -class Q_3DRENDERSHARED_PRIVATE_EXPORT Renderer : public AbstractRenderer -{ -public: - explicit Renderer(QRenderAspect::RenderType type); - ~Renderer(); - - void dumpInfo() const override; - API api() const override { return AbstractRenderer::OpenGL; } - - qint64 time() const override; - void setTime(qint64 time) override; - void setJobsInLastFrame(int jobsInLastFrame) override; - - void setNodeManagers(NodeManagers *managers) override; - void setServices(Qt3DCore::QServiceLocator *services) override; - void setSurfaceExposed(bool exposed) override; - - NodeManagers *nodeManagers() const override; - Qt3DCore::QServiceLocator *services() const override { return m_services; } - - void initialize() override; - void shutdown() override; - void releaseGraphicsResources() override; - - void render() override; - void doRender(bool swapBuffers = true) override; - void cleanGraphicsResources() override; - - bool isRunning() const override { return m_running.loadRelaxed(); } - - void setSceneRoot(Entity *sgRoot) override; - Entity *sceneRoot() const override { return m_renderSceneRoot; } - - FrameGraphNode *frameGraphRoot() const override; - RenderQueue *renderQueue() const { return m_renderQueue; } - - void markDirty(BackendNodeDirtySet changes, BackendNode *node) override; - BackendNodeDirtySet dirtyBits() override; - -#if defined(QT_BUILD_INTERNAL) - void clearDirtyBits(BackendNodeDirtySet changes) override; -#endif - bool shouldRender() const override; - void skipNextFrame() override; - void jobsDone(Qt3DCore::QAspectManager *manager) override; - - QVector preRenderingJobs() override; - QVector renderBinJobs() override; - Qt3DCore::QAspectJobPtr pickBoundingVolumeJob() override; - Qt3DCore::QAspectJobPtr rayCastingJob() override; - Qt3DCore::QAspectJobPtr syncLoadingJobs() override; - Qt3DCore::QAspectJobPtr expandBoundingVolumeJob() override; - - QVector createRenderBufferJobs() const; - - inline FrameCleanupJobPtr frameCleanupJob() const { return m_cleanupJob; } - inline UpdateShaderDataTransformJobPtr updateShaderDataTransformJob() const { return m_updateShaderDataTransformJob; } - inline CalculateBoundingVolumeJobPtr calculateBoundingVolumeJob() const { return m_calculateBoundingVolumeJob; } - inline UpdateTreeEnabledJobPtr updateTreeEnabledJob() const { return m_updateTreeEnabledJob; } - inline UpdateWorldTransformJobPtr updateWorldTransformJob() const { return m_worldTransformJob; } - inline UpdateWorldBoundingVolumeJobPtr updateWorldBoundingVolumeJob() const { return m_updateWorldBoundingVolumeJob; } - inline UpdateLevelOfDetailJobPtr updateLevelOfDetailJob() const { return m_updateLevelOfDetailJob; } - inline UpdateMeshTriangleListJobPtr updateMeshTriangleListJob() const { return m_updateMeshTriangleListJob; } - inline FilterCompatibleTechniqueJobPtr filterCompatibleTechniqueJob() const { return m_filterCompatibleTechniqueJob; } - inline SynchronizerJobPtr syncLoadingJobs() const { return m_syncLoadingJobs; } - inline UpdateSkinningPaletteJobPtr updateSkinningPaletteJob() const { return m_updateSkinningPaletteJob; } - inline SynchronizerPostFramePtr introspectShadersJob() const { return m_introspectShaderJob; } - inline Qt3DCore::QAspectJobPtr bufferGathererJob() const { return m_bufferGathererJob; } - inline Qt3DCore::QAspectJobPtr textureGathererJob() const { return m_textureGathererJob; } - inline UpdateEntityLayersJobPtr updateEntityLayersJob() const { return m_updateEntityLayersJob; } - inline LightGathererPtr lightGathererJob() const { return m_lightGathererJob; } - inline RenderableEntityFilterPtr renderableEntityFilterJob() const { return m_renderableEntityFilterJob; } - inline ComputableEntityFilterPtr computableEntityFilterJob() const { return m_computableEntityFilterJob; } - inline SynchronizerJobPtr cacheLightJob() const { return m_cacheLightsJob; } - inline SynchronizerJobPtr cacheRenderableEntitiesJob() const { return m_cacheRenderableEntitiesJob; } - inline SynchronizerJobPtr cacheComputableEntitiesJob() const { return m_cacheComputableEntitiesJob; } - - Qt3DCore::QAbstractFrameAdvanceService *frameAdvanceService() const override; - - void registerEventFilter(Qt3DCore::QEventFilterService *service) override; - - void setSettings(RenderSettings *settings) override; - RenderSettings *settings() const override; - QOpenGLContext *shareContext() const override; - - inline GLResourceManagers *glResourceManagers() const { return m_glResourceManagers; } - - // Executed in secondary GL thread - void loadShader(Shader *shader, Qt3DRender::Render::HShader shaderHandle) override; - - - void updateGLResources(); - void updateTexture(Texture *texture); - void cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId); - void cleanupShader(const Shader *shader); - void downloadGLBuffers(); - void blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId, - Qt3DCore::QNodeId outputRenderTargetId, - QRect inputRect, - QRect outputRect, - GLuint defaultFramebuffer); - - void prepareCommandsSubmission(const QVector &renderViews); - bool executeCommandsSubmission(const RenderView *rv); - bool updateVAOWithAttributes(Geometry *geometry, - const RenderCommand *command, - GLShader *shader, - bool forceUpdate); - - bool requiresVAOAttributeUpdate(Geometry *geometry, - const RenderCommand *command) const; - - // For Scene2D rendering - void setOpenGLContext(QOpenGLContext *context) override; - bool accessOpenGLTexture(Qt3DCore::QNodeId nodeId, - QOpenGLTexture **texture, - QMutex **lock, - bool readonly) override; - QSharedPointer resourceAccessor() const override; - - - const GraphicsApiFilterData *contextInfo() const; - SubmissionContext *submissionContext() const; - - inline RenderStateSet *defaultRenderState() const { return m_defaultRenderStateSet; } - - void enqueueRenderView(RenderView *renderView, int submitOrder); - bool isReadyToSubmit(); - - QVariant executeCommand(const QStringList &args) override; - void setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) override; - QSurfaceFormat format() override; - - struct ViewSubmissionResultData - { - ViewSubmissionResultData() - : lastBoundFBOId(0) - , surface(nullptr) - {} - - uint lastBoundFBOId; - QSurface *surface; - }; - - ViewSubmissionResultData submitRenderViews(const QVector &renderViews); - - RendererCache *cache() { return &m_cache; } - void setScreen(QScreen *scr) override; - QScreen *screen() const override; - -#ifdef QT3D_RENDER_UNIT_TESTS -public: -#else - -private: -#endif - bool canRender() const; - Profiling::FrameProfiler *activeProfiler() const; - - Qt3DCore::QServiceLocator *m_services; - NodeManagers *m_nodesManager; - - // Frame graph root - Qt3DCore::QNodeId m_frameGraphRootUuid; - - Entity *m_renderSceneRoot; - - // Fail safe values that we can use if a RenderCommand - // is missing a shader - RenderStateSet *m_defaultRenderStateSet; - ShaderParameterPack m_defaultUniformPack; - - QScopedPointer m_submissionContext; - QSurfaceFormat m_format; - - RenderQueue *m_renderQueue; - QScopedPointer m_renderThread; - QScopedPointer m_vsyncFrameAdvanceService; - - QSemaphore m_submitRenderViewsSemaphore; - QSemaphore m_waitForInitializationToBeCompleted; - QMutex m_hasBeenInitializedMutex; - - QAtomicInt m_running; - - QScopedPointer m_pickEventFilter; - - QVector m_dirtyAttributes; - QVector m_dirtyGeometry; - QAtomicInt m_exposed; - - struct DirtyBits { - BackendNodeDirtySet marked; // marked dirty since last job build - BackendNodeDirtySet remaining; // remaining dirty after jobs have finished - }; - DirtyBits m_dirtyBits; - - QAtomicInt m_lastFrameCorrect; - QOpenGLContext *m_glContext; - QOpenGLContext *m_shareContext; - mutable QMutex m_shareContextMutex; - PickBoundingVolumeJobPtr m_pickBoundingVolumeJob; - RayCastingJobPtr m_rayCastingJob; - - qint64 m_time; - - RenderSettings *m_settings; - - UpdateShaderDataTransformJobPtr m_updateShaderDataTransformJob; - FrameCleanupJobPtr m_cleanupJob; - UpdateWorldTransformJobPtr m_worldTransformJob; - ExpandBoundingVolumeJobPtr m_expandBoundingVolumeJob; - CalculateBoundingVolumeJobPtr m_calculateBoundingVolumeJob; - UpdateWorldBoundingVolumeJobPtr m_updateWorldBoundingVolumeJob; - UpdateTreeEnabledJobPtr m_updateTreeEnabledJob; - SendBufferCaptureJobPtr m_sendBufferCaptureJob; - UpdateSkinningPaletteJobPtr m_updateSkinningPaletteJob; - UpdateLevelOfDetailJobPtr m_updateLevelOfDetailJob; - UpdateMeshTriangleListJobPtr m_updateMeshTriangleListJob; - FilterCompatibleTechniqueJobPtr m_filterCompatibleTechniqueJob; - UpdateEntityLayersJobPtr m_updateEntityLayersJob; - LightGathererPtr m_lightGathererJob; - RenderableEntityFilterPtr m_renderableEntityFilterJob; - ComputableEntityFilterPtr m_computableEntityFilterJob; - - QVector m_pendingRenderCaptureSendRequests; - - void performDraw(RenderCommand *command); - void performCompute(const RenderView *rv, RenderCommand *command); - void createOrUpdateVAO(RenderCommand *command, - HVao *previousVAOHandle, - OpenGLVertexArrayObject **vao); - - SynchronizerJobPtr m_bufferGathererJob; - SynchronizerJobPtr m_vaoGathererJob; - SynchronizerJobPtr m_textureGathererJob; - SynchronizerJobPtr m_sendSetFenceHandlesToFrontendJob; - SynchronizerPostFramePtr m_introspectShaderJob; - SynchronizerJobPtr m_syncLoadingJobs; - SynchronizerJobPtr m_cacheRenderableEntitiesJob; - SynchronizerJobPtr m_cacheComputableEntitiesJob; - SynchronizerJobPtr m_cacheLightsJob; - - void lookForAbandonedVaos(); - void lookForDirtyBuffers(); - void lookForDownloadableBuffers(); - void lookForDirtyTextures(); - void reloadDirtyShaders(); - void sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager); - void sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager); - void sendSetFenceHandlesToFrontend(); - void sendDisablesToFrontend(Qt3DCore::QAspectManager *manager); - - QMutex m_abandonedVaosMutex; - QVector m_abandonedVaos; - - QVector m_dirtyBuffers; - QVector m_downloadableBuffers; - QVector m_dirtyShaders; - QVector m_dirtyTextures; - QVector> m_updatedTextureProperties; - QVector> m_updatedSetFences; - QVector m_updatedDisableSubtreeEnablers; - Qt3DCore::QNodeIdVector m_textureIdsToCleanup; - QVector m_shaderBuilderUpdates; - - bool m_ownedContext; - - OffscreenSurfaceHelper *m_offscreenHelper; - GLResourceManagers *m_glResourceManagers; - QMutex m_offscreenSurfaceMutex; - - QScopedPointer m_commandExecuter; - - mutable QScopedPointer m_frameProfiler; - -#ifdef QT_BUILD_INTERNAL - friend class ::tst_Renderer; -#endif - - QMetaObject::Connection m_contextConnection; - RendererCache m_cache; - bool m_shouldSwapBuffers; - - QVector m_frameGraphLeaves; - QScreen *m_screen = nullptr; - QSharedPointer m_scene2DResourceAccessor; - - Debug::ImGuiRenderer *m_imGuiRenderer; - QList> m_frameMouseEvents; - QList m_frameKeyEvents; - QMutex m_frameEventsMutex; - int m_jobsInLastFrame; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERER_H diff --git a/src/render/renderers/opengl/renderer/renderercache_p.h b/src/render/renderers/opengl/renderer/renderercache_p.h deleted file mode 100644 index 02fe4ff41..000000000 --- a/src/render/renderers/opengl/renderer/renderercache_p.h +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERERCACHE_P_H -#define QT3DRENDER_RENDER_RENDERERCACHE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -struct RendererCache -{ - struct LeafNodeData - { - QVector filterEntitiesByLayer; - MaterialParameterGathererData materialParameterGatherer; - EntityRenderCommandData renderCommandData; - }; - - // Shared amongst all RV cache - QVector renderableEntities; - QVector computeEntities; - QVector gatheredLights; - EnvironmentLight* environmentLight; - - // Per RV cache - QHash leafNodeCache; - - QMutex *mutex() { return &m_mutex; } - -private: - QMutex m_mutex; -}; - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERERCACHE_P_H diff --git a/src/render/renderers/opengl/renderer/renderqueue.cpp b/src/render/renderers/opengl/renderer/renderqueue.cpp deleted file mode 100644 index bd9d3ee59..000000000 --- a/src/render/renderers/opengl/renderer/renderqueue.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderqueue_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -RenderQueue::RenderQueue() - : m_noRender(false) - , m_wasReset(true) - , m_targetRenderViewCount(0) - , m_currentRenderViewCount(0) - , m_currentWorkQueue(1) -{ -} - -int RenderQueue::currentRenderViewCount() const -{ - return m_currentRenderViewCount; -} - -/* - * In case the framegraph changed or when the current number of render queue - * needs to be reset. - */ -void RenderQueue::reset() -{ - m_currentRenderViewCount = 0; - m_targetRenderViewCount = 0; - m_currentWorkQueue.clear(); - m_noRender = false; - m_wasReset = true; -} - -void RenderQueue::setNoRender() -{ - Q_ASSERT(m_targetRenderViewCount == 0); - m_noRender = true; -} - -/* - * Queue up a RenderView for the frame being built. - * Thread safe as this is called from the renderer which is locked. - * Returns true if the renderView is complete - */ -bool RenderQueue::queueRenderView(RenderView *renderView, uint submissionOrderIndex) -{ - Q_ASSERT(!m_noRender); - m_currentWorkQueue[submissionOrderIndex] = renderView; - ++m_currentRenderViewCount; - Q_ASSERT(m_currentRenderViewCount <= m_targetRenderViewCount); - return isFrameQueueComplete(); -} - -/* - * Called by the Rendering Thread to retrieve the a frame queue to render. - * A call to reset is required after rendering of the frame. Otherwise under some - * conditions the current but then invalidated frame queue could be reused. - */ -QVector RenderQueue::nextFrameQueue() -{ - return m_currentWorkQueue; -} - -/* - * Sets the number \a targetRenderViewCount of RenderView objects that make up a frame. - */ -void RenderQueue::setTargetRenderViewCount(int targetRenderViewCount) -{ - Q_ASSERT(!m_noRender); - m_targetRenderViewCount = targetRenderViewCount; - m_currentWorkQueue.resize(targetRenderViewCount); - m_wasReset = false; -} - -/* - * Returns true if all the RenderView objects making up the current frame have been queued. - * Returns false otherwise. - * \note a frameQueue or size 0 is considered incomplete. - */ -bool RenderQueue::isFrameQueueComplete() const -{ - return (m_noRender - || (m_targetRenderViewCount > 0 && m_targetRenderViewCount == m_currentRenderViewCount)); -} - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/renderqueue_p.h b/src/render/renderers/opengl/renderer/renderqueue_p.h deleted file mode 100644 index e565115f2..000000000 --- a/src/render/renderers/opengl/renderer/renderqueue_p.h +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERQUEUE_H -#define QT3DRENDER_RENDER_RENDERQUEUE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class RenderView; - -class Q_AUTOTEST_EXPORT RenderQueue -{ -public: - RenderQueue(); - - void setTargetRenderViewCount(int targetRenderViewCount); - int targetRenderViewCount() const { return m_targetRenderViewCount; } - int currentRenderViewCount() const; - bool isFrameQueueComplete() const; - - bool queueRenderView(RenderView *renderView, uint submissionOrderIndex); - QVector nextFrameQueue(); - void reset(); - - void setNoRender(); - inline bool isNoRender() const { return m_noRender; } - - inline bool wasReset() const { return m_wasReset; } - - inline QMutex *mutex() { return &m_mutex; } - -private: - bool m_noRender; - bool m_wasReset; - int m_targetRenderViewCount; - int m_currentRenderViewCount; - QVector m_currentWorkQueue; - QMutex m_mutex; -}; - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERQUEUE_H diff --git a/src/render/renderers/opengl/renderer/renderview.cpp b/src/render/renderers/opengl/renderer/renderview.cpp deleted file mode 100644 index 6b6de01a7..000000000 --- a/src/render/renderers/opengl/renderer/renderview.cpp +++ /dev/null @@ -1,1236 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderview_p.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#if defined(QT3D_RENDER_VIEW_JOB_TIMINGS) -#include -#endif - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - - -namespace { - -// register our QNodeId's as a metatype during program loading -const int Q_DECL_UNUSED qNodeIdTypeId = qMetaTypeId(); - -const int MAX_LIGHTS = 8; - -#define LIGHT_POSITION_NAME QLatin1String(".position") -#define LIGHT_TYPE_NAME QLatin1String(".type") -#define LIGHT_COLOR_NAME QLatin1String(".color") -#define LIGHT_INTENSITY_NAME QLatin1String(".intensity") - -int LIGHT_COUNT_NAME_ID = 0; -int LIGHT_POSITION_NAMES[MAX_LIGHTS]; -int LIGHT_TYPE_NAMES[MAX_LIGHTS]; -int LIGHT_COLOR_NAMES[MAX_LIGHTS]; -int LIGHT_INTENSITY_NAMES[MAX_LIGHTS]; -QString LIGHT_STRUCT_NAMES[MAX_LIGHTS]; - -int LIGHT_POSITION_UNROLL_NAMES[MAX_LIGHTS]; -int LIGHT_TYPE_UNROLL_NAMES[MAX_LIGHTS]; -int LIGHT_COLOR_UNROLL_NAMES[MAX_LIGHTS]; -int LIGHT_INTENSITY_UNROLL_NAMES[MAX_LIGHTS]; -QString LIGHT_STRUCT_UNROLL_NAMES[MAX_LIGHTS]; - -bool wasInitialized = false; - -} // anonymous namespace - -RenderView::StandardUniformsNameToTypeHash RenderView::ms_standardUniformSetters; - - -RenderView::StandardUniformsNameToTypeHash RenderView::initializeStandardUniformSetters() -{ - RenderView::StandardUniformsNameToTypeHash setters; - - setters.insert(Shader::modelMatrixNameId, ModelMatrix); - setters.insert(Shader::viewMatrixNameId, ViewMatrix); - setters.insert(Shader::projectionMatrixNameId, ProjectionMatrix); - setters.insert(Shader::modelViewMatrixNameId, ModelViewMatrix); - setters.insert(Shader::viewProjectionMatrixNameId, ViewProjectionMatrix); - setters.insert(Shader::modelViewProjectionNameId, ModelViewProjectionMatrix); - setters.insert(Shader::mvpNameId, ModelViewProjectionMatrix); - setters.insert(Shader::inverseModelMatrixNameId, InverseModelMatrix); - setters.insert(Shader::inverseViewMatrixNameId, InverseViewMatrix); - setters.insert(Shader::inverseProjectionMatrixNameId, InverseProjectionMatrix); - setters.insert(Shader::inverseModelViewNameId, InverseModelViewMatrix); - setters.insert(Shader::inverseViewProjectionMatrixNameId, InverseViewProjectionMatrix); - setters.insert(Shader::inverseModelViewProjectionNameId, InverseModelViewProjectionMatrix); - setters.insert(Shader::modelNormalMatrixNameId, ModelNormalMatrix); - setters.insert(Shader::modelViewNormalNameId, ModelViewNormalMatrix); - setters.insert(Shader::viewportMatrixNameId, ViewportMatrix); - setters.insert(Shader::inverseViewportMatrixNameId, InverseViewportMatrix); - setters.insert(Shader::aspectRatioNameId, AspectRatio); - setters.insert(Shader::exposureNameId, Exposure); - setters.insert(Shader::gammaNameId, Gamma); - setters.insert(Shader::timeNameId, Time); - setters.insert(Shader::eyePositionNameId, EyePosition); - setters.insert(Shader::skinningPaletteNameId, SkinningPalette); - - return setters; -} - -// TODO: Move this somewhere global where GraphicsContext::setViewport() can use it too -static QRectF resolveViewport(const QRectF &fractionalViewport, const QSize &surfaceSize) -{ - return QRectF(fractionalViewport.x() * surfaceSize.width(), - (1.0 - fractionalViewport.y() - fractionalViewport.height()) * surfaceSize.height(), - fractionalViewport.width() * surfaceSize.width(), - fractionalViewport.height() * surfaceSize.height()); -} - -static Matrix4x4 getProjectionMatrix(const CameraLens *lens) -{ - if (!lens) - qWarning() << "[Qt3D Renderer] No Camera Lens found. Add a CameraSelector to your Frame Graph or make sure that no entities will be rendered."; - return lens ? lens->projection() : Matrix4x4(); -} - -UniformValue RenderView::standardUniformValue(RenderView::StandardUniform standardUniformType, - Entity *entity, - const Matrix4x4 &model) const -{ - switch (standardUniformType) { - case ModelMatrix: - return UniformValue(model); - case ViewMatrix: - return UniformValue(m_data.m_viewMatrix); - case ProjectionMatrix: - return UniformValue(getProjectionMatrix(m_data.m_renderCameraLens)); - case ModelViewMatrix: - return UniformValue(m_data.m_viewMatrix * model); - case ViewProjectionMatrix: - return UniformValue(getProjectionMatrix(m_data.m_renderCameraLens) * m_data.m_viewMatrix); - case ModelViewProjectionMatrix: - return UniformValue(m_data.m_viewProjectionMatrix * model); - case InverseModelMatrix: - return UniformValue(model.inverted()); - case InverseViewMatrix: - return UniformValue(m_data.m_viewMatrix.inverted()); - case InverseProjectionMatrix: { - return UniformValue(getProjectionMatrix(m_data.m_renderCameraLens).inverted()); - } - case InverseModelViewMatrix: - return UniformValue((m_data.m_viewMatrix * model).inverted()); - case InverseViewProjectionMatrix: { - const Matrix4x4 viewProjectionMatrix = getProjectionMatrix(m_data.m_renderCameraLens) * m_data.m_viewMatrix; - return UniformValue(viewProjectionMatrix.inverted()); - } - case InverseModelViewProjectionMatrix: - return UniformValue((m_data.m_viewProjectionMatrix * model).inverted()); - case ModelNormalMatrix: - return UniformValue(convertToQMatrix4x4(model).normalMatrix()); - case ModelViewNormalMatrix: - return UniformValue(convertToQMatrix4x4(m_data.m_viewMatrix * model).normalMatrix()); - case ViewportMatrix: { - QMatrix4x4 viewportMatrix; - // TO DO: Implement on Matrix4x4 - viewportMatrix.viewport(resolveViewport(m_viewport, m_surfaceSize)); - return UniformValue(Matrix4x4(viewportMatrix)); - } - case InverseViewportMatrix: { - QMatrix4x4 viewportMatrix; - // TO DO: Implement on Matrix4x4 - viewportMatrix.viewport(resolveViewport(m_viewport, m_surfaceSize)); - return UniformValue(Matrix4x4(viewportMatrix.inverted())); - } - case AspectRatio: - return float(m_surfaceSize.width()) / std::max(1.f, float(m_surfaceSize.height())); - case Exposure: - return UniformValue(m_data.m_renderCameraLens ? m_data.m_renderCameraLens->exposure() : 0.0f); - case Gamma: - return UniformValue(m_gamma); - case Time: - return UniformValue(float(m_renderer->time() / 1000000000.0f)); - case EyePosition: - return UniformValue(m_data.m_eyePos); - case SkinningPalette: { - const Armature *armature = entity->renderComponent(); - if (!armature) { - qCWarning(Jobs, "Requesting skinningPalette uniform but no armature set on entity"); - return UniformValue(); - } - return armature->skinningPaletteUniform(); - } - default: - Q_UNREACHABLE(); - return UniformValue(); - } -} - -RenderView::RenderView() - : m_isDownloadBuffersEnable(false) - , m_hasBlitFramebufferInfo(false) - , m_renderer(nullptr) - , m_manager(nullptr) - , m_devicePixelRatio(1.) - , m_viewport(QRectF(0., 0., 1., 1.)) - , m_gamma(2.2f) - , m_surface(nullptr) - , m_clearBuffer(QClearBuffers::None) - , m_clearDepthValue(1.f) - , m_clearStencilValue(0) - , m_stateSet(nullptr) - , m_noDraw(false) - , m_compute(false) - , m_frustumCulling(false) - , m_showDebugOverlay(false) - , m_memoryBarrier(QMemoryBarrier::None) - , m_environmentLight(nullptr) -{ - m_workGroups[0] = 1; - m_workGroups[1] = 1; - m_workGroups[2] = 1; - - if (Q_UNLIKELY(!wasInitialized)) { - // Needed as we can control the init order of static/global variables across compile units - // and this hash relies on the static StringToInt class - wasInitialized = true; - RenderView::ms_standardUniformSetters = RenderView::initializeStandardUniformSetters(); - LIGHT_COUNT_NAME_ID = StringToInt::lookupId(QLatin1String("lightCount")); - for (int i = 0; i < MAX_LIGHTS; ++i) { - Q_STATIC_ASSERT_X(MAX_LIGHTS < 10, "can't use the QChar trick anymore"); - LIGHT_STRUCT_NAMES[i] = QLatin1String("lights[") + QLatin1Char(char('0' + i)) + QLatin1Char(']'); - LIGHT_POSITION_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_POSITION_NAME); - LIGHT_TYPE_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_TYPE_NAME); - LIGHT_COLOR_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_COLOR_NAME); - LIGHT_INTENSITY_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_NAMES[i] + LIGHT_INTENSITY_NAME); - - LIGHT_STRUCT_UNROLL_NAMES[i] = QLatin1String("light_") + QLatin1Char(char('0' + i)); - LIGHT_POSITION_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_POSITION_NAME); - LIGHT_TYPE_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_TYPE_NAME); - LIGHT_COLOR_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_COLOR_NAME); - LIGHT_INTENSITY_UNROLL_NAMES[i] = StringToInt::lookupId(LIGHT_STRUCT_UNROLL_NAMES[i] + LIGHT_INTENSITY_NAME); - } - } -} - -RenderView::~RenderView() -{ - delete m_stateSet; -} - -namespace { - -template -struct AdjacentSubRangeFinder -{ - static bool adjacentSubRange(const RenderCommand &, const RenderCommand &) - { - Q_UNREACHABLE(); - return false; - } -}; - -template<> -struct AdjacentSubRangeFinder -{ - static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) - { - return a.m_changeCost == b.m_changeCost; - } -}; - -template<> -struct AdjacentSubRangeFinder -{ - static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) - { - return a.m_depth == b.m_depth; - } -}; - -template<> -struct AdjacentSubRangeFinder -{ - static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) - { - return a.m_glShader == b.m_glShader; - } -}; - -template<> -struct AdjacentSubRangeFinder -{ - static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) - { - return a.m_depth == b.m_depth; - } -}; - -template<> -struct AdjacentSubRangeFinder -{ - static bool adjacentSubRange(const RenderCommand &a, const RenderCommand &b) - { - // Two renderCommands are adjacent if one contains all the other command's textures - QVector texturesA = a.m_parameterPack.textures(); - QVector texturesB = b.m_parameterPack.textures(); - - if (texturesB.size() > texturesA.size()) - qSwap(texturesA, texturesB); - - // textureB.size() is always <= textureA.size() - for (const ShaderParameterPack::NamedResource &texB : qAsConst(texturesB)) { - if (!texturesA.contains(texB)) - return false; - } - return true; - } -}; - -template -int advanceUntilNonAdjacent(const QVector &commands, - const int beg, const int end, Predicate pred) -{ - int i = beg + 1; - while (i < end) { - if (!pred(*(commands.begin() + beg), *(commands.begin() + i))) - break; - ++i; - } - return i; -} - - -using CommandIt = QVector::iterator; - -template -struct SubRangeSorter -{ - static void sortSubRange(CommandIt begin, const CommandIt end) - { - Q_UNUSED(begin); - Q_UNUSED(end); - Q_UNREACHABLE(); - } -}; - -template<> -struct SubRangeSorter -{ - static void sortSubRange(CommandIt begin, const CommandIt end) - { - std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { - return a.m_changeCost > b.m_changeCost; - }); - } -}; - -template<> -struct SubRangeSorter -{ - static void sortSubRange(CommandIt begin, const CommandIt end) - { - std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { - return a.m_depth > b.m_depth; - }); - } -}; - -template<> -struct SubRangeSorter -{ - static void sortSubRange(CommandIt begin, const CommandIt end) - { - // First we sort by shader - std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { - return a.m_glShader > b.m_glShader; - }); - } -}; - -template<> -struct SubRangeSorter -{ - static void sortSubRange(CommandIt begin, const CommandIt end) - { - std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { - return a.m_depth < b.m_depth; - }); - } -}; - -template<> -struct SubRangeSorter -{ - static void sortSubRange(CommandIt begin, const CommandIt end) - { - std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) { - QVector texturesA = a.m_parameterPack.textures(); - QVector texturesB = b.m_parameterPack.textures(); - - const int originalTextureASize = texturesA.size(); - - if (texturesB.size() > texturesA.size()) - qSwap(texturesA, texturesB); - - int identicalTextureCount = 0; - - for (const ShaderParameterPack::NamedResource &texB : qAsConst(texturesB)) { - if (texturesA.contains(texB)) - ++identicalTextureCount; - } - - return identicalTextureCount < originalTextureASize; - }); - } -}; - -int findSubRange(const QVector &commands, - const int begin, const int end, - const QSortPolicy::SortType sortType) -{ - switch (sortType) { - case QSortPolicy::StateChangeCost: - return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - case QSortPolicy::BackToFront: - return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - case QSortPolicy::Material: - return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - case QSortPolicy::FrontToBack: - return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - case QSortPolicy::Texture: - return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - case QSortPolicy::Uniform: - return end; - default: - Q_UNREACHABLE(); - return end; - } -} - -void sortByMaterial(QVector &commands, int begin, const int end) -{ - // We try to arrange elements so that their rendering cost is minimized for a given shader - int rangeEnd = advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - while (begin != end) { - if (begin + 1 < rangeEnd) { - std::stable_sort(commands.begin() + begin + 1, commands.begin() + rangeEnd, [] (const RenderCommand &a, const RenderCommand &b){ - return a.m_material.handle() < b.m_material.handle(); - }); - } - begin = rangeEnd; - rangeEnd = advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder::adjacentSubRange); - } -} - -void sortCommandRange(QVector &commands, int begin, const int end, const int level, - const QVector &sortingTypes) -{ - if (level >= sortingTypes.size()) - return; - - switch (sortingTypes.at(level)) { - case QSortPolicy::StateChangeCost: - SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); - break; - case QSortPolicy::BackToFront: - SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); - break; - case QSortPolicy::Material: - // Groups all same shader DNA together - SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); - // Group all same material together (same parameters most likely) - sortByMaterial(commands, begin, end); - break; - case QSortPolicy::FrontToBack: - SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); - break; - case QSortPolicy::Texture: - SubRangeSorter::sortSubRange(commands.begin() + begin, commands.begin() + end); - break; - case QSortPolicy::Uniform: - break; - default: - Q_UNREACHABLE(); - } - - // For all sub ranges of adjacent item for sortType[i] - // Perform filtering with sortType[i + 1] - int rangeEnd = findSubRange(commands, begin, end, sortingTypes.at(level)); - while (begin != end) { - sortCommandRange(commands, begin, rangeEnd, level + 1, sortingTypes); - begin = rangeEnd; - rangeEnd = findSubRange(commands, begin, end, sortingTypes.at(level)); - } -} - -} // anonymous - -void RenderView::sort() -{ - // Compares the bitsetKey of the RenderCommands - // Key[Depth | StateCost | Shader] - sortCommandRange(m_commands, 0, m_commands.size(), 0, m_data.m_sortingTypes); - - // For RenderCommand with the same shader - // We compute the adjacent change cost - - // Only perform uniform minimization if we explicitly asked for it - if (!m_data.m_sortingTypes.contains(QSortPolicy::Uniform)) - return; - - // Minimize uniform changes - int i = 0; - const int commandSize = m_commands.size(); - while (i < commandSize) { - int j = i; - - // Advance while commands share the same shader - while (i < commandSize && - m_commands[j].m_glShader == m_commands[i].m_glShader) - ++i; - - if (i - j > 0) { // Several commands have the same shader, so we minimize uniform changes - PackUniformHash cachedUniforms = m_commands[j++].m_parameterPack.uniforms(); - - while (j < i) { - // We need the reference here as we are modifying the original container - // not the copy - PackUniformHash &uniforms = m_commands[j].m_parameterPack.m_uniforms; - - for (int u = 0; u < uniforms.keys.size();) { - // We are comparing the values: - // - raw uniform values - // - the texture Node id if the uniform represents a texture - // since all textures are assigned texture units before the RenderCommands - // sharing the same material (shader) are rendered, we can't have the case - // where two uniforms, referencing the same texture eventually have 2 different - // texture unit values - const int uniformNameId = uniforms.keys.at(u); - const UniformValue &refValue = cachedUniforms.value(uniformNameId); - const UniformValue &newValue = uniforms.values.at(u); - if (newValue == refValue) { - uniforms.erase(u); - } else { - // Record updated value so that subsequent comparison - // for the next command will be made againts latest - // uniform value - cachedUniforms.insert(uniformNameId, newValue); - ++u; - } - } - ++j; - } - } - } -} - -void RenderView::setRenderer(Renderer *renderer) -{ - m_renderer = renderer; - m_manager = renderer->nodeManagers(); -} - -void RenderView::addClearBuffers(const ClearBuffers *cb) { - QClearBuffers::BufferTypeFlags type = cb->type(); - - if (type & QClearBuffers::StencilBuffer) { - m_clearStencilValue = cb->clearStencilValue(); - m_clearBuffer |= QClearBuffers::StencilBuffer; - } - if (type & QClearBuffers::DepthBuffer) { - m_clearDepthValue = cb->clearDepthValue(); - m_clearBuffer |= QClearBuffers::DepthBuffer; - } - // keep track of global ClearColor (if set) and collect all DrawBuffer-specific - // ClearColors - if (type & QClearBuffers::ColorBuffer) { - ClearBufferInfo clearBufferInfo; - clearBufferInfo.clearColor = cb->clearColor(); - - if (cb->clearsAllColorBuffers()) { - m_globalClearColorBuffer = clearBufferInfo; - m_clearBuffer |= QClearBuffers::ColorBuffer; - } else { - if (cb->bufferId()) { - const RenderTargetOutput *targetOutput = m_manager->attachmentManager()->lookupResource(cb->bufferId()); - if (targetOutput) { - clearBufferInfo.attchmentPoint = targetOutput->point(); - // Note: a job is later performed to find the drawIndex from the buffer attachment point - // using the AttachmentPack - m_specificClearColorBuffers.push_back(clearBufferInfo); - } - } - } - } -} - -// If we are there, we know that entity had a GeometryRenderer + Material -EntityRenderCommandData RenderView::buildDrawRenderCommands(const QVector &entities, - int offset, int count) const -{ - GLShaderManager *glShaderManager = m_renderer->glResourceManagers()->glShaderManager(); - EntityRenderCommandData commands; - - commands.reserve(count); - - for (int i = 0; i < count; ++i) { - const int idx = offset + i; - Entity *entity = entities.at(idx); - GeometryRenderer *geometryRenderer = nullptr; - HGeometryRenderer geometryRendererHandle = entity->componentHandle(); - - // There is a geometry renderer with geometry - if ((geometryRenderer = m_manager->geometryRendererManager()->data(geometryRendererHandle)) != nullptr - && geometryRenderer->isEnabled() - && !geometryRenderer->geometryId().isNull()) { - - const Qt3DCore::QNodeId materialComponentId = entity->componentUuid(); - const HMaterial materialHandle = entity->componentHandle(); - const QVector renderPassData = m_parameters.value(materialComponentId); - - HGeometry geometryHandle = m_manager->geometryManager()->lookupHandle(geometryRenderer->geometryId()); - Geometry *geometry = m_manager->geometryManager()->data(geometryHandle); - - // 1 RenderCommand per RenderPass pass on an Entity with a Mesh - for (const RenderPassParameterData &passData : renderPassData) { - // Add the RenderPass Parameters - RenderCommand command = {}; - command.m_geometryRenderer = geometryRendererHandle; - command.m_geometry = geometryHandle; - - command.m_material = materialHandle; - // For RenderPass based states we use the globally set RenderState - // if no renderstates are defined as part of the pass. That means: - // RenderPass { renderStates: [] } will use the states defined by - // StateSet in the FrameGraph - RenderPass *pass = passData.pass; - if (pass->hasRenderStates()) { - command.m_stateSet = RenderStateSetPtr::create(); - addStatesToRenderStateSet(command.m_stateSet.data(), pass->renderStates(), m_manager->renderStateManager()); - if (m_stateSet != nullptr) - command.m_stateSet->merge(m_stateSet); - command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); - } - command.m_shaderId = pass->shaderProgram(); - command.m_glShader = glShaderManager->lookupResource(command.m_shaderId); - - // It takes two frames to have a valid command as we can only - // reference a glShader at frame n if it has been loaded at frame n - 1 - if (!command.m_glShader) - continue; - - { // Scoped to show extent - - // Update the draw command with what's going to be needed for the drawing - int primitiveCount = geometryRenderer->vertexCount(); - int estimatedCount = 0; - Attribute *indexAttribute = nullptr; - Attribute *indirectAttribute = nullptr; - - const QVector attributeIds = geometry->attributes(); - for (Qt3DCore::QNodeId attributeId : attributeIds) { - Attribute *attribute = m_manager->attributeManager()->lookupResource(attributeId); - switch (attribute->attributeType()) { - case QAttribute::IndexAttribute: - indexAttribute = attribute; - break; - case QAttribute::DrawIndirectAttribute: - indirectAttribute = attribute; - break; - case QAttribute::VertexAttribute: - estimatedCount = std::max(int(attribute->count()), estimatedCount); - break; - default: - Q_UNREACHABLE(); - break; - } - } - - command.m_drawIndexed = (indexAttribute != nullptr); - command.m_drawIndirect = (indirectAttribute != nullptr); - - // Update the draw command with all the information required for the drawing - if (command.m_drawIndexed) { - command.m_indexAttributeDataType = GraphicsContext::glDataTypeFromAttributeDataType(indexAttribute->vertexBaseType()); - command.m_indexAttributeByteOffset = indexAttribute->byteOffset() + geometryRenderer->indexBufferByteOffset(); - } - - // Note: we only care about the primitiveCount when using direct draw calls - // For indirect draw calls it is assumed the buffer was properly set already - if (command.m_drawIndirect) { - command.m_indirectAttributeByteOffset = indirectAttribute->byteOffset(); - command.m_indirectDrawBuffer = m_manager->bufferManager()->lookupHandle(indirectAttribute->bufferId()); - } else { - // Use the count specified by the GeometryRender - // If not specify use the indexAttribute count if present - // Otherwise tries to use the count from the attribute with the highest count - if (primitiveCount == 0) { - if (indexAttribute) - primitiveCount = indexAttribute->count(); - else - primitiveCount = estimatedCount; - } - } - - command.m_primitiveCount = primitiveCount; - command.m_primitiveType = geometryRenderer->primitiveType(); - command.m_primitiveRestartEnabled = geometryRenderer->primitiveRestartEnabled(); - command.m_restartIndexValue = geometryRenderer->restartIndexValue(); - command.m_firstInstance = geometryRenderer->firstInstance(); - command.m_instanceCount = geometryRenderer->instanceCount(); - command.m_firstVertex = geometryRenderer->firstVertex(); - command.m_indexOffset = geometryRenderer->indexOffset(); - command.m_verticesPerPatch = geometryRenderer->verticesPerPatch(); - } // scope - - - commands.push_back(entity, - std::move(command), - std::move(passData)); - } - } - } - - return commands; -} - -EntityRenderCommandData RenderView::buildComputeRenderCommands(const QVector &entities, - int offset, int count) const -{ - // If the RenderView contains only a ComputeDispatch then it cares about - // A ComputeDispatch is also implicitely a NoDraw operation - // enabled flag - // layer component - // material/effect/technique/parameters/filters/ - EntityRenderCommandData commands; - GLShaderManager *glShaderManager = m_renderer->glResourceManagers()->glShaderManager(); - - commands.reserve(count); - - for (int i = 0; i < count; ++i) { - const int idx = offset + i; - Entity *entity = entities.at(idx); - ComputeCommand *computeJob = nullptr; - HComputeCommand computeCommandHandle = entity->componentHandle(); - if ((computeJob = nodeManagers()->computeJobManager()->data(computeCommandHandle)) != nullptr - && computeJob->isEnabled()) { - - const Qt3DCore::QNodeId materialComponentId = entity->componentUuid(); - const QVector renderPassData = m_parameters.value(materialComponentId); - - // 1 RenderCommand per RenderPass pass on an Entity with a Mesh - for (const RenderPassParameterData &passData : renderPassData) { - // Add the RenderPass Parameters - RenderCommand command = {}; - RenderPass *pass = passData.pass; - - if (pass->hasRenderStates()) { - command.m_stateSet = RenderStateSetPtr::create(); - addStatesToRenderStateSet(command.m_stateSet.data(), pass->renderStates(), m_manager->renderStateManager()); - - // Merge per pass stateset with global stateset - // so that the local stateset only overrides - if (m_stateSet != nullptr) - command.m_stateSet->merge(m_stateSet); - command.m_changeCost = m_renderer->defaultRenderState()->changeCost(command.m_stateSet.data()); - } - command.m_shaderId = pass->shaderProgram(); - command.m_glShader = glShaderManager->lookupResource(command.m_shaderId); - - // It takes two frames to have a valid command as we can only - // reference a glShader at frame n if it has been loaded at frame n - 1 - if (!command.m_glShader) - continue; - - command.m_computeCommand = computeCommandHandle; - command.m_type = RenderCommand::Compute; - command.m_workGroups[0] = std::max(m_workGroups[0], computeJob->x()); - command.m_workGroups[1] = std::max(m_workGroups[1], computeJob->y()); - command.m_workGroups[2] = std::max(m_workGroups[2], computeJob->z()); - - commands.push_back(entity, - std::move(command), - std::move(passData)); - } - } - } - - return commands; -} - -void RenderView::updateRenderCommand(EntityRenderCommandData *renderCommandData, - int offset, - int count) -{ - // Note: since many threads can be building render commands - // we need to ensure that the UniformBlockValueBuilder they are using - // is only accessed from the same thread - UniformBlockValueBuilder *builder = new UniformBlockValueBuilder(); - builder->shaderDataManager = m_manager->shaderDataManager(); - builder->textureManager = m_manager->textureManager(); - m_localData.setLocalData(builder); - - for (int i = 0, m = count; i < m; ++i) { - const int idx = offset + i; - Entity *entity = renderCommandData->entities.at(idx); - const RenderPassParameterData passData = renderCommandData->passesData.at(idx); - RenderCommand &command = renderCommandData->commands[idx]; - - // Pick which lights to take in to account. - // For now decide based on the distance by taking the MAX_LIGHTS closest lights. - // Replace with more sophisticated mechanisms later. - // Copy vector so that we can sort it concurrently and we only want to sort the one for the current command - QVector lightSources; - EnvironmentLight *environmentLight = nullptr; - - if (command.m_type == RenderCommand::Draw) { - // Project the camera-to-object-center vector onto the camera - // view vector. This gives a depth value suitable as the key - // for BackToFront sorting. - command.m_depth = Vector3D::dotProduct(entity->worldBoundingVolume()->center() - m_data.m_eyePos, m_data.m_eyeViewDir); - - environmentLight = m_environmentLight; - lightSources = m_lightSources; - - if (lightSources.size() > 1) { - const Vector3D entityCenter = entity->worldBoundingVolume()->center(); - std::sort(lightSources.begin(), lightSources.end(), - [&] (const LightSource &a, const LightSource &b) { - const float distA = entityCenter.distanceToPoint(a.entity->worldBoundingVolume()->center()); - const float distB = entityCenter.distanceToPoint(b.entity->worldBoundingVolume()->center()); - return distA < distB; - }); - } - lightSources = lightSources.mid(0, std::max(lightSources.size(), MAX_LIGHTS)); - } else { // Compute - // Note: if frameCount has reached 0 in the previous frame, isEnabled - // would be false - ComputeCommand *computeJob = m_manager->computeJobManager()->data(command.m_computeCommand); - if (computeJob->runType() == QComputeCommand::Manual) - computeJob->updateFrameCount(); - } - - ParameterInfoList globalParameters = passData.parameterInfo; - // setShaderAndUniforms can initialize a localData - // make sure this is cleared before we leave this function - - setShaderAndUniforms(&command, - globalParameters, - entity, - lightSources, - environmentLight); - } - - // We reset the local data once we are done with it - m_localData.setLocalData(nullptr); -} - -void RenderView::updateMatrices() -{ - if (m_data.m_renderCameraNode && m_data.m_renderCameraLens && m_data.m_renderCameraLens->isEnabled()) { - const Matrix4x4 cameraWorld = *(m_data.m_renderCameraNode->worldTransform()); - setViewMatrix(m_data.m_renderCameraLens->viewMatrix(cameraWorld)); - - setViewProjectionMatrix(m_data.m_renderCameraLens->projection() * viewMatrix()); - //To get the eyePosition of the camera, we need to use the inverse of the - //camera's worldTransform matrix. - const Matrix4x4 inverseWorldTransform = viewMatrix().inverted(); - const Vector3D eyePosition(inverseWorldTransform.column(3)); - setEyePosition(eyePosition); - - // Get the viewing direction of the camera. Use the normal matrix to - // ensure non-uniform scale works too. - const QMatrix3x3 normalMat = convertToQMatrix4x4(m_data.m_viewMatrix).normalMatrix(); - // dir = normalize(QVector3D(0, 0, -1) * normalMat) - setEyeViewDirection(Vector3D(-normalMat(2, 0), -normalMat(2, 1), -normalMat(2, 2)).normalized()); - } -} - -void RenderView::setUniformValue(ShaderParameterPack &uniformPack, int nameId, const UniformValue &value) const -{ - // At this point a uniform value can only be a scalar type - // or a Qt3DCore::QNodeId corresponding to a Texture or Image - // ShaderData/Buffers would be handled as UBO/SSBO and would therefore - // not be in the default uniform block - if (value.valueType() == UniformValue::NodeId) { - const Qt3DCore::QNodeId *nodeIds = value.constData(); - - const int uniformArraySize = value.byteSize() / sizeof(Qt3DCore::QNodeId); - UniformValue::ValueType resourceType = UniformValue::TextureValue; - - for (int i = 0; i < uniformArraySize; ++i) { - const Qt3DCore::QNodeId resourceId = nodeIds[i]; - - const Texture *tex = m_manager->textureManager()->lookupResource(resourceId); - if (tex != nullptr) { - uniformPack.setTexture(nameId, i, resourceId); - } else { - const ShaderImage *img = m_manager->shaderImageManager()->lookupResource(resourceId); - if (img != nullptr) { - resourceType = UniformValue::ShaderImageValue; - uniformPack.setImage(nameId, i, resourceId); - } - } - } - - // This uniform will be overridden in SubmissionContext::setParameters - // and -1 values will be replaced by valid Texture or Image units - UniformValue uniformValue(uniformArraySize * sizeof(int), resourceType); - std::fill(uniformValue.data(), uniformValue.data() + uniformArraySize, -1); - uniformPack.setUniform(nameId, uniformValue); - } else { - uniformPack.setUniform(nameId, value); - } -} - -void RenderView::setStandardUniformValue(ShaderParameterPack &uniformPack, - int glslNameId, - int nameId, - Entity *entity, - const Matrix4x4 &worldTransform) const -{ - uniformPack.setUniform(glslNameId, standardUniformValue(ms_standardUniformSetters[nameId], entity, worldTransform)); -} - -void RenderView::setUniformBlockValue(ShaderParameterPack &uniformPack, - GLShader *shader, - const ShaderUniformBlock &block, - const UniformValue &value) const -{ - Q_UNUSED(shader) - - if (value.valueType() == UniformValue::NodeId) { - - Buffer *buffer = nullptr; - if ((buffer = m_manager->bufferManager()->lookupResource(*value.constData())) != nullptr) { - BlockToUBO uniformBlockUBO; - uniformBlockUBO.m_blockIndex = block.m_index; - uniformBlockUBO.m_bufferID = buffer->peerId(); - uniformBlockUBO.m_needsUpdate = false; - uniformPack.setUniformBuffer(std::move(uniformBlockUBO)); - // Buffer update to GL buffer will be done at render time - } - } -} - -void RenderView::setShaderStorageValue(ShaderParameterPack &uniformPack, - GLShader *shader, - const ShaderStorageBlock &block, - const UniformValue &value) const -{ - Q_UNUSED(shader) - if (value.valueType() == UniformValue::NodeId) { - Buffer *buffer = nullptr; - if ((buffer = m_manager->bufferManager()->lookupResource(*value.constData())) != nullptr) { - BlockToSSBO shaderStorageBlock; - shaderStorageBlock.m_blockIndex = block.m_index; - shaderStorageBlock.m_bufferID = buffer->peerId(); - shaderStorageBlock.m_bindingIndex = block.m_binding; - uniformPack.setShaderStorageBuffer(shaderStorageBlock); - // Buffer update to GL buffer will be done at render time - } - } -} - -void RenderView::setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, GLShader *shader, ShaderData *shaderData, const QString &structName) const -{ - UniformBlockValueBuilder *builder = m_localData.localData(); - builder->activeUniformNamesToValue.clear(); - - // Set the view matrix to be used to transform "Transformed" properties in the ShaderData - builder->viewMatrix = m_data.m_viewMatrix; - // Force to update the whole block - builder->updatedPropertiesOnly = false; - // Retrieve names and description of each active uniforms in the uniform block - builder->uniforms = shader->activeUniformsForUniformBlock(-1); - // Build name-value map for the block - builder->buildActiveUniformNameValueMapStructHelper(shaderData, structName); - // Set uniform values for each entrie of the block name-value map - QHash::const_iterator activeValuesIt = builder->activeUniformNamesToValue.constBegin(); - const QHash::const_iterator activeValuesEnd = builder->activeUniformNamesToValue.constEnd(); - - // TO DO: Make the ShaderData store UniformValue - while (activeValuesIt != activeValuesEnd) { - setUniformValue(uniformPack, activeValuesIt.key(), UniformValue::fromVariant(activeValuesIt.value())); - ++activeValuesIt; - } -} - -void RenderView::setShaderAndUniforms(RenderCommand *command, - ParameterInfoList ¶meters, - Entity *entity, - const QVector &activeLightSources, - EnvironmentLight *environmentLight) const -{ - // The VAO Handle is set directly in the renderer thread so as to avoid having to use a mutex here - // Set shader, technique, and effect by basically doing : - // ShaderProgramManager[MaterialManager[frontentEntity->id()]->Effect->Techniques[TechniqueFilter->name]->RenderPasses[RenderPassFilter->name]]; - // The Renderer knows that if one of those is null, a default material / technique / effect as to be used - - // Find all RenderPasses (in order) matching values set in the RenderPassFilter - // Get list of parameters for the Material, Effect, and Technique - // For each ParameterBinder in the RenderPass -> create a QUniformPack - // Once that works, improve that to try and minimize QUniformPack updates - - GLShader *shader = command->m_glShader; - if (shader != nullptr && shader->isLoaded()) { - - // Builds the QUniformPack, sets shader standard uniforms and store attributes name / glname bindings - // If a parameter is defined and not found in the bindings it is assumed to be a binding of Uniform type with the glsl name - // equals to the parameter name - const QVector uniformNamesIds = shader->uniformsNamesIds(); - const QVector standardUniformNamesIds = shader->standardUniformNameIds(); - const QVector uniformBlockNamesIds = shader->uniformBlockNamesIds(); - const QVector shaderStorageBlockNamesIds = shader->storageBlockNamesIds(); - const QVector attributeNamesIds = shader->attributeNamesIds(); - - // Set fragData Name and index - // Later on we might want to relink the shader if attachments have changed - // But for now we set them once and for all - if (!m_renderTarget.isNull() && !shader->isLoaded()) { - QHash fragOutputs; - const auto atts = m_attachmentPack.attachments(); - for (const Attachment &att : atts) { - if (att.m_point <= QRenderTargetOutput::Color15) - fragOutputs.insert(att.m_name, att.m_point); - } - // Set frag outputs in the shaders if hash not empty - if (!fragOutputs.isEmpty()) - shader->setFragOutputs(fragOutputs); - } - - if (!uniformNamesIds.isEmpty() || !standardUniformNamesIds.isEmpty() || - !attributeNamesIds.isEmpty() || - !shaderStorageBlockNamesIds.isEmpty() || !attributeNamesIds.isEmpty()) { - - // Set default standard uniforms without bindings - const Matrix4x4 worldTransform = *(entity->worldTransform()); - - for (const int uniformNameId : standardUniformNamesIds) - setStandardUniformValue(command->m_parameterPack, uniformNameId, uniformNameId, entity, worldTransform); - - // Set default attributes - command->m_activeAttributes = attributeNamesIds; - - // At this point we know whether the command is a valid draw command or not - // We still need to process the uniforms as the command could be a compute command - command->m_isValid = !command->m_activeAttributes.empty(); - - // Parameters remaining could be - // -> uniform scalar / vector - // -> uniform struct / arrays - // -> uniform block / array (4.3) - // -> ssbo block / array (4.3) - - ParameterInfoList::const_iterator it = parameters.cbegin(); - const ParameterInfoList::const_iterator parametersEnd = parameters.cend(); - - while (it != parametersEnd) { - Parameter *param = m_manager->data(it->handle); - const UniformValue &uniformValue = param->uniformValue(); - if (uniformNamesIds.contains(it->nameId)) { // Parameter is a regular uniform - setUniformValue(command->m_parameterPack, it->nameId, uniformValue); - } else if (uniformBlockNamesIds.indexOf(it->nameId) != -1) { // Parameter is a uniform block - setUniformBlockValue(command->m_parameterPack, shader, shader->uniformBlockForBlockNameId(it->nameId), uniformValue); - } else if (shaderStorageBlockNamesIds.indexOf(it->nameId) != -1) { // Parameters is a SSBO - setShaderStorageValue(command->m_parameterPack, shader, shader->storageBlockForBlockNameId(it->nameId), uniformValue); - } else { // Parameter is a struct - ShaderData *shaderData = nullptr; - if (uniformValue.valueType() == UniformValue::NodeId && - (shaderData = m_manager->shaderDataManager()->lookupResource(*uniformValue.constData())) != nullptr) { - // Try to check if we have a struct or array matching a QShaderData parameter - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, StringToInt::lookupString(it->nameId)); - } - // Otherwise: param unused by current shader - } - ++it; - } - - // Lights - - int lightIdx = 0; - for (const LightSource &lightSource : activeLightSources) { - if (lightIdx == MAX_LIGHTS) - break; - Entity *lightEntity = lightSource.entity; - const Matrix4x4 lightWorldTransform = *(lightEntity->worldTransform()); - const Vector3D worldPos = lightWorldTransform * Vector3D(0.0f, 0.0f, 0.0f); - for (Light *light : lightSource.lights) { - if (!light->isEnabled()) - continue; - - ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(light->shaderData()); - if (!shaderData) - continue; - - if (lightIdx == MAX_LIGHTS) - break; - - // Note: implicit conversion of values to UniformValue - setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[lightIdx], worldPos); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[lightIdx], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[lightIdx], 0.5f); - - setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[lightIdx], worldPos); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[lightIdx], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[lightIdx], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[lightIdx], 0.5f); - - - // There is no risk in doing that even if multithreaded - // since we are sure that a shaderData is unique for a given light - // and won't ever be referenced as a Component either - Matrix4x4 *worldTransform = lightEntity->worldTransform(); - if (worldTransform) - shaderData->updateWorldTransform(*worldTransform); - - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_NAMES[lightIdx]); - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, LIGHT_STRUCT_UNROLL_NAMES[lightIdx]); - ++lightIdx; - } - } - - if (uniformNamesIds.contains(LIGHT_COUNT_NAME_ID)) - setUniformValue(command->m_parameterPack, LIGHT_COUNT_NAME_ID, UniformValue(qMax((environmentLight ? 0 : 1), lightIdx))); - - // If no active light sources and no environment light, add a default light - if (activeLightSources.isEmpty() && !environmentLight) { - // Note: implicit conversion of values to UniformValue - setUniformValue(command->m_parameterPack, LIGHT_POSITION_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_NAMES[0], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_NAMES[0], 0.5f); - - setUniformValue(command->m_parameterPack, LIGHT_POSITION_UNROLL_NAMES[0], Vector3D(10.0f, 10.0f, 0.0f)); - setUniformValue(command->m_parameterPack, LIGHT_TYPE_UNROLL_NAMES[0], int(QAbstractLight::PointLight)); - setUniformValue(command->m_parameterPack, LIGHT_COLOR_UNROLL_NAMES[0], Vector3D(1.0f, 1.0f, 1.0f)); - setUniformValue(command->m_parameterPack, LIGHT_INTENSITY_UNROLL_NAMES[0], 0.5f); - } - - // Environment Light - int envLightCount = 0; - if (environmentLight && environmentLight->isEnabled()) { - ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(environmentLight->shaderData()); - if (shaderData) { - setDefaultUniformBlockShaderDataValue(command->m_parameterPack, shader, shaderData, QStringLiteral("envLight")); - envLightCount = 1; - } - } else { - // with some drivers, samplers (like the envbox sampler) need to be bound even though - // they may not be actually used, otherwise draw calls can fail - static const int irradianceId = StringToInt::lookupId(QLatin1String("envLight.irradiance")); - static const int specularId = StringToInt::lookupId(QLatin1String("envLight.specular")); - setUniformValue(command->m_parameterPack, irradianceId, m_renderer->submissionContext()->maxTextureUnitsCount()); - setUniformValue(command->m_parameterPack, specularId, m_renderer->submissionContext()->maxTextureUnitsCount()); - } - setUniformValue(command->m_parameterPack, StringToInt::lookupId(QStringLiteral("envLightCount")), envLightCount); - } - } -} - -bool RenderView::hasBlitFramebufferInfo() const -{ - return m_hasBlitFramebufferInfo; -} - -void RenderView::setHasBlitFramebufferInfo(bool hasBlitFramebufferInfo) -{ - m_hasBlitFramebufferInfo = hasBlitFramebufferInfo; -} - -BlitFramebufferInfo RenderView::blitFrameBufferInfo() const -{ - return m_blitFrameBufferInfo; -} - -void RenderView::setBlitFrameBufferInfo(const BlitFramebufferInfo &blitFrameBufferInfo) -{ - m_blitFrameBufferInfo = blitFrameBufferInfo; -} - -bool RenderView::isDownloadBuffersEnable() const -{ - return m_isDownloadBuffersEnable; -} - -void RenderView::setIsDownloadBuffersEnable(bool isDownloadBuffersEnable) -{ - m_isDownloadBuffersEnable = isDownloadBuffersEnable; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/renderview_p.h b/src/render/renderers/opengl/renderer/renderview_p.h deleted file mode 100644 index f00228c84..000000000 --- a/src/render/renderers/opengl/renderer/renderview_p.h +++ /dev/null @@ -1,410 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERVIEW_H -#define QT3DRENDER_RENDER_RENDERVIEW_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -// TODO: Move out once this is all refactored -#include - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -class QRenderPass; - -namespace Render { - -class Renderer; -class NodeManagers; -class RenderCommand; -class RenderPassFilter; -class TechniqueFilter; -class ViewportNode; -class Effect; -class RenderPass; - -typedef QPair ActivePropertyContent; -typedef QPair ActiveProperty; - -struct Q_AUTOTEST_EXPORT Plane -{ - explicit Plane(const Vector4D &planeEquation) - : planeEquation(planeEquation) - , normal(Vector3D(planeEquation).normalized()) - , d(planeEquation.w() / Vector3D(planeEquation).length()) - {} - - const Vector4D planeEquation; - const Vector3D normal; - const float d; -}; - -struct Q_AUTOTEST_EXPORT ClearBufferInfo -{ - int drawBufferIndex = 0; - QRenderTargetOutput::AttachmentPoint attchmentPoint = QRenderTargetOutput::Color0; - QVector4D clearColor; -}; - -struct Q_AUTOTEST_EXPORT BlitFramebufferInfo -{ - Qt3DCore::QNodeId sourceRenderTargetId; - Qt3DCore::QNodeId destinationRenderTargetId; - QRect sourceRect; - QRect destinationRect; - Qt3DRender::QRenderTargetOutput::AttachmentPoint sourceAttachmentPoint; - Qt3DRender::QRenderTargetOutput::AttachmentPoint destinationAttachmentPoint; - QBlitFramebuffer::InterpolationMethod interpolationMethod; -}; - -// This class is kind of analogous to RenderBin but I want to avoid trampling -// on that until we get this working - -class Q_AUTOTEST_EXPORT RenderView -{ -public: - RenderView(); - ~RenderView(); - - QT3D_ALIGNED_MALLOC_AND_FREE() - - // TODO: Add a way to specify a sort predicate for the RenderCommands - void sort(); - - void setRenderer(Renderer *renderer); - inline void setSurfaceSize(const QSize &size) Q_DECL_NOTHROW { m_surfaceSize = size; } - inline Renderer *renderer() const Q_DECL_NOTHROW { return m_renderer; } - inline NodeManagers *nodeManagers() const Q_DECL_NOTHROW { return m_manager; } - inline const QSize &surfaceSize() const Q_DECL_NOTHROW { return m_surfaceSize; } - inline void setDevicePixelRatio(qreal r) Q_DECL_NOTHROW { m_devicePixelRatio = r; } - inline qreal devicePixelRatio() const Q_DECL_NOTHROW { return m_devicePixelRatio; } - - inline void setRenderCameraLens(CameraLens *renderCameraLens) Q_DECL_NOTHROW { m_data.m_renderCameraLens = renderCameraLens; } - inline CameraLens *renderCameraLens() const Q_DECL_NOTHROW { return m_data.m_renderCameraLens; } - - inline void setRenderCameraEntity(Entity *renderCameraNode) Q_DECL_NOTHROW { m_data.m_renderCameraNode = renderCameraNode; } - inline Entity *renderCameraEntity() const Q_DECL_NOTHROW { return m_data.m_renderCameraNode; } - - inline void setViewMatrix(const Matrix4x4 &viewMatrix) Q_DECL_NOTHROW { m_data.m_viewMatrix = viewMatrix; } - inline Matrix4x4 viewMatrix() const Q_DECL_NOTHROW { return m_data.m_viewMatrix; } - - inline void setViewProjectionMatrix(const Matrix4x4 &viewProjectionMatrix) Q_DECL_NOTHROW { m_data.m_viewProjectionMatrix = viewProjectionMatrix; } - inline Matrix4x4 viewProjectionMatrix() const Q_DECL_NOTHROW { return m_data.m_viewProjectionMatrix; } - - inline void setEyePosition(const Vector3D &eyePos) Q_DECL_NOTHROW { m_data.m_eyePos = eyePos; } - inline Vector3D eyePosition() const Q_DECL_NOTHROW { return m_data.m_eyePos; } - - inline void setEyeViewDirection(const Vector3D &dir) Q_DECL_NOTHROW { m_data.m_eyeViewDir = dir; } - inline Vector3D eyeViewDirection() const Q_DECL_NOTHROW { return m_data.m_eyeViewDir; } - - inline void appendLayerFilter(const Qt3DCore::QNodeId layerFilterId) Q_DECL_NOTHROW { m_data.m_layerFilterIds.push_back(layerFilterId); } - inline Qt3DCore::QNodeIdVector layerFilters() const Q_DECL_NOTHROW { return m_data.m_layerFilterIds; } - - inline void appendProximityFilterId(const Qt3DCore::QNodeId proximityFilterId) { m_data.m_proximityFilterIds.push_back(proximityFilterId); } - inline Qt3DCore::QNodeIdVector proximityFilterIds() const { return m_data.m_proximityFilterIds; } - - inline void appendInsertFenceId(const Qt3DCore::QNodeId setFenceId) { m_insertFenceIds.push_back(setFenceId); } - // We prefix with get to avoid confusion when it is called - inline Qt3DCore::QNodeIdVector insertFenceIds() const { return m_insertFenceIds; } - - inline void appendWaitFence(const QWaitFenceData &data) { m_waitFences.push_back(data); } - inline QVector waitFences() const { return m_waitFences; } - - inline void setRenderPassFilter(const RenderPassFilter *rpFilter) Q_DECL_NOTHROW { m_data.m_passFilter = rpFilter; } - inline const RenderPassFilter *renderPassFilter() const Q_DECL_NOTHROW { return m_data.m_passFilter; } - - inline void setTechniqueFilter(const TechniqueFilter *filter) Q_DECL_NOTHROW { m_data.m_techniqueFilter = filter; } - inline const TechniqueFilter *techniqueFilter() const Q_DECL_NOTHROW { return m_data.m_techniqueFilter; } - - inline RenderStateSet *stateSet() const Q_DECL_NOTHROW { return m_stateSet; } - void setStateSet(RenderStateSet *stateSet) Q_DECL_NOTHROW { m_stateSet = stateSet; } - - inline bool noDraw() const Q_DECL_NOTHROW { return m_noDraw; } - void setNoDraw(bool noDraw) Q_DECL_NOTHROW { m_noDraw = noDraw; } - - inline bool isCompute() const Q_DECL_NOTHROW { return m_compute; } - void setCompute(bool compute) Q_DECL_NOTHROW { m_compute = compute; } - - void setComputeWorkgroups(int x, int y, int z) Q_DECL_NOTHROW { m_workGroups[0] = x; m_workGroups[1] = y; m_workGroups[2] = z; } - const int *computeWorkGroups() const Q_DECL_NOTHROW { return m_workGroups; } - inline bool frustumCulling() const Q_DECL_NOTHROW { return m_frustumCulling; } - void setFrustumCulling(bool frustumCulling) Q_DECL_NOTHROW { m_frustumCulling = frustumCulling; } - bool showDebugOverlay() const Q_DECL_NOTHROW { return m_showDebugOverlay; } - void setShowDebugOverlay(bool showDebugOverlay) Q_DECL_NOTHROW { m_showDebugOverlay = showDebugOverlay; } - - inline void setMaterialParameterTable(const MaterialParameterGathererData ¶meters) Q_DECL_NOTHROW { m_parameters = parameters; } - - // TODO: Get rid of this overly complex memory management by splitting out the - // InnerData as a RenderViewConfig struct. This can be created by setRenderViewConfigFromFrameGraphLeafNode - // and passed along with the RenderView to the functions that populate the renderview - inline void setViewport(const QRectF &vp) Q_DECL_NOTHROW { m_viewport = vp; } - inline QRectF viewport() const Q_DECL_NOTHROW { return m_viewport; } - - inline float gamma() const Q_DECL_NOTHROW { return m_gamma; } - inline void setGamma(float gamma) Q_DECL_NOTHROW { m_gamma = gamma; } - - // depth and stencil ClearBuffers are cached locally - // color ClearBuffers are collected, as there may be multiple - // color buffers to be cleared. we need to apply all these at rendering - void addClearBuffers(const ClearBuffers *cb); - inline QVector specificClearColorBufferInfo() const { return m_specificClearColorBuffers; } - inline QVector &specificClearColorBufferInfo() { return m_specificClearColorBuffers; } - inline ClearBufferInfo globalClearColorBufferInfo() const { return m_globalClearColorBuffer; } - - inline QClearBuffers::BufferTypeFlags clearTypes() const { return m_clearBuffer; } - inline float clearDepthValue() const { return m_clearDepthValue; } - inline int clearStencilValue() const { return m_clearStencilValue; } - - RenderPassList passesAndParameters(ParameterInfoList *parameter, Entity *node, bool useDefaultMaterials = true); - - EntityRenderCommandData buildDrawRenderCommands(const QVector &entities, - int offset, int count) const; - EntityRenderCommandData buildComputeRenderCommands(const QVector &entities, - int offset, int count) const; - - - void updateRenderCommand(EntityRenderCommandData *renderCommandData, - int offset, int count); - - - void setCommands(const QVector &commands) Q_DECL_NOTHROW { m_commands = commands; } - QVector &commands() { return m_commands; } - QVector commands() const { return m_commands; } - - void setAttachmentPack(const AttachmentPack &pack) { m_attachmentPack = pack; } - const AttachmentPack &attachmentPack() const { return m_attachmentPack; } - - void setRenderTargetId(Qt3DCore::QNodeId renderTargetId) Q_DECL_NOTHROW { m_renderTarget = renderTargetId; } - Qt3DCore::QNodeId renderTargetId() const Q_DECL_NOTHROW { return m_renderTarget; } - - void addSortType(const QVector &sortTypes) { m_data.m_sortingTypes.append(sortTypes); } - - void setSurface(QSurface *surface) { m_surface = surface; } - QSurface *surface() const { return m_surface; } - - void setLightSources(const QVector &lightSources) Q_DECL_NOTHROW { m_lightSources = lightSources; } - void setEnvironmentLight(EnvironmentLight *environmentLight) Q_DECL_NOTHROW { m_environmentLight = environmentLight; } - - void updateMatrices(); - - inline void setRenderCaptureNodeId(const Qt3DCore::QNodeId nodeId) Q_DECL_NOTHROW { m_renderCaptureNodeId = nodeId; } - inline const Qt3DCore::QNodeId renderCaptureNodeId() const Q_DECL_NOTHROW { return m_renderCaptureNodeId; } - inline void setRenderCaptureRequest(const QRenderCaptureRequest& request) Q_DECL_NOTHROW { m_renderCaptureRequest = request; } - inline const QRenderCaptureRequest renderCaptureRequest() const Q_DECL_NOTHROW { return m_renderCaptureRequest; } - - void setMemoryBarrier(QMemoryBarrier::Operations barrier) Q_DECL_NOTHROW { m_memoryBarrier = barrier; } - QMemoryBarrier::Operations memoryBarrier() const Q_DECL_NOTHROW { return m_memoryBarrier; } - - // Helps making the size of RenderView smaller - // Contains all the data needed for the actual building of the RenderView - // But that aren't used later by the Renderer - struct InnerData { - InnerData() - : m_renderCameraLens(nullptr) - , m_renderCameraNode(nullptr) - , m_techniqueFilter(nullptr) - , m_passFilter(nullptr) - { - } - CameraLens *m_renderCameraLens; - Entity *m_renderCameraNode; - const TechniqueFilter *m_techniqueFilter; - const RenderPassFilter *m_passFilter; - Matrix4x4 m_viewMatrix; - Matrix4x4 m_viewProjectionMatrix; - Qt3DCore::QNodeIdVector m_layerFilterIds; - QVector m_sortingTypes; - Vector3D m_eyePos; - Vector3D m_eyeViewDir; - Qt3DCore::QNodeIdVector m_proximityFilterIds; - }; - - bool isDownloadBuffersEnable() const; - void setIsDownloadBuffersEnable(bool isDownloadBuffersEnable); - - BlitFramebufferInfo blitFrameBufferInfo() const; - void setBlitFrameBufferInfo(const BlitFramebufferInfo &blitFrameBufferInfo); - - bool hasBlitFramebufferInfo() const; - void setHasBlitFramebufferInfo(bool hasBlitFramebufferInfo); - -private: - void setShaderAndUniforms(RenderCommand *command, - ParameterInfoList ¶meters, - Entity *entity, - const QVector &activeLightSources, - EnvironmentLight *environmentLight) const; - mutable QThreadStorage m_localData; - - Qt3DCore::QNodeId m_renderCaptureNodeId; - QRenderCaptureRequest m_renderCaptureRequest; - bool m_isDownloadBuffersEnable; - - bool m_hasBlitFramebufferInfo; - BlitFramebufferInfo m_blitFrameBufferInfo; - - Renderer *m_renderer; - NodeManagers *m_manager; - QSize m_surfaceSize; - qreal m_devicePixelRatio; - - InnerData m_data; - - QRectF m_viewport; - float m_gamma; - Qt3DCore::QNodeId m_renderTarget; - QSurface *m_surface; - AttachmentPack m_attachmentPack; - QClearBuffers::BufferTypeFlags m_clearBuffer; - float m_clearDepthValue; - int m_clearStencilValue; - ClearBufferInfo m_globalClearColorBuffer; // global ClearColor - QVector m_specificClearColorBuffers; // different draw buffers with distinct colors - RenderStateSet *m_stateSet; - bool m_noDraw:1; - bool m_compute:1; - bool m_frustumCulling:1; - bool m_showDebugOverlay:1; - int m_workGroups[3]; - QMemoryBarrier::Operations m_memoryBarrier; - QVector m_insertFenceIds; - QVector m_waitFences; - - QVector m_commands; - mutable QVector m_lightSources; - EnvironmentLight *m_environmentLight; - - MaterialParameterGathererData m_parameters; - - enum StandardUniform - { - ModelMatrix, - ViewMatrix, - ProjectionMatrix, - ModelViewMatrix, - ViewProjectionMatrix, - ModelViewProjectionMatrix, - InverseModelMatrix, - InverseViewMatrix, - InverseProjectionMatrix, - InverseModelViewMatrix, - InverseViewProjectionMatrix, - InverseModelViewProjectionMatrix, - ModelNormalMatrix, - ModelViewNormalMatrix, - ViewportMatrix, - InverseViewportMatrix, - AspectRatio, - Time, - Exposure, - Gamma, - EyePosition, - SkinningPalette - }; - - typedef QHash StandardUniformsNameToTypeHash; - static StandardUniformsNameToTypeHash ms_standardUniformSetters; - static StandardUniformsNameToTypeHash initializeStandardUniformSetters(); - - UniformValue standardUniformValue(StandardUniform standardUniformType, - Entity *entity, - const Matrix4x4 &model) const; - - void setUniformValue(ShaderParameterPack &uniformPack, int nameId, const UniformValue &value) const; - void setStandardUniformValue(ShaderParameterPack &uniformPack, - int glslNameId, - int nameId, - Entity *entity, - const Matrix4x4 &worldTransform) const; - void setUniformBlockValue(ShaderParameterPack &uniformPack, - GLShader *shader, - const ShaderUniformBlock &block, - const UniformValue &value) const; - void setShaderStorageValue(ShaderParameterPack &uniformPack, - GLShader *shader, - const ShaderStorageBlock &block, - const UniformValue &value) const; - void setDefaultUniformBlockShaderDataValue(ShaderParameterPack &uniformPack, - GLShader *shader, - ShaderData *shaderData, - const QString &structName) const; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERVIEW_H diff --git a/src/render/renderers/opengl/renderer/renderviewbuilder.cpp b/src/render/renderers/opengl/renderer/renderviewbuilder.cpp deleted file mode 100644 index 4034af146..000000000 --- a/src/render/renderers/opengl/renderer/renderviewbuilder.cpp +++ /dev/null @@ -1,803 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderviewbuilder_p.h" - -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -// In some cases having less jobs is better (especially on fast cpus where -// splitting just adds more overhead). Ideally, we should try to set the value -// depending on the platform/CPU/nbr of cores -const int RenderViewBuilder::m_optimalParallelJobCount = QThread::idealThreadCount(); - -namespace { - -int findIdealNumberOfWorkers(int elementCount, int packetSize = 100) -{ - if (elementCount == 0 || packetSize == 0) - return 0; - return std::min(std::max(elementCount / packetSize, 1), RenderViewBuilder::optimalJobCount()); -} - - -class SyncPreCommandBuilding -{ -public: - explicit SyncPreCommandBuilding(RenderViewInitializerJobPtr renderViewInitializerJob, - const QVector &renderViewCommandBuilderJobs, - Renderer *renderer, - FrameGraphNode *leafNode) - : m_renderViewInitializer(renderViewInitializerJob) - , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) - , m_renderer(renderer) - , m_leafNode(leafNode) - { - } - - void operator()() - { - // Split commands to build among jobs - QMutexLocker lock(m_renderer->cache()->mutex()); - // Rebuild RenderCommands for all entities in RV (ignoring filtering) - RendererCache *cache = m_renderer->cache(); - const RendererCache::LeafNodeData &dataCacheForLeaf = cache->leafNodeCache[m_leafNode]; - RenderView *rv = m_renderViewInitializer->renderView(); - const auto entities = !rv->isCompute() ? cache->renderableEntities : cache->computeEntities; - - rv->setMaterialParameterTable(dataCacheForLeaf.materialParameterGatherer); - - lock.unlock(); - - // Split among the ideal number of command builders - const int idealPacketSize = std::min(std::max(100, entities.size() / RenderViewBuilder::optimalJobCount()), entities.size()); - // Try to split work into an ideal number of workers - const int m = findIdealNumberOfWorkers(entities.size(), idealPacketSize); - - for (int i = 0; i < m; ++i) { - const RenderViewCommandBuilderJobPtr renderViewCommandBuilder = m_renderViewCommandBuilderJobs.at(i); - const int count = (i == m - 1) ? entities.size() - (i * idealPacketSize) : idealPacketSize; - renderViewCommandBuilder->setEntities(entities, i * idealPacketSize, count); - } - } - -private: - RenderViewInitializerJobPtr m_renderViewInitializer; - QVector m_renderViewCommandBuilderJobs; - Renderer *m_renderer; - FrameGraphNode *m_leafNode; -}; - -class SyncRenderViewPostCommandUpdate -{ -public: - explicit SyncRenderViewPostCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob, - const QVector &renderViewCommandUpdateJobs, - Renderer *renderer) - : m_renderViewJob(renderViewJob) - , m_renderViewCommandUpdaterJobs(renderViewCommandUpdateJobs) - , m_renderer(renderer) - {} - - void operator()() - { - // Append all the commands and sort them - RenderView *rv = m_renderViewJob->renderView(); - - const EntityRenderCommandDataPtr commandData = m_renderViewCommandUpdaterJobs.first()->renderables(); - - if (commandData) { - const QVector commands = std::move(commandData->commands); - rv->setCommands(commands); - - // TO DO: Find way to store commands once or at least only when required - // Sort the commands - rv->sort(); - } - - // Enqueue our fully populated RenderView with the RenderThread - m_renderer->enqueueRenderView(rv, m_renderViewJob->submitOrderIndex()); - } - -private: - RenderViewInitializerJobPtr m_renderViewJob; - QVector m_renderViewCommandUpdaterJobs; - Renderer *m_renderer; -}; - -class SyncPreFrustumCulling -{ -public: - explicit SyncPreFrustumCulling(const RenderViewInitializerJobPtr &renderViewJob, - const FrustumCullingJobPtr &frustumCulling) - : m_renderViewJob(renderViewJob) - , m_frustumCullingJob(frustumCulling) - {} - - void operator()() - { - RenderView *rv = m_renderViewJob->renderView(); - - // Update matrices now that all transforms have been updated - rv->updateMatrices(); - - // Frustum culling - m_frustumCullingJob->setViewProjection(rv->viewProjectionMatrix()); - } - -private: - RenderViewInitializerJobPtr m_renderViewJob; - FrustumCullingJobPtr m_frustumCullingJob; -}; - -class SyncRenderViewPostInitialization -{ -public: - explicit SyncRenderViewPostInitialization(const RenderViewInitializerJobPtr &renderViewJob, - const FrustumCullingJobPtr &frustumCullingJob, - const FilterLayerEntityJobPtr &filterEntityByLayerJob, - const FilterProximityDistanceJobPtr &filterProximityJob, - const QVector &materialGathererJobs, - const QVector &renderViewCommandUpdaterJobs, - const QVector &renderViewCommandBuilderJobs) - : m_renderViewJob(renderViewJob) - , m_frustumCullingJob(frustumCullingJob) - , m_filterEntityByLayerJob(filterEntityByLayerJob) - , m_filterProximityJob(filterProximityJob) - , m_materialGathererJobs(materialGathererJobs) - , m_renderViewCommandUpdaterJobs(renderViewCommandUpdaterJobs) - , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) - {} - - void operator()() - { - RenderView *rv = m_renderViewJob->renderView(); - - // Layer filtering - if (!m_filterEntityByLayerJob.isNull()) - m_filterEntityByLayerJob->setLayerFilters(rv->layerFilters()); - - // Proximity filtering - m_filterProximityJob->setProximityFilterIds(rv->proximityFilterIds()); - - // Material Parameter building - for (const auto &materialGatherer : qAsConst(m_materialGathererJobs)) { - materialGatherer->setRenderPassFilter(const_cast(rv->renderPassFilter())); - materialGatherer->setTechniqueFilter(const_cast(rv->techniqueFilter())); - } - - // Command builders and updates - for (const auto &renderViewCommandUpdater : qAsConst(m_renderViewCommandUpdaterJobs)) - renderViewCommandUpdater->setRenderView(rv); - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) - renderViewCommandBuilder->setRenderView(rv); - - // Set whether frustum culling is enabled or not - m_frustumCullingJob->setActive(rv->frustumCulling()); - } - -private: - RenderViewInitializerJobPtr m_renderViewJob; - FrustumCullingJobPtr m_frustumCullingJob; - FilterLayerEntityJobPtr m_filterEntityByLayerJob; - FilterProximityDistanceJobPtr m_filterProximityJob; - QVector m_materialGathererJobs; - QVector m_renderViewCommandUpdaterJobs; - QVector m_renderViewCommandBuilderJobs; -}; - -class SyncRenderViewPreCommandUpdate -{ -public: - explicit SyncRenderViewPreCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob, - const FrustumCullingJobPtr &frustumCullingJob, - const FilterProximityDistanceJobPtr &filterProximityJob, - const QVector &materialGathererJobs, - const QVector &renderViewCommandUpdaterJobs, - const QVector &renderViewCommandBuilderJobs, - Renderer *renderer, - FrameGraphNode *leafNode, - bool fullCommandRebuild) - : m_renderViewJob(renderViewJob) - , m_frustumCullingJob(frustumCullingJob) - , m_filterProximityJob(filterProximityJob) - , m_materialGathererJobs(materialGathererJobs) - , m_renderViewCommandUpdaterJobs(renderViewCommandUpdaterJobs) - , m_renderViewCommandBuilderJobs(renderViewCommandBuilderJobs) - , m_renderer(renderer) - , m_leafNode(leafNode) - , m_fullRebuild(fullCommandRebuild) - {} - - void operator()() - { - // Set the result of previous job computations - // for final RenderCommand building - RenderView *rv = m_renderViewJob->renderView(); - - if (!rv->noDraw()) { - ///////// CACHE LOCKED //////////// - // Retrieve Data from Cache - RendererCache *cache = m_renderer->cache(); - QMutexLocker lock(cache->mutex()); - Q_ASSERT(cache->leafNodeCache.contains(m_leafNode)); - - const bool isDraw = !rv->isCompute(); - const RendererCache::LeafNodeData &dataCacheForLeaf = cache->leafNodeCache[m_leafNode]; - - // Rebuild RenderCommands if required - // This should happen fairly infrequently (FrameGraph Change, Geometry/Material change) - // and allow to skip that step most of the time - if (m_fullRebuild) { - EntityRenderCommandData commandData; - // Reduction - { - int totalCommandCount = 0; - for (const RenderViewCommandBuilderJobPtr &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) - totalCommandCount += renderViewCommandBuilder->commandData().size(); - commandData.reserve(totalCommandCount); - for (const RenderViewCommandBuilderJobPtr &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) - commandData += std::move(renderViewCommandBuilder->commandData()); - } - - - // Store new cache - RendererCache::LeafNodeData &writableCacheForLeaf = cache->leafNodeCache[m_leafNode]; - writableCacheForLeaf.renderCommandData = std::move(commandData); - } - const EntityRenderCommandData commandData = dataCacheForLeaf.renderCommandData; - const QVector filteredEntities = dataCacheForLeaf.filterEntitiesByLayer; - QVector renderableEntities = isDraw ? cache->renderableEntities : cache->computeEntities; - QVector lightSources = cache->gatheredLights; - - rv->setMaterialParameterTable(dataCacheForLeaf.materialParameterGatherer); - rv->setEnvironmentLight(cache->environmentLight); - lock.unlock(); - ///////// END OF CACHE LOCKED //////////// - - // Filter out entities that weren't selected by the layer filters - // Remove all entities from the compute and renderable vectors that aren't in the filtered layer vector - renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, filteredEntities); - - // Set the light sources, with layer filters applied. - for (int i = 0; i < lightSources.count(); ++i) { - if (!filteredEntities.contains(lightSources[i].entity)) - lightSources.removeAt(i--); - } - rv->setLightSources(lightSources); - - if (isDraw) { - // Filter out frustum culled entity for drawable entities - if (rv->frustumCulling()) - renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_frustumCullingJob->visibleEntities()); - // Filter out entities which didn't satisfy proximity filtering - if (!rv->proximityFilterIds().empty()) - renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_filterProximityJob->filteredEntities()); - } - - // Early return in case we have nothing to filter - if (renderableEntities.size() == 0) - return; - - // Filter out Render commands for which the Entity wasn't selected because - // of frustum, proximity or layer filtering - EntityRenderCommandDataPtr filteredCommandData = EntityRenderCommandDataPtr::create(); - filteredCommandData->reserve(renderableEntities.size()); - // Because dataCacheForLeaf.renderableEntities or computeEntities are sorted - // What we get out of EntityRenderCommandData is also sorted by Entity - auto eIt = renderableEntities.cbegin(); - const auto eEnd = renderableEntities.cend(); - int cIt = 0; - const int cEnd = commandData.size(); - - while (eIt != eEnd) { - const Entity *targetEntity = *eIt; - // Advance until we have commands whose Entity has a lower address - // than the selected filtered entity - while (cIt != cEnd && commandData.entities.at(cIt) < targetEntity) - ++cIt; - - // Push pointers to command data for all commands that match the - // entity - while (cIt != cEnd && commandData.entities.at(cIt) == targetEntity) { - filteredCommandData->push_back(commandData.entities.at(cIt), - commandData.commands.at(cIt), - commandData.passesData.at(cIt)); - ++cIt; - } - ++eIt; - } - - // Split among the number of command builders - // The idealPacketSize is at least 100 entities per worker - const int idealPacketSize = std::min(std::max(100, filteredCommandData->size() / RenderViewBuilder::optimalJobCount()), filteredCommandData->size()); - const int m = findIdealNumberOfWorkers(filteredCommandData->size(), idealPacketSize); - - for (int i = 0; i < m; ++i) { - const RenderViewCommandUpdaterJobPtr renderViewCommandBuilder = m_renderViewCommandUpdaterJobs.at(i); - const int count = (i == m - 1) ? filteredCommandData->size() - (i * idealPacketSize) : idealPacketSize; - renderViewCommandBuilder->setRenderables(filteredCommandData, i * idealPacketSize, count); - } - } - } - -private: - RenderViewInitializerJobPtr m_renderViewJob; - FrustumCullingJobPtr m_frustumCullingJob; - FilterProximityDistanceJobPtr m_filterProximityJob; - QVector m_materialGathererJobs; - QVector m_renderViewCommandUpdaterJobs; - QVector m_renderViewCommandBuilderJobs; - Renderer *m_renderer; - FrameGraphNode *m_leafNode; - bool m_fullRebuild; -}; - -class SetClearDrawBufferIndex -{ -public: - explicit SetClearDrawBufferIndex(const RenderViewInitializerJobPtr &renderViewJob) - : m_renderViewJob(renderViewJob) - {} - - void operator()() - { - RenderView *rv = m_renderViewJob->renderView(); - QVector &clearBuffersInfo = rv->specificClearColorBufferInfo(); - const AttachmentPack &attachmentPack = rv->attachmentPack(); - for (ClearBufferInfo &clearBufferInfo : clearBuffersInfo) - clearBufferInfo.drawBufferIndex = attachmentPack.getDrawBufferIndex(clearBufferInfo.attchmentPoint); - - } - -private: - RenderViewInitializerJobPtr m_renderViewJob; -}; - -class SyncFilterEntityByLayer -{ -public: - explicit SyncFilterEntityByLayer(const FilterLayerEntityJobPtr &filterEntityByLayerJob, - Renderer *renderer, - FrameGraphNode *leafNode) - : m_filterEntityByLayerJob(filterEntityByLayerJob) - , m_renderer(renderer) - , m_leafNode(leafNode) - { - } - - void operator()() - { - QMutexLocker lock(m_renderer->cache()->mutex()); - // Save the filtered by layer subset into the cache - const QVector filteredEntities = m_filterEntityByLayerJob->filteredEntities(); - RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; - dataCacheForLeaf.filterEntitiesByLayer = filteredEntities; - } - -private: - FilterLayerEntityJobPtr m_filterEntityByLayerJob; - Renderer *m_renderer; - FrameGraphNode *m_leafNode; -}; - -class SyncMaterialParameterGatherer -{ -public: - explicit SyncMaterialParameterGatherer(const QVector &materialParameterGathererJobs, - Renderer *renderer, - FrameGraphNode *leafNode) - : m_materialParameterGathererJobs(materialParameterGathererJobs) - , m_renderer(renderer) - , m_leafNode(leafNode) - { - } - - void operator()() - { - QMutexLocker lock(m_renderer->cache()->mutex()); - RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode]; - dataCacheForLeaf.materialParameterGatherer.clear(); - - for (const auto &materialGatherer : qAsConst(m_materialParameterGathererJobs)) - dataCacheForLeaf.materialParameterGatherer.unite(materialGatherer->materialToPassAndParameter()); - } - -private: - QVector m_materialParameterGathererJobs; - Renderer *m_renderer; - FrameGraphNode *m_leafNode; -}; - -} // anonymous - -RenderViewBuilder::RenderViewBuilder(Render::FrameGraphNode *leafNode, int renderViewIndex, Renderer *renderer) - : m_leafNode(leafNode) - , m_renderViewIndex(renderViewIndex) - , m_renderer(renderer) - , m_layerCacheNeedsToBeRebuilt(false) - , m_materialGathererCacheNeedsToBeRebuilt(false) - , m_renderCommandCacheNeedsToBeRebuilt(false) - , m_renderViewJob(RenderViewInitializerJobPtr::create()) - , m_filterEntityByLayerJob() - , m_frustumCullingJob(new Render::FrustumCullingJob()) - , m_syncPreFrustumCullingJob(SynchronizerJobPtr::create(SyncPreFrustumCulling(m_renderViewJob, m_frustumCullingJob), JobTypes::SyncFrustumCulling)) - , m_setClearDrawBufferIndexJob(SynchronizerJobPtr::create(SetClearDrawBufferIndex(m_renderViewJob), JobTypes::ClearBufferDrawIndex)) - , m_syncFilterEntityByLayerJob() - , m_filterProximityJob(Render::FilterProximityDistanceJobPtr::create()) -{ -} - -RenderViewInitializerJobPtr RenderViewBuilder::renderViewJob() const -{ - return m_renderViewJob; -} - -FilterLayerEntityJobPtr RenderViewBuilder::filterEntityByLayerJob() const -{ - return m_filterEntityByLayerJob; -} - -FrustumCullingJobPtr RenderViewBuilder::frustumCullingJob() const -{ - return m_frustumCullingJob; -} - -QVector RenderViewBuilder::renderViewCommandUpdaterJobs() const -{ - return m_renderViewCommandUpdaterJobs; -} - -QVector RenderViewBuilder::renderViewCommandBuilderJobs() const -{ - return m_renderViewCommandBuilderJobs; -} - -QVector RenderViewBuilder::materialGathererJobs() const -{ - return m_materialGathererJobs; -} - -SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostInitializationJob() const -{ - return m_syncRenderViewPostInitializationJob; -} - -SynchronizerJobPtr RenderViewBuilder::syncPreFrustumCullingJob() const -{ - return m_syncPreFrustumCullingJob; -} - -SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandBuildingJob() const -{ - return m_syncRenderViewPreCommandBuildingJob; -} - -SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandUpdateJob() const -{ - return m_syncRenderViewPreCommandUpdateJob; -} - -SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostCommandUpdateJob() const -{ - return m_syncRenderViewPostCommandUpdateJob; -} - -SynchronizerJobPtr RenderViewBuilder::setClearDrawBufferIndexJob() const -{ - return m_setClearDrawBufferIndexJob; -} - -SynchronizerJobPtr RenderViewBuilder::syncFilterEntityByLayerJob() const -{ - return m_syncFilterEntityByLayerJob; -} - -SynchronizerJobPtr RenderViewBuilder::syncMaterialGathererJob() const -{ - return m_syncMaterialGathererJob; -} - -FilterProximityDistanceJobPtr RenderViewBuilder::filterProximityJob() const -{ - return m_filterProximityJob; -} - -void RenderViewBuilder::prepareJobs() -{ - // Init what we can here - m_filterProximityJob->setManager(m_renderer->nodeManagers()); - m_frustumCullingJob->setRoot(m_renderer->sceneRoot()); - - if (m_renderCommandCacheNeedsToBeRebuilt) { - - m_renderViewCommandBuilderJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); - for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto renderViewCommandBuilder = Render::RenderViewCommandBuilderJobPtr::create(); - m_renderViewCommandBuilderJobs.push_back(renderViewCommandBuilder); - } - m_syncRenderViewPreCommandBuildingJob = SynchronizerJobPtr::create(SyncPreCommandBuilding(m_renderViewJob, - m_renderViewCommandBuilderJobs, - m_renderer, - m_leafNode), - JobTypes::SyncRenderViewPreCommandBuilding); - } - - m_renderViewJob->setRenderer(m_renderer); - m_renderViewJob->setFrameGraphLeafNode(m_leafNode); - m_renderViewJob->setSubmitOrderIndex(m_renderViewIndex); - - // RenderCommand building is the most consuming task -> split it - // Estimate the number of jobs to create based on the number of entities - m_renderViewCommandUpdaterJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); - for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto renderViewCommandUpdater = Render::RenderViewCommandUpdaterJobPtr::create(); - renderViewCommandUpdater->setRenderer(m_renderer); - m_renderViewCommandUpdaterJobs.push_back(renderViewCommandUpdater); - } - - if (m_materialGathererCacheNeedsToBeRebuilt) { - // Since Material gathering is an heavy task, we split it - const QVector materialHandles = m_renderer->nodeManagers()->materialManager()->activeHandles(); - const int elementsPerJob = materialHandles.size() / RenderViewBuilder::m_optimalParallelJobCount; - const int lastRemaingElements = materialHandles.size() % RenderViewBuilder::m_optimalParallelJobCount; - m_materialGathererJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); - for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto materialGatherer = Render::MaterialParameterGathererJobPtr::create(); - materialGatherer->setNodeManagers(m_renderer->nodeManagers()); - if (i == RenderViewBuilder::m_optimalParallelJobCount - 1) - materialGatherer->setHandles(materialHandles.mid(i * elementsPerJob, elementsPerJob + lastRemaingElements)); - else - materialGatherer->setHandles(materialHandles.mid(i * elementsPerJob, elementsPerJob)); - m_materialGathererJobs.push_back(materialGatherer); - } - m_syncMaterialGathererJob = SynchronizerJobPtr::create(SyncMaterialParameterGatherer(m_materialGathererJobs, - m_renderer, - m_leafNode), - JobTypes::SyncMaterialGatherer); - } - - if (m_layerCacheNeedsToBeRebuilt) { - m_filterEntityByLayerJob = Render::FilterLayerEntityJobPtr::create(); - m_filterEntityByLayerJob->setManager(m_renderer->nodeManagers()); - m_syncFilterEntityByLayerJob = SynchronizerJobPtr::create(SyncFilterEntityByLayer(m_filterEntityByLayerJob, - m_renderer, - m_leafNode), - JobTypes::SyncFilterEntityByLayer); - } - - m_syncRenderViewPreCommandUpdateJob = SynchronizerJobPtr::create(SyncRenderViewPreCommandUpdate(m_renderViewJob, - m_frustumCullingJob, - m_filterProximityJob, - m_materialGathererJobs, - m_renderViewCommandUpdaterJobs, - m_renderViewCommandBuilderJobs, - m_renderer, - m_leafNode, - m_renderCommandCacheNeedsToBeRebuilt), - JobTypes::SyncRenderViewPreCommandUpdate); - - m_syncRenderViewPostCommandUpdateJob = SynchronizerJobPtr::create(SyncRenderViewPostCommandUpdate(m_renderViewJob, - m_renderViewCommandUpdaterJobs, - m_renderer), - JobTypes::SyncRenderViewPostCommandUpdate); - - m_syncRenderViewPostInitializationJob = SynchronizerJobPtr::create(SyncRenderViewPostInitialization(m_renderViewJob, - m_frustumCullingJob, - m_filterEntityByLayerJob, - m_filterProximityJob, - m_materialGathererJobs, - m_renderViewCommandUpdaterJobs, - m_renderViewCommandBuilderJobs), - JobTypes::SyncRenderViewInitialization); -} - -QVector RenderViewBuilder::buildJobHierachy() const -{ - QVector jobs; - - jobs.reserve(m_materialGathererJobs.size() + m_renderViewCommandUpdaterJobs.size() + 11); - - // Set dependencies - - // Finish the skinning palette job before processing renderviews - // TODO: Maybe only update skinning palettes for non-culled entities - m_renderViewJob->addDependency(m_renderer->updateSkinningPaletteJob()); - - m_syncPreFrustumCullingJob->addDependency(m_renderer->updateWorldTransformJob()); - m_syncPreFrustumCullingJob->addDependency(m_renderer->updateShaderDataTransformJob()); - m_syncPreFrustumCullingJob->addDependency(m_syncRenderViewPostInitializationJob); - - m_frustumCullingJob->addDependency(m_renderer->expandBoundingVolumeJob()); - m_frustumCullingJob->addDependency(m_syncPreFrustumCullingJob); - - m_setClearDrawBufferIndexJob->addDependency(m_syncRenderViewPostInitializationJob); - - m_syncRenderViewPostInitializationJob->addDependency(m_renderViewJob); - - m_filterProximityJob->addDependency(m_renderer->expandBoundingVolumeJob()); - m_filterProximityJob->addDependency(m_syncRenderViewPostInitializationJob); - - m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncRenderViewPostInitializationJob); - m_syncRenderViewPreCommandUpdateJob->addDependency(m_filterProximityJob); - m_syncRenderViewPreCommandUpdateJob->addDependency(m_frustumCullingJob); - - // Ensure the RenderThread won't be able to process dirtyResources - // before they have been completely gathered - m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->introspectShadersJob()); - m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->bufferGathererJob()); - m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->textureGathererJob()); - m_syncRenderViewPreCommandUpdateJob->addDependency(m_renderer->cacheLightJob()); - - for (const auto &renderViewCommandUpdater : qAsConst(m_renderViewCommandUpdaterJobs)) { - renderViewCommandUpdater->addDependency(m_syncRenderViewPreCommandUpdateJob); - m_syncRenderViewPostCommandUpdateJob->addDependency(renderViewCommandUpdater); - } - - m_renderer->frameCleanupJob()->addDependency(m_syncRenderViewPostCommandUpdateJob); - m_renderer->frameCleanupJob()->addDependency(m_setClearDrawBufferIndexJob); - - // Add jobs - jobs.push_back(m_renderViewJob); // Step 1 - - jobs.push_back(m_syncRenderViewPostInitializationJob); // Step 2 - - if (m_renderCommandCacheNeedsToBeRebuilt) { // Step 3 - m_syncRenderViewPreCommandBuildingJob->addDependency(m_renderer->cacheComputableEntitiesJob()); - m_syncRenderViewPreCommandBuildingJob->addDependency(m_renderer->cacheRenderableEntitiesJob()); - m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncRenderViewPostInitializationJob); - - if (m_materialGathererCacheNeedsToBeRebuilt) - m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncMaterialGathererJob); - - jobs.push_back(m_syncRenderViewPreCommandBuildingJob); - - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandBuilderJobs)) { - renderViewCommandBuilder->addDependency(m_syncRenderViewPreCommandBuildingJob); - m_syncRenderViewPreCommandUpdateJob->addDependency(renderViewCommandBuilder); - jobs.push_back(renderViewCommandBuilder); - } - } - - if (m_layerCacheNeedsToBeRebuilt) { - m_filterEntityByLayerJob->addDependency(m_renderer->updateEntityLayersJob()); - m_filterEntityByLayerJob->addDependency(m_syncRenderViewPostInitializationJob); - m_filterEntityByLayerJob->addDependency(m_renderer->updateTreeEnabledJob()); - - m_syncFilterEntityByLayerJob->addDependency(m_filterEntityByLayerJob); - m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncFilterEntityByLayerJob); - - jobs.push_back(m_filterEntityByLayerJob); // Step 3 - jobs.push_back(m_syncFilterEntityByLayerJob); // Step 4 - } - jobs.push_back(m_syncPreFrustumCullingJob); // Step 3 - jobs.push_back(m_filterProximityJob); // Step 3 - jobs.push_back(m_setClearDrawBufferIndexJob); // Step 3 - - if (m_materialGathererCacheNeedsToBeRebuilt) { - for (const auto &materialGatherer : qAsConst(m_materialGathererJobs)) { - materialGatherer->addDependency(m_syncRenderViewPostInitializationJob); - materialGatherer->addDependency(m_renderer->introspectShadersJob()); - materialGatherer->addDependency(m_renderer->filterCompatibleTechniqueJob()); - jobs.push_back(materialGatherer); // Step3 - m_syncMaterialGathererJob->addDependency(materialGatherer); - } - m_syncRenderViewPreCommandUpdateJob->addDependency(m_syncMaterialGathererJob); - - jobs.push_back(m_syncMaterialGathererJob); // Step 3 - } - - jobs.push_back(m_frustumCullingJob); // Step 4 - jobs.push_back(m_syncRenderViewPreCommandUpdateJob); // Step 5 - - // Build RenderCommands or Update RenderCommand Uniforms - for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewCommandUpdaterJobs)) // Step 6 - jobs.push_back(renderViewCommandBuilder); - - jobs.push_back(m_syncRenderViewPostCommandUpdateJob); // Step 7 - - return jobs; -} - -Renderer *RenderViewBuilder::renderer() const -{ - return m_renderer; -} - -int RenderViewBuilder::renderViewIndex() const -{ - return m_renderViewIndex; -} - -void RenderViewBuilder::setLayerCacheNeedsToBeRebuilt(bool needsToBeRebuilt) -{ - m_layerCacheNeedsToBeRebuilt = needsToBeRebuilt; -} - -bool RenderViewBuilder::layerCacheNeedsToBeRebuilt() const -{ - return m_layerCacheNeedsToBeRebuilt; -} - -void RenderViewBuilder::setMaterialGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt) -{ - m_materialGathererCacheNeedsToBeRebuilt = needsToBeRebuilt; -} - -bool RenderViewBuilder::materialGathererCacheNeedsToBeRebuilt() const -{ - return m_materialGathererCacheNeedsToBeRebuilt; -} - -void RenderViewBuilder::setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt) -{ - m_renderCommandCacheNeedsToBeRebuilt = needsToBeRebuilt; -} - -bool RenderViewBuilder::renderCommandCacheNeedsToBeRebuilt() const -{ - return m_renderCommandCacheNeedsToBeRebuilt; -} - -int RenderViewBuilder::optimalJobCount() -{ - return RenderViewBuilder::m_optimalParallelJobCount; -} - -QVector RenderViewBuilder::entitiesInSubset(const QVector &entities, const QVector &subset) -{ - QVector intersection; - intersection.reserve(qMin(entities.size(), subset.size())); - std::set_intersection(entities.begin(), entities.end(), - subset.begin(), subset.end(), - std::back_inserter(intersection)); - - return intersection; -} - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderer/renderviewbuilder_p.h b/src/render/renderers/opengl/renderer/renderviewbuilder_p.h deleted file mode 100644 index a2ab80e7e..000000000 --- a/src/render/renderers/opengl/renderer/renderviewbuilder_p.h +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERVIEWBUILDER_H -#define QT3DRENDER_RENDER_RENDERVIEWBUILDER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -class Renderer; - -using SynchronizerJobPtr = GenericLambdaJobPtr>; - -class Q_AUTOTEST_EXPORT RenderViewBuilder -{ -public: - explicit RenderViewBuilder(Render::FrameGraphNode *leafNode, int renderViewIndex, Renderer *renderer); - - RenderViewInitializerJobPtr renderViewJob() const; - FilterLayerEntityJobPtr filterEntityByLayerJob() const; - FrustumCullingJobPtr frustumCullingJob() const; - QVector renderViewCommandBuilderJobs() const; - QVector renderViewCommandUpdaterJobs() const; - QVector materialGathererJobs() const; - SynchronizerJobPtr syncRenderViewPostInitializationJob() const; - SynchronizerJobPtr syncPreFrustumCullingJob() const; - SynchronizerJobPtr syncRenderViewPreCommandBuildingJob() const; - SynchronizerJobPtr syncRenderViewPreCommandUpdateJob() const; - SynchronizerJobPtr syncRenderViewPostCommandUpdateJob() const; - SynchronizerJobPtr setClearDrawBufferIndexJob() const; - SynchronizerJobPtr syncFilterEntityByLayerJob() const; - FilterProximityDistanceJobPtr filterProximityJob() const; - SynchronizerJobPtr syncMaterialGathererJob() const; - - void prepareJobs(); - QVector buildJobHierachy() const; - - Renderer *renderer() const; - int renderViewIndex() const; - - void setLayerCacheNeedsToBeRebuilt(bool needsToBeRebuilt); - bool layerCacheNeedsToBeRebuilt() const; - void setMaterialGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt); - bool materialGathererCacheNeedsToBeRebuilt() const; - void setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt); - bool renderCommandCacheNeedsToBeRebuilt() const; - - static int optimalJobCount(); - static QVector entitiesInSubset(const QVector &entities, const QVector &subset); - -private: - Render::FrameGraphNode *m_leafNode; - const int m_renderViewIndex; - Renderer *m_renderer; - bool m_layerCacheNeedsToBeRebuilt; - bool m_materialGathererCacheNeedsToBeRebuilt; - bool m_renderCommandCacheNeedsToBeRebuilt; - - RenderViewInitializerJobPtr m_renderViewJob; - FilterLayerEntityJobPtr m_filterEntityByLayerJob; - FrustumCullingJobPtr m_frustumCullingJob; - QVector m_renderViewCommandBuilderJobs; - QVector m_renderViewCommandUpdaterJobs; - QVector m_materialGathererJobs; - - SynchronizerJobPtr m_syncRenderViewPostInitializationJob; - SynchronizerJobPtr m_syncPreFrustumCullingJob; - SynchronizerJobPtr m_syncRenderViewPreCommandBuildingJob; - SynchronizerJobPtr m_syncRenderViewPreCommandUpdateJob; - SynchronizerJobPtr m_syncRenderViewPostCommandUpdateJob; - SynchronizerJobPtr m_setClearDrawBufferIndexJob; - SynchronizerJobPtr m_syncFilterEntityByLayerJob; - SynchronizerJobPtr m_syncMaterialGathererJob; - FilterProximityDistanceJobPtr m_filterProximityJob; - - static const int m_optimalParallelJobCount; -}; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERVIEWBUILDER_H diff --git a/src/render/renderers/opengl/renderer/shaderparameterpack.cpp b/src/render/renderers/opengl/renderer/shaderparameterpack.cpp deleted file mode 100644 index 1cfb59343..000000000 --- a/src/render/renderers/opengl/renderer/shaderparameterpack.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "shaderparameterpack_p.h" - -#include -#include - -#include - -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -ShaderParameterPack::~ShaderParameterPack() -{ -} - -void ShaderParameterPack::setUniform(const int glslNameId, const UniformValue &val) -{ - m_uniforms.insert(glslNameId, val); -} - -void ShaderParameterPack::setTexture(const int glslNameId, int uniformArrayIndex, Qt3DCore::QNodeId texId) -{ - for (int t=0; t -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLShaderProgram; - -namespace Qt3DCore { -class QFrameAllocator; -} - -namespace Qt3DRender { -namespace Render { - -class GraphicsContext; - -struct BlockToUBO { - int m_blockIndex; - Qt3DCore::QNodeId m_bufferID; - bool m_needsUpdate; - QHash m_updatedProperties; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, BlockToUBO, Q_MOVABLE_TYPE) - -struct BlockToSSBO { - int m_blockIndex; - int m_bindingIndex; - Qt3DCore::QNodeId m_bufferID; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, BlockToSSBO, Q_PRIMITIVE_TYPE) - - -struct PackUniformHash -{ - QVector keys; - QVector values; - - PackUniformHash() - { - keys.reserve(10); - values.reserve(10); - } - - void insert(int key, const UniformValue &value) - { - const int idx = keys.indexOf(key); - if (idx != -1) { - values[idx] = value; - } else { - keys.push_back(key); - values.push_back(value); - } - } - - UniformValue value(int key) const - { - const int idx = keys.indexOf(key); - if (idx != -1) - return values.at(idx); - return UniformValue(); - } - - UniformValue& value(int key) - { - const int idx = keys.indexOf(key); - if (idx != -1) - return values[idx]; - insert(key, UniformValue()); - return value(key); - } - - void erase(int idx) - { - keys.removeAt(idx); - values.removeAt(idx); - } - - bool contains(int key) const - { - return keys.contains(key); - } -}; - -class Q_AUTOTEST_EXPORT ShaderParameterPack -{ -public: - ~ShaderParameterPack(); - - void setUniform(const int glslNameId, const UniformValue &val); - void setTexture(const int glslNameId, int uniformArrayIndex, Qt3DCore::QNodeId id); - void setImage(const int glslNameId, int uniformArrayIndex, Qt3DCore::QNodeId id); - - void setUniformBuffer(BlockToUBO blockToUBO); - void setShaderStorageBuffer(BlockToSSBO blockToSSBO); - void setSubmissionUniform(const ShaderUniform &uniform); - - inline PackUniformHash &uniforms() { return m_uniforms; } - inline const PackUniformHash &uniforms() const { return m_uniforms; } - UniformValue uniform(const int glslNameId) const { return m_uniforms.value(glslNameId); } - - - struct NamedResource - { - enum Type { - Texture = 0, - Image - }; - - NamedResource() {} - NamedResource(const int glslNameId, Qt3DCore::QNodeId texId, - int uniformArrayIndex, Type type) - : glslNameId(glslNameId) - , nodeId(texId) - , uniformArrayIndex(uniformArrayIndex) - , type(type) - { } - - int glslNameId; - Qt3DCore::QNodeId nodeId; - int uniformArrayIndex; - Type type; - - bool operator==(const NamedResource &other) const - { - return glslNameId == other.glslNameId && - nodeId == other.nodeId && - uniformArrayIndex == other.uniformArrayIndex && - type == other.type; - } - - bool operator!=(const NamedResource &other) const - { - return !(*this == other); - } - }; - - inline QVector textures() const { return m_textures; } - inline QVector images() const { return m_images; } - inline QVector uniformBuffers() const { return m_uniformBuffers; } - inline QVector shaderStorageBuffers() const { return m_shaderStorageBuffers; } - inline QVector submissionUniforms() const { return m_submissionUniforms; } -private: - PackUniformHash m_uniforms; - - QVector m_textures; - QVector m_images; - QVector m_uniformBuffers; - QVector m_shaderStorageBuffers; - QVector m_submissionUniforms; - - friend class RenderView; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderParameterPack::NamedResource, Q_PRIMITIVE_TYPE) - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -Q_DECLARE_METATYPE(Qt3DRender::Render::ShaderParameterPack) - -#endif // QT3DRENDER_RENDER_SHADERPARAMETERPACK_P_H diff --git a/src/render/renderers/opengl/renderer/shadervariables_p.h b/src/render/renderers/opengl/renderer/shadervariables_p.h deleted file mode 100644 index e0fa07dff..000000000 --- a/src/render/renderers/opengl/renderer/shadervariables_p.h +++ /dev/null @@ -1,152 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_SHADERVARIABLES_P_H -#define QT3DRENDER_RENDER_SHADERVARIABLES_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -struct ShaderAttribute -{ - ShaderAttribute() - : m_nameId(-1) - , m_type(0) - , m_size(0) - , m_location(-1) - {} - - QString m_name; - int m_nameId; - GLenum m_type; - int m_size; - int m_location; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderAttribute, Q_MOVABLE_TYPE) - -struct ShaderUniform -{ - ShaderUniform() - : m_nameId(-1) - , m_type(GL_NONE) - , m_size(0) - , m_offset(-1) - , m_location(-1) - , m_blockIndex(-1) - , m_arrayStride(-1) - , m_matrixStride(-1) - , m_rawByteSize(0) - {} - - QString m_name; - int m_nameId; - GLenum m_type; - int m_size; - int m_offset; // -1 default, >= 0 if uniform defined in uniform block - int m_location; // -1 if uniform defined in a uniform block - int m_blockIndex; // -1 is the default, >= 0 if uniform defined in uniform block - int m_arrayStride; // -1 is the default, >= 0 if uniform defined in uniform block and if it's an array - int m_matrixStride; // -1 is the default, >= 0 uniform defined in uniform block and is a matrix - uint m_rawByteSize; // contains byte size (size / type / strides) - // size, offset and strides are in bytes -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderUniform, Q_MOVABLE_TYPE) - -struct ShaderUniformBlock -{ - ShaderUniformBlock() - : m_nameId(-1) - , m_index(-1) - , m_binding(-1) - , m_activeUniformsCount(0) - , m_size(0) - {} - - QString m_name; - int m_nameId; - int m_index; - int m_binding; - int m_activeUniformsCount; - int m_size; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderUniformBlock, Q_MOVABLE_TYPE) - -struct ShaderStorageBlock -{ - ShaderStorageBlock() - : m_nameId(-1) - , m_index(-1) - , m_binding(-1) - , m_size(0) - , m_activeVariablesCount(0) - {} - - QString m_name; - int m_nameId; - int m_index; - int m_binding; - int m_size; - int m_activeVariablesCount; -}; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderStorageBlock, Q_MOVABLE_TYPE) - -} // namespace Render - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_SHADERVARIABLES_P_H diff --git a/src/render/renderers/opengl/renderstates/renderstates.pri b/src/render/renderers/opengl/renderstates/renderstates.pri deleted file mode 100644 index 10f51a0ed..000000000 --- a/src/render/renderers/opengl/renderstates/renderstates.pri +++ /dev/null @@ -1,7 +0,0 @@ -INCLUDEPATH += $$PWD - -SOURCES += \ - $$PWD/renderstateset.cpp - -HEADERS += \ - $$PWD/renderstateset_p.h diff --git a/src/render/renderers/opengl/renderstates/renderstateset.cpp b/src/render/renderers/opengl/renderstates/renderstateset.cpp deleted file mode 100644 index d667d9c76..000000000 --- a/src/render/renderers/opengl/renderstates/renderstateset.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderstateset_p.h" - -#include - -#include -#include - -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -RenderStateSet::RenderStateSet() - : m_stateMask(0) -{ -} - -RenderStateSet::~RenderStateSet() -{ -} - -template<> -void RenderStateSet::addState(const StateVariant &ds) -{ - m_states.push_back(ds); - m_stateMask |= ds.type; -} - -int RenderStateSet::changeCost(RenderStateSet *previousState) -{ - if (previousState == this) - return 0; - - int cost = 0; - - // first, find cost of any resets - StateMaskSet invOurState = ~stateMask(); - StateMaskSet stateToReset = previousState->stateMask() & invOurState; - - std::bitset<64> bs(stateToReset); - cost += int(bs.count()); - - // now, find out how many states we're changing - for (const StateVariant &ds : qAsConst(m_states)) { - // if the other state contains matching, then doesn't - // contribute to cost at all - if (previousState->contains(ds)) - continue; - - // flat cost for now; could be replaced with a cost() method on - // RenderState - cost += 2; - } - - return cost; -} - -StateMaskSet RenderStateSet::stateMask() const -{ - return m_stateMask; -} - -// This modifies our state to add states from others -// if we don't already contain a state with that type set -void RenderStateSet::merge(RenderStateSet *other) -{ - m_stateMask |= other->stateMask(); - const QVector otherStates = other->states(); - - // We only add states which are new (different type) - for (const StateVariant &otherState : otherStates) { - const bool canAdd = canAddStateOfType(otherState.type); - if (canAdd) - m_states.push_back(otherState); - } -} - -bool RenderStateSet::canAddStateOfType(StateMask type) const -{ - return !hasStateOfType(type) || allowMultipleStatesOfType(type); -} - -bool RenderStateSet::hasStateOfType(StateMask type) const -{ - return (type & stateMask()); -} - -bool RenderStateSet::allowMultipleStatesOfType(StateMask type) const -{ - return (type == BlendEquationArgumentsMask) || - (type == ClipPlaneMask); -} - -bool RenderStateSet::contains(const StateVariant &ds) const -{ - // trivial reject using the state mask bits - if (!(ds.type & stateMask())) - return false; - - for (const StateVariant &rs : m_states) { - if (rs == ds) - return true; - } - return false; -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/renderstates/renderstateset_p.h b/src/render/renderers/opengl/renderstates/renderstateset_p.h deleted file mode 100644 index c2f3a0219..000000000 --- a/src/render/renderers/opengl/renderstates/renderstateset_p.h +++ /dev/null @@ -1,122 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERSTATE_H -#define QT3DRENDER_RENDER_RENDERSTATE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -class QRenderState; - -namespace Render { - -class RenderState; - -class RenderStateSet -{ -public: - RenderStateSet(); - ~RenderStateSet(); - - template - void addState(const GenericState &state) - { - addState(StateVariant::fromValue(state)); - } - - /** - * @brief changeCost - metric of cost to change to this state-set from - * a candidate previous state-set. This is used to find an optimal - * ordering of state-sets when sending draw commands. - * @param previousState - * @return - */ - int changeCost(RenderStateSet* previousState); - - StateMaskSet stateMask() const; - void merge(RenderStateSet *other); - - QVector states() const { return m_states; } - - bool canAddStateOfType(StateMask type) const; - - /** - * @brief contains - check if this set contains a matching piece of state - * @param ds - * @return - */ - bool contains(const StateVariant &ds) const; - -private: - bool hasStateOfType(StateMask type) const; - bool allowMultipleStatesOfType(StateMask type) const; - -private: - StateMaskSet m_stateMask; - QVector m_states; -}; - -template<> -void RenderStateSet::addState(const StateVariant &state); - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERSTATE_H diff --git a/src/render/renderers/opengl/textures/gltexture.cpp b/src/render/renderers/opengl/textures/gltexture.cpp deleted file mode 100644 index 20e6007a0..000000000 --- a/src/render/renderers/opengl/textures/gltexture.cpp +++ /dev/null @@ -1,772 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "gltexture_p.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(QT_OPENGL_ES_2) -#include -#include -#endif - -QT_BEGIN_NAMESPACE - -using namespace Qt3DCore; - -namespace Qt3DRender { -namespace Render { - -namespace { - -// This uploadGLData where the data is a fullsize subimage -// as QOpenGLTexture doesn't allow partial subimage uploads -void uploadGLData(QOpenGLTexture *glTex, - int level, int layer, QOpenGLTexture::CubeMapFace face, - const QByteArray &bytes, const QTextureImageDataPtr &data) -{ - if (data->isCompressed()) { - glTex->setCompressedData(level, layer, face, bytes.size(), bytes.constData()); - } else { - QOpenGLPixelTransferOptions uploadOptions; - uploadOptions.setAlignment(1); - glTex->setData(level, layer, face, data->pixelFormat(), data->pixelType(), bytes.constData(), &uploadOptions); - } -} - -// For partial sub image uploads -void uploadGLData(QOpenGLTexture *glTex, - int mipLevel, int layer, QOpenGLTexture::CubeMapFace cubeFace, - int xOffset, int yOffset, int zOffset, - const QByteArray &bytes, const QTextureImageDataPtr &data) -{ - if (data->isCompressed()) { - qWarning() << Q_FUNC_INFO << "Uploading non full sized Compressed Data not supported yet"; - } else { - QOpenGLPixelTransferOptions uploadOptions; - uploadOptions.setAlignment(1); - glTex->setData(xOffset, yOffset, zOffset, - data->width(), data->height(), data->depth(), - mipLevel, layer, cubeFace, data->layers(), - data->pixelFormat(), data->pixelType(), - bytes.constData(), &uploadOptions); - } -} - -} // anonymous - - -GLTexture::GLTexture() - : m_dirtyFlags(None) - , m_gl(nullptr) - , m_renderBuffer(nullptr) - , m_dataFunctor() - , m_pendingDataFunctor(nullptr) - , m_sharedTextureId(-1) - , m_externalRendering(false) - , m_wasTextureRecreated(false) -{ -} - -GLTexture::~GLTexture() -{ -} - -// Must be called from RenderThread with active GL context -void GLTexture::destroy() -{ - delete m_gl; - m_gl = nullptr; - delete m_renderBuffer; - m_renderBuffer = nullptr; - - m_dirtyFlags = None; - m_sharedTextureId = -1; - m_externalRendering = false; - m_wasTextureRecreated = false; - m_dataFunctor.reset(); - m_pendingDataFunctor = nullptr; - - m_properties = {}; - m_parameters = {}; - m_textureData.reset(); - m_images.clear(); - m_imageData.clear(); - m_pendingTextureDataUpdates.clear(); -} - -bool GLTexture::loadTextureDataFromGenerator() -{ - m_textureData = m_dataFunctor->operator()(); - // if there is a texture generator, most properties will be defined by it - if (m_textureData) { - const QAbstractTexture::Target target = m_textureData->target(); - - // If both target and functor return Automatic we are still - // probably loading the texture, return false - if (m_properties.target == QAbstractTexture::TargetAutomatic && - target == QAbstractTexture::TargetAutomatic) { - m_textureData.reset(); - return false; - } - - if (m_properties.target != QAbstractTexture::TargetAutomatic && - target != QAbstractTexture::TargetAutomatic && - m_properties.target != target) { - qWarning() << Q_FUNC_INFO << "Generator and Properties not requesting the same texture target"; - m_textureData.reset(); - return false; - } - - // We take target type from generator if it wasn't explicitly set by the user - if (m_properties.target == QAbstractTexture::TargetAutomatic) - m_properties.target = target; - m_properties.width = m_textureData->width(); - m_properties.height = m_textureData->height(); - m_properties.depth = m_textureData->depth(); - m_properties.layers = m_textureData->layers(); - m_properties.format = m_textureData->format(); - - const QVector imageData = m_textureData->imageData(); - - if (imageData.size() > 0) { - // Set the mips level based on the first image if autoMipMapGeneration is disabled - if (!m_properties.generateMipMaps) - m_properties.mipLevels = imageData.first()->mipLevels(); - } - } - return !m_textureData.isNull(); -} - -void GLTexture::loadTextureDataFromImages() -{ - int maxMipLevel = 0; - for (const Image &img : qAsConst(m_images)) { - const QTextureImageDataPtr imgData = img.generator->operator()(); - // imgData may be null in the following cases: - // - Texture is created with TextureImages which have yet to be - // loaded (skybox where you don't yet know the path, source set by - // a property binding, queued connection ...) - // - TextureImage whose generator failed to return a valid data - // (invalid url, error opening file...) - if (imgData.isNull()) - continue; - - m_imageData.push_back(imgData); - maxMipLevel = qMax(maxMipLevel, img.mipLevel); - - // If the texture doesn't have a texture generator, we will - // derive some properties from the first TextureImage (layer=0, miplvl=0, face=0) - if (!m_textureData && img.layer == 0 && img.mipLevel == 0 && img.face == QAbstractTexture::CubeMapPositiveX) { - if (imgData->width() != -1 && imgData->height() != -1 && imgData->depth() != -1) { - m_properties.width = imgData->width(); - m_properties.height = imgData->height(); - m_properties.depth = imgData->depth(); - } - // Set the format of the texture if the texture format is set to Automatic - if (m_properties.format == QAbstractTexture::Automatic) { - m_properties.format = static_cast(imgData->format()); - } - setDirtyFlag(Properties, true); - } - } - - // make sure the number of mip levels is set when there is no texture data generator - if (!m_dataFunctor) { - m_properties.mipLevels = maxMipLevel + 1; - setDirtyFlag(Properties, true); - } -} - -// Called from RenderThread -GLTexture::TextureUpdateInfo GLTexture::createOrUpdateGLTexture() -{ - TextureUpdateInfo textureInfo; - m_wasTextureRecreated = false; - - const bool hasSharedTextureId = m_sharedTextureId > 0; - // Only load texture data if we are not using a sharedTextureId - // Check if dataFunctor or images have changed - if (!hasSharedTextureId) { - // If dataFunctor exists and we have no data and it hasn´t run yet - if (m_dataFunctor && !m_textureData && m_dataFunctor.get() != m_pendingDataFunctor ) { - const bool successfullyLoadedTextureData = loadTextureDataFromGenerator(); - // If successful, m_textureData has content - if (successfullyLoadedTextureData) { - setDirtyFlag(Properties, true); - setDirtyFlag(TextureData, true); - } else { - if (m_pendingDataFunctor != m_dataFunctor.get()) { - qWarning() << "[Qt3DRender::GLTexture] No QTextureData generated from Texture Generator yet. Texture will be invalid for this frame"; - m_pendingDataFunctor = m_dataFunctor.get(); - } - textureInfo.properties.status = QAbstractTexture::Loading; - return textureInfo; - } - } - - // If images have changed, clear previous images data - // and regenerate m_imageData for the images - if (testDirtyFlag(TextureImageData)) { - m_imageData.clear(); - loadTextureDataFromImages(); - // Mark for upload if we actually have something to upload - if (!m_imageData.empty()) { - setDirtyFlag(TextureData, true); - } - // Reset image flag - setDirtyFlag(TextureImageData, false); - } - - // Don't try to create the texture if the target or format was still not set - // Format should either be set by user or if Automatic - // by either the dataGenerator of the texture or the first Image - // Target should explicitly be set by the user or the dataGenerator - if (m_properties.target == QAbstractTexture::TargetAutomatic || - m_properties.format == QAbstractTexture::Automatic || - m_properties.format == QAbstractTexture::NoFormat) { - textureInfo.properties.status = QAbstractTexture::Error; - return textureInfo; - } - } - - // If the properties changed or texture has become a shared texture from a - // 3rd party engine, we need to destroy and maybe re-allocate the texture - if (testDirtyFlag(Properties) || testDirtyFlag(SharedTextureId)) { - delete m_gl; - m_gl = nullptr; - textureInfo.wasUpdated = true; - // If we are destroyed because of some property change but still have (some) of - // our content data make sure we are marked for upload - // TO DO: We should actually check if the textureData is still correct - // in regard to the size, target and format of the texture though. - if (!testDirtyFlag(SharedTextureId) && - (m_textureData || !m_imageData.empty() || !m_pendingTextureDataUpdates.empty())) - setDirtyFlag(TextureData, true); - } - - m_properties.status = QAbstractTexture::Ready; - - if (testDirtyFlag(SharedTextureId) || hasSharedTextureId) { - // Update m_properties by doing introspection on the texture - if (hasSharedTextureId) - introspectPropertiesFromSharedTextureId(); - setDirtyFlag(SharedTextureId, false); - } else { - // We only build a QOpenGLTexture if we have no shared textureId set - if (!m_gl) { - m_gl = buildGLTexture(); - if (!m_gl) { - qWarning() << "[Qt3DRender::GLTexture] failed to create texture"; - textureInfo.properties.status = QAbstractTexture::Error; - return textureInfo; - } - - m_gl->allocateStorage(); - if (!m_gl->isStorageAllocated()) { - qWarning() << "[Qt3DRender::GLTexture] failed to allocate texture"; - textureInfo.properties.status = QAbstractTexture::Error; - return textureInfo; - } - m_wasTextureRecreated = true; - } - - textureInfo.texture = m_gl; - - // need to (re-)upload texture data? - const bool needsUpload = testDirtyFlag(TextureData); - if (needsUpload) { - uploadGLTextureData(); - setDirtyFlag(TextureData, false); - } - - // need to set texture parameters? - if (testDirtyFlag(Properties) || testDirtyFlag(Parameters)) { - updateGLTextureParameters(); - setDirtyFlag(Properties, false); - setDirtyFlag(Parameters, false); - } - } - - textureInfo.properties = m_properties; - - return textureInfo; -} - -RenderBuffer *GLTexture::getOrCreateRenderBuffer() -{ - if (m_dataFunctor && !m_textureData) { - m_textureData = m_dataFunctor->operator()(); - if (m_textureData) { - if (m_properties.target != QAbstractTexture::TargetAutomatic) - qWarning() << "[Qt3DRender::GLTexture] [renderbuffer] When a texture provides a generator, it's target is expected to be TargetAutomatic"; - - m_properties.width = m_textureData->width(); - m_properties.height = m_textureData->height(); - m_properties.format = m_textureData->format(); - - setDirtyFlag(Properties); - } else { - if (m_pendingDataFunctor != m_dataFunctor.get()) { - qWarning() << "[Qt3DRender::GLTexture] [renderbuffer] No QTextureData generated from Texture Generator yet. Texture will be invalid for this frame"; - m_pendingDataFunctor = m_dataFunctor.get(); - } - return nullptr; - } - } - - if (testDirtyFlag(Properties)) { - delete m_renderBuffer; - m_renderBuffer = nullptr; - } - - if (!m_renderBuffer) - m_renderBuffer = new RenderBuffer(m_properties.width, m_properties.height, m_properties.format); - - setDirtyFlag(Properties, false); - setDirtyFlag(Parameters, false); - - return m_renderBuffer; -} - -// This must be called from the RenderThread -// So GLTexture release from the manager can only be done from that thread -void GLTexture::cleanup() -{ - destroy(); -} - -void GLTexture::setParameters(const TextureParameters ¶ms) -{ - if (m_parameters != params) { - m_parameters = params; - setDirtyFlag(Parameters); - } -} - -void GLTexture::setProperties(const TextureProperties &props) -{ - if (m_properties != props) { - m_properties = props; - setDirtyFlag(Properties); - } -} - -void GLTexture::setImages(const QVector &images) -{ - // check if something has changed at all - bool same = (images.size() == m_images.size()); - if (same) { - for (int i = 0; i < images.size(); i++) { - if (images[i] != m_images[i]) { - same = false; - break; - } - } - } - - - if (!same) { - m_images = images; - requestImageUpload(); - } -} - -void GLTexture::setGenerator(const QTextureGeneratorPtr &generator) -{ - m_textureData.reset(); - m_dataFunctor = generator; - m_pendingDataFunctor = nullptr; - requestUpload(); -} - -void GLTexture::setSharedTextureId(int textureId) -{ - if (m_sharedTextureId != textureId) { - m_sharedTextureId = textureId; - setDirtyFlag(SharedTextureId); - } -} - -void GLTexture::addTextureDataUpdates(const QVector &updates) -{ - m_pendingTextureDataUpdates += updates; - requestUpload(); -} - -// Return nullptr if -// - context cannot be obtained -// - texture hasn't yet been loaded -QOpenGLTexture *GLTexture::buildGLTexture() -{ - QOpenGLContext *ctx = QOpenGLContext::currentContext(); - if (!ctx) { - qWarning() << Q_FUNC_INFO << "requires an OpenGL context"; - return nullptr; - } - - const QAbstractTexture::Target actualTarget = m_properties.target; - if (actualTarget == QAbstractTexture::TargetAutomatic) { - // If the target is automatic at this point, it means that the texture - // hasn't been loaded yet (case of remote urls) and that loading failed - // and that target format couldn't be deduced - return nullptr; - } - - QOpenGLTexture* glTex = new QOpenGLTexture(static_cast(actualTarget)); - - // m_format may not be ES2 compatible. Now it's time to convert it, if necessary. - QAbstractTexture::TextureFormat format = m_properties.format; - if (ctx->isOpenGLES() && ctx->format().majorVersion() < 3) { - switch (m_properties.format) { - case QAbstractTexture::RGBA8_UNorm: - case QAbstractTexture::RGBAFormat: - format = QAbstractTexture::RGBAFormat; - break; - case QAbstractTexture::RGB8_UNorm: - case QAbstractTexture::RGBFormat: - format = QAbstractTexture::RGBFormat; - break; - case QAbstractTexture::DepthFormat: - format = QAbstractTexture::DepthFormat; - break; - default: - auto warning = qWarning(); - warning << "Could not find a matching OpenGL ES 2.0 texture format:"; - QtDebugUtils::formatQEnum(warning, m_properties.format); - break; - } - } - - // Map ETC1 to ETC2 when supported. This allows using features like - // immutable storage as ETC2 is standard in GLES 3.0, while the ETC1 extension - // is written against GLES 1.0. - if (m_properties.format == QAbstractTexture::RGB8_ETC1) { - if ((ctx->isOpenGLES() && ctx->format().majorVersion() >= 3) - || ctx->hasExtension(QByteArrayLiteral("GL_OES_compressed_ETC2_RGB8_texture")) - || ctx->hasExtension(QByteArrayLiteral("GL_ARB_ES3_compatibility"))) - format = m_properties.format = QAbstractTexture::RGB8_ETC2; - } - - glTex->setFormat(m_properties.format == QAbstractTexture::Automatic ? - QOpenGLTexture::NoFormat : - static_cast(format)); - glTex->setSize(m_properties.width, m_properties.height, m_properties.depth); - // Set layers count if texture array - if (actualTarget == QAbstractTexture::Target1DArray || - actualTarget == QAbstractTexture::Target2DArray || - actualTarget == QAbstractTexture::Target2DMultisampleArray || - actualTarget == QAbstractTexture::TargetCubeMapArray) { - glTex->setLayers(m_properties.layers); - } - - if (actualTarget == QAbstractTexture::Target2DMultisample || - actualTarget == QAbstractTexture::Target2DMultisampleArray) { - // Set samples count if multisampled texture - // (multisampled textures don't have mipmaps) - glTex->setSamples(m_properties.samples); - } else if (m_properties.generateMipMaps) { - glTex->setMipLevels(glTex->maximumMipLevels()); - } else { - glTex->setAutoMipMapGenerationEnabled(false); - if (glTex->hasFeature(QOpenGLTexture::TextureMipMapLevel)) { - glTex->setMipBaseLevel(0); - glTex->setMipMaxLevel(m_properties.mipLevels - 1); - } - glTex->setMipLevels(m_properties.mipLevels); - } - - if (!glTex->create()) { - qWarning() << Q_FUNC_INFO << "creating QOpenGLTexture failed"; - return nullptr; - } - - return glTex; -} - -void GLTexture::uploadGLTextureData() -{ - // Upload all QTexImageData set by the QTextureGenerator - if (m_textureData) { - const QVector imgData = m_textureData->imageData(); - - for (const QTextureImageDataPtr &data : imgData) { - const int mipLevels = m_properties.generateMipMaps ? 1 : data->mipLevels(); - - for (int layer = 0; layer < data->layers(); layer++) { - for (int face = 0; face < data->faces(); face++) { - for (int level = 0; level < mipLevels; level++) { - // ensure we don't accidentally cause a detach / copy of the raw bytes - const QByteArray bytes(data->data(layer, face, level)); - uploadGLData(m_gl, level, layer, - static_cast(QOpenGLTexture::CubeMapPositiveX + face), - bytes, data); - } - } - } - } - } - - // Upload all QTexImageData references by the TextureImages - for (int i = 0; i < std::min(m_images.size(), m_imageData.size()); i++) { - const QTextureImageDataPtr &imgData = m_imageData.at(i); - // Here the bytes in the QTextureImageData contain data for a single - // layer, face or mip level, unlike the QTextureGenerator case where - // they are in a single blob. Hence QTextureImageData::data() is not suitable. - const QByteArray bytes(QTextureImageDataPrivate::get(imgData.get())->m_data); - uploadGLData(m_gl, m_images[i].mipLevel, m_images[i].layer, - static_cast(m_images[i].face), - bytes, imgData); - } - // Free up image data once content has been uploaded - // Note: if data functor stores the data, this won't really free anything though - m_imageData.clear(); - - // Update data from TextureUpdates - const QVector textureDataUpdates = std::move(m_pendingTextureDataUpdates); - for (const QTextureDataUpdate &update : textureDataUpdates) { - const QTextureImageDataPtr imgData = update.data(); - - if (!imgData) { - qWarning() << Q_FUNC_INFO << "QTextureDataUpdate no QTextureImageData set"; - continue; - } - - const int xOffset = update.x(); - const int yOffset = update.y(); - const int zOffset = update.z(); - const int xExtent = xOffset + imgData->width(); - const int yExtent = yOffset + imgData->height(); - const int zExtent = zOffset + imgData->depth(); - - // Check update is compatible with our texture - if (xOffset >= m_gl->width() || - yOffset >= m_gl->height() || - zOffset >= m_gl->depth() || - xExtent > m_gl->width() || - yExtent > m_gl->height() || - zExtent > m_gl->depth() || - update.mipLevel() >= m_gl->mipLevels() || - update.layer() >= m_gl->layers()) { - qWarning() << Q_FUNC_INFO << "QTextureDataUpdate incompatible with texture"; - continue; - } - - const QByteArray bytes = (QTextureImageDataPrivate::get(imgData.get())->m_data); - // Here the bytes in the QTextureImageData contain data for a single - // layer, face or mip level, unlike the QTextureGenerator case where - // they are in a single blob. Hence QTextureImageData::data() is not suitable. - - uploadGLData(m_gl, - update.mipLevel(), update.layer(), - static_cast(update.face()), - xOffset, yOffset, zOffset, - bytes, imgData); - } -} - -void GLTexture::updateGLTextureParameters() -{ - const QAbstractTexture::Target actualTarget = m_properties.target; - const bool isMultisampledTexture = (actualTarget == QAbstractTexture::Target2DMultisample || - actualTarget == QAbstractTexture::Target2DMultisampleArray); - // Multisampled textures can only be accessed by texelFetch in shaders - // and don't support wrap modes and mig/mag filtes - if (isMultisampledTexture) - return; - - m_gl->setWrapMode(QOpenGLTexture::DirectionS, static_cast(m_parameters.wrapModeX)); - if (actualTarget != QAbstractTexture::Target1D && - actualTarget != QAbstractTexture::Target1DArray && - actualTarget != QAbstractTexture::TargetBuffer) - m_gl->setWrapMode(QOpenGLTexture::DirectionT, static_cast(m_parameters.wrapModeY)); - if (actualTarget == QAbstractTexture::Target3D) - m_gl->setWrapMode(QOpenGLTexture::DirectionR, static_cast(m_parameters.wrapModeZ)); - m_gl->setMinMagFilters(static_cast(m_parameters.minificationFilter), - static_cast(m_parameters.magnificationFilter)); - if (m_gl->hasFeature(QOpenGLTexture::AnisotropicFiltering)) - m_gl->setMaximumAnisotropy(m_parameters.maximumAnisotropy); - if (m_gl->hasFeature(QOpenGLTexture::TextureComparisonOperators)) { - m_gl->setComparisonFunction(static_cast(m_parameters.comparisonFunction)); - m_gl->setComparisonMode(static_cast(m_parameters.comparisonMode)); - } -} - -void GLTexture::introspectPropertiesFromSharedTextureId() -{ - // We know that the context is active when this function is called - QOpenGLContext *ctx = QOpenGLContext::currentContext(); - if (!ctx) { - qWarning() << Q_FUNC_INFO << "requires an OpenGL context"; - return; - } - QOpenGLFunctions *gl = ctx->functions(); - - // If the user has set the target format himself, we won't try to deduce it - if (m_properties.target != QAbstractTexture::TargetAutomatic) - return; - - const QAbstractTexture::Target targets[] = { - QAbstractTexture::Target2D, - QAbstractTexture::TargetCubeMap, -#ifndef QT_OPENGL_ES_2 - QAbstractTexture::Target1D, - QAbstractTexture::Target1DArray, - QAbstractTexture::Target3D, - QAbstractTexture::Target2DArray, - QAbstractTexture::TargetCubeMapArray, - QAbstractTexture::Target2DMultisample, - QAbstractTexture::Target2DMultisampleArray, - QAbstractTexture::TargetRectangle, - QAbstractTexture::TargetBuffer, -#endif - }; - -#ifndef QT_OPENGL_ES_2 - // Try to find texture target with GL 4.5 functions - const QPair ctxGLVersion = ctx->format().version(); - if (ctxGLVersion.first > 4 || (ctxGLVersion.first == 4 && ctxGLVersion.second >= 5)) { - // Only for GL 4.5+ -#ifdef GL_TEXTURE_TARGET - QOpenGLFunctions_4_5_Core *gl5 = ctx->versionFunctions(); - if (gl5 != nullptr) - gl5->glGetTextureParameteriv(m_sharedTextureId, GL_TEXTURE_TARGET, reinterpret_cast(&m_properties.target)); -#endif - } -#endif - - // If GL 4.5 function unavailable or not working, try a slower way - if (m_properties.target == QAbstractTexture::TargetAutomatic) { - // // OpenGL offers no proper way of querying for the target of a texture given its id - gl->glActiveTexture(GL_TEXTURE0); - - const GLenum targetBindings[] = { - GL_TEXTURE_BINDING_2D, - GL_TEXTURE_BINDING_CUBE_MAP, -#ifndef QT_OPENGL_ES_2 - GL_TEXTURE_BINDING_1D, - GL_TEXTURE_BINDING_1D_ARRAY, - GL_TEXTURE_BINDING_3D, - GL_TEXTURE_BINDING_2D_ARRAY, - GL_TEXTURE_BINDING_CUBE_MAP_ARRAY, - GL_TEXTURE_BINDING_2D_MULTISAMPLE, - GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY, - GL_TEXTURE_BINDING_RECTANGLE, - GL_TEXTURE_BINDING_BUFFER -#endif - }; - - Q_ASSERT(sizeof(targetBindings) / sizeof(targetBindings[0] == sizeof(targets) / sizeof(targets[0]))); - - for (uint i = 0; i < sizeof(targetBindings) / sizeof(targetBindings[0]); ++i) { - const int target = targets[i]; - gl->glBindTexture(target, m_sharedTextureId); - int boundId = 0; - gl->glGetIntegerv(targetBindings[i], &boundId); - gl->glBindTexture(target, 0); - if (boundId == m_sharedTextureId) { - m_properties.target = static_cast(target); - break; - } - } - } - - // Return early if we weren't able to find texture target - if (std::find(std::begin(targets), std::end(targets), m_properties.target) == std::end(targets)) { - qWarning() << "Unable to determine texture target for shared GL texture"; - return; - } - - // Bind texture once we know its target - gl->glBindTexture(m_properties.target, m_sharedTextureId); - - // TO DO: Improve by using glGetTextureParameters when available which - // support direct state access -#ifndef GL_TEXTURE_MAX_LEVEL -#define GL_TEXTURE_MAX_LEVEL 0x813D -#endif - -#ifndef GL_TEXTURE_WRAP_R -#define GL_TEXTURE_WRAP_R 0x8072 -#endif - - gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_MAX_LEVEL, reinterpret_cast(&m_properties.mipLevels)); - gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_MIN_FILTER, reinterpret_cast(&m_parameters.minificationFilter)); - gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_MAG_FILTER, reinterpret_cast(&m_parameters.magnificationFilter)); - gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_WRAP_R, reinterpret_cast(&m_parameters.wrapModeX)); - gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_WRAP_S, reinterpret_cast(&m_parameters.wrapModeY)); - gl->glGetTexParameteriv(int(m_properties.target), GL_TEXTURE_WRAP_T, reinterpret_cast(&m_parameters.wrapModeZ)); - -#ifndef QT_OPENGL_ES_2 - // Try to retrieve dimensions (not available on ES 2.0) - if (!ctx->isOpenGLES()) { - QOpenGLFunctions_3_1 *gl3 = ctx->versionFunctions(); - if (!gl3) { - qWarning() << "Failed to retrieve shared texture dimensions"; - return; - } - - gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_WIDTH, reinterpret_cast(&m_properties.width)); - gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_HEIGHT, reinterpret_cast(&m_properties.height)); - gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_DEPTH, reinterpret_cast(&m_properties.depth)); - gl3->glGetTexLevelParameteriv(int(m_properties.target), 0, GL_TEXTURE_INTERNAL_FORMAT, reinterpret_cast(&m_properties.format)); - } -#endif - - gl->glBindTexture(m_properties.target, 0); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/textures/gltexture_p.h b/src/render/renderers/opengl/textures/gltexture_p.h deleted file mode 100644 index ca851712d..000000000 --- a/src/render/renderers/opengl/textures/gltexture_p.h +++ /dev/null @@ -1,266 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_GLTEXTURE_H -#define QT3DRENDER_RENDER_GLTEXTURE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLTexture; - -namespace Qt3DRender { -namespace Render { - -class TextureImageManager; -class TextureDataManager; -class TextureImageDataManager; -class RenderBuffer; - -/** - * @brief - * Actual implementation of the OpenGL texture object. Makes sure the - * QOpenGLTexture is up-to-date with the generators, properties and parameters - * that were set for this GLTexture. - * - * Can be shared among multiple QTexture backend nodes through the - * GLTextureManager, which will make sure that there are no two GLTextures - * sharing the same texture data. - * - * A GLTexture can be unique though. In that case, it will not be shared - * between QTextures, but private to one QTexture only. - * - * A GLTexture can also represent an OpenGL renderbuffer object. This is used - * only in certain special cases, mainly to provide a packed depth-stencil - * renderbuffer suitable as an FBO attachment with OpenGL ES 3.1 and earlier. - * Such a GLTexture will have no texture object under the hood, and therefore - * the only valid operation is getOrCreateRenderBuffer(). - */ -class Q_AUTOTEST_EXPORT GLTexture -{ -public: - GLTexture(); - ~GLTexture(); - - enum DirtyFlag { - None = 0, - TextureData = (1 << 0), // texture data needs uploading to GPU - Properties = (1 << 1), // texture needs to be (re-)created - Parameters = (1 << 2), // texture parameters need to be (re-)set - SharedTextureId = (1 << 3), // texture id from shared context - TextureImageData = (1 << 4) // texture image data needs uploading - }; - - /** - * Helper class to hold the defining properties of TextureImages - */ - struct Image { - QTextureImageDataGeneratorPtr generator; - int layer; - int mipLevel; - QAbstractTexture::CubeMapFace face; - - inline bool operator==(const Image &o) const { - bool sameGenerators = (generator == o.generator) - || (!generator.isNull() && !o.generator.isNull() && *generator == *o.generator); - return sameGenerators && layer == o.layer && mipLevel == o.mipLevel && face == o.face; - } - inline bool operator!=(const Image &o) const { return !(*this == o); } - }; - - inline TextureProperties properties() const { return m_properties; } - inline TextureParameters parameters() const { return m_parameters; } - inline QTextureGeneratorPtr textureGenerator() const { return m_dataFunctor; } - inline int sharedTextureId() const { return m_sharedTextureId; } - inline QVector images() const { return m_images; } - - inline QSize size() const { return QSize(m_properties.width, m_properties.height); } - inline QOpenGLTexture *getGLTexture() const { return m_gl; } - - /** - * @brief - * Returns the QOpenGLTexture for this GLTexture. If necessary, - * the GL texture will be created from the TextureImageDatas associated - * with the texture and image functors. If no functors are provided, - * the texture will be created without images. - * - * If the texture properties or parameters have changed, these changes - * will be applied to the resulting OpenGL texture. - */ - struct TextureUpdateInfo - { - QOpenGLTexture *texture = nullptr; - bool wasUpdated = false; - TextureProperties properties; - }; - - TextureUpdateInfo createOrUpdateGLTexture(); - - /** - * @brief - * Returns the RenderBuffer for this GLTexture. If this is the first - * call, the OpenGL renderbuffer object will be created. - */ - RenderBuffer *getOrCreateRenderBuffer(); - - - void destroy(); - - void cleanup(); - - bool isDirty() const - { - return m_dirtyFlags != None; - } - - bool hasTextureData() const { return !m_textureData.isNull(); } - bool hasImagesData() const { return !m_imageData.isEmpty(); } - - QFlags dirtyFlags() const { return m_dirtyFlags; } - - QMutex *externalRenderingLock() - { - return &m_externalRenderingMutex; - } - - void setExternalRenderingEnabled(bool enable) - { - m_externalRendering = enable; - } - - bool isExternalRenderingEnabled() const - { - return m_externalRendering; - } - - // Purely for unit testing purposes - bool wasTextureRecreated() const - { - return m_wasTextureRecreated; - } - - void setParameters(const TextureParameters ¶ms); - void setProperties(const TextureProperties &props); - void setImages(const QVector &images); - void setGenerator(const QTextureGeneratorPtr &generator); - void setSharedTextureId(int textureId); - void addTextureDataUpdates(const QVector &updates); - - QVector textureDataUpdates() const { return m_pendingTextureDataUpdates; } - QTextureGeneratorPtr dataGenerator() const { return m_dataFunctor; } - -private: - void requestImageUpload() - { - m_dirtyFlags |= TextureImageData; - } - - void requestUpload() - { - m_dirtyFlags |= TextureData; - } - - bool testDirtyFlag(DirtyFlag flag) - { - return m_dirtyFlags.testFlag(flag); - } - - void setDirtyFlag(DirtyFlag flag, bool value = true) - { - m_dirtyFlags.setFlag(flag, value); - } - - QOpenGLTexture *buildGLTexture(); - bool loadTextureDataFromGenerator(); - void loadTextureDataFromImages(); - void uploadGLTextureData(); - void updateGLTextureParameters(); - void introspectPropertiesFromSharedTextureId(); - void destroyResources(); - - QFlags m_dirtyFlags; - QMutex m_externalRenderingMutex; - QOpenGLTexture *m_gl; - RenderBuffer *m_renderBuffer; - - // target which is actually used for GL texture - TextureProperties m_properties; - TextureParameters m_parameters; - - QTextureGeneratorPtr m_dataFunctor; - QTextureGenerator *m_pendingDataFunctor; - QVector m_images; - - // cache actual image data generated by the functors - QTextureDataPtr m_textureData; - QVector m_imageData; - QVector m_pendingTextureDataUpdates; - - int m_sharedTextureId; - bool m_externalRendering; - bool m_wasTextureRecreated; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_GLTEXTURE_H diff --git a/src/render/renderers/opengl/textures/renderbuffer.cpp b/src/render/renderers/opengl/textures/renderbuffer.cpp deleted file mode 100644 index bc5050f73..000000000 --- a/src/render/renderers/opengl/textures/renderbuffer.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "renderbuffer_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { -namespace Render { - -RenderBuffer::RenderBuffer(int width, int height, QAbstractTexture::TextureFormat format) - : m_size(width, height), - m_format(format), - m_renderBuffer(0), - m_context(nullptr) -{ - QOpenGLContext *ctx = QOpenGLContext::currentContext(); - if (!ctx) { - qWarning("Renderbuffer requires an OpenGL context"); - return; - } - - m_context = ctx; - QOpenGLFunctions *f = ctx->functions(); - f->glGenRenderbuffers(1, &m_renderBuffer); - if (!m_renderBuffer) - return; - - f->glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer); - while (f->glGetError() != GL_NO_ERROR) { } - f->glRenderbufferStorage(GL_RENDERBUFFER, format, width, height); - GLint err = f->glGetError(); - if (err != GL_NO_ERROR) - qWarning("Failed to set renderbuffer storage: error 0x%x", err); - f->glBindRenderbuffer(GL_RENDERBUFFER, 0); -} - -RenderBuffer::~RenderBuffer() -{ - if (m_renderBuffer) { - QOpenGLContext *ctx = QOpenGLContext::currentContext(); - - // Ignore the fact that renderbuffers are sharable resources and let's - // just expect that the context is the same as when the resource was - // created. QOpenGLTexture suffers from the same limitation anyway, and - // this is unlikely to become an issue within Qt 3D. - if (ctx == m_context) { - ctx->functions()->glDeleteRenderbuffers(1, &m_renderBuffer); - } else { - qWarning("Wrong current context; renderbuffer not destroyed"); - } - } -} - -void RenderBuffer::bind() -{ - if (!m_renderBuffer) - return; - - m_context->functions()->glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer); -} - -void RenderBuffer::release() -{ - if (!m_context) - return; - - m_context->functions()->glBindRenderbuffer(GL_RENDERBUFFER, 0); -} - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE diff --git a/src/render/renderers/opengl/textures/renderbuffer_p.h b/src/render/renderers/opengl/textures/renderbuffer_p.h deleted file mode 100644 index 7dc62492a..000000000 --- a/src/render/renderers/opengl/textures/renderbuffer_p.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 3 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL3 included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 3 requirements -** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 2.0 or (at your option) the GNU General -** Public license version 3 or any later version approved by the KDE Free -** Qt Foundation. The licenses are as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-2.0.html and -** https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_RENDERBUFFER_P_H -#define QT3DRENDER_RENDER_RENDERBUFFER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -class QOpenGLContext; - -namespace Qt3DRender { -namespace Render { - -class Q_AUTOTEST_EXPORT RenderBuffer -{ -public: - RenderBuffer(int width, int height, QAbstractTexture::TextureFormat format); - ~RenderBuffer(); - - int width() const { return m_size.width(); } - int height() const { return m_size.height(); } - QSize size() const { return m_size; } - QAbstractTexture::TextureFormat format() const { return m_format; } - GLuint renderBufferId() const { return m_renderBuffer; } - - void bind(); - void release(); - -private: - QSize m_size; - QAbstractTexture::TextureFormat m_format; - GLuint m_renderBuffer; - QOpenGLContext *m_context; -}; - -} // namespace Render -} // namespace Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_RENDERBUFFER_P_H diff --git a/src/render/renderers/opengl/textures/textures.pri b/src/render/renderers/opengl/textures/textures.pri deleted file mode 100644 index e17abfbb3..000000000 --- a/src/render/renderers/opengl/textures/textures.pri +++ /dev/null @@ -1,9 +0,0 @@ -INCLUDEPATH += $$PWD - -SOURCES += \ - $$PWD/gltexture.cpp \ - $$PWD/renderbuffer.cpp - -HEADERS += \ - $$PWD/gltexture_p.h \ - $$PWD/renderbuffer_p.h diff --git a/src/render/renderers/renderers.pri b/src/render/renderers/renderers.pri deleted file mode 100644 index 795a6fbdf..000000000 --- a/src/render/renderers/renderers.pri +++ /dev/null @@ -1,7 +0,0 @@ -TEMPLATE = subdirs - -# OpenGL renderer -include($$OUT_PWD/qt3drender-config.pri) -QT_FOR_CONFIG += 3drender-private - -qtConfig(qt3d-opengl-renderer): include(opengl/opengl.pri) diff --git a/src/render/renderstates/genericstate_p.h b/src/render/renderstates/genericstate_p.h index e3ece36f5..1d363e4fe 100644 --- a/src/render/renderstates/genericstate_p.h +++ b/src/render/renderstates/genericstate_p.h @@ -56,6 +56,7 @@ #include #include #include +#include //#include #include #include @@ -73,7 +74,7 @@ class GraphicsContext; typedef quint64 StateMaskSet; -class RenderStateImpl +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderStateImpl { public: virtual ~RenderStateImpl() {} diff --git a/src/render/renderstates/renderstatenode_p.h b/src/render/renderstates/renderstatenode_p.h index e0258112f..604046e00 100644 --- a/src/render/renderstates/renderstatenode_p.h +++ b/src/render/renderstates/renderstatenode_p.h @@ -57,7 +57,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT RenderStateNode : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderStateNode : public BackendNode { public: RenderStateNode(); @@ -67,7 +67,6 @@ public: StateMask type() const { return m_impl.type; } StateVariant impl() const { return m_impl; } -protected: void cleanup(); private: diff --git a/src/render/renderstates/renderstates.cpp b/src/render/renderstates/renderstates.cpp index 5e238c010..1ab4e0092 100644 --- a/src/render/renderstates/renderstates.cpp +++ b/src/render/renderstates/renderstates.cpp @@ -44,7 +44,6 @@ #include #include -#include #include #include #include diff --git a/src/render/renderstates/renderstates.pri b/src/render/renderstates/renderstates.pri index 06ba53a41..867a8c299 100644 --- a/src/render/renderstates/renderstates.pri +++ b/src/render/renderstates/renderstates.pri @@ -51,7 +51,8 @@ HEADERS += \ $$PWD/statemask_p.h \ $$PWD/statevariant_p.h \ $$PWD/qrastermode.h \ - $$PWD/qrastermode_p.h + $$PWD/qrastermode_p.h \ + $$PWD/renderstateset_p.h SOURCES += \ $$PWD/qalphacoverage.cpp \ @@ -82,4 +83,5 @@ SOURCES += \ $$PWD/renderstatenode.cpp \ $$PWD/statevariant.cpp \ $$PWD/qmultisampleantialiasing.cpp \ - $$PWD/qrastermode.cpp + $$PWD/qrastermode.cpp \ + $$PWD/renderstateset.cpp diff --git a/src/render/renderstates/renderstates_p.h b/src/render/renderstates/renderstates_p.h index 6c8e9d551..8c4c065ee 100644 --- a/src/render/renderstates/renderstates_p.h +++ b/src/render/renderstates/renderstates_p.h @@ -59,128 +59,128 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { -class Q_AUTOTEST_EXPORT BlendEquationArguments : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT BlendEquationArguments : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT BlendEquation : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT BlendEquation : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT AlphaFunc : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT AlphaFunc : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT MSAAEnabled : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT MSAAEnabled : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT DepthRange : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT DepthRange : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT DepthTest : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT DepthTest : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT RasterMode : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT RasterMode : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT NoDepthMask : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT NoDepthMask : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT CullFace : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT CullFace : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT FrontFace : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT FrontFace : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT Dithering : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT Dithering : public GenericState { }; -class Q_AUTOTEST_EXPORT ScissorTest : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT ScissorTest : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT StencilTest : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT StencilTest : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT AlphaCoverage : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT AlphaCoverage : public GenericState { }; -class Q_AUTOTEST_EXPORT PointSize : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT PointSize : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT PolygonOffset : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT PolygonOffset : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT ColorMask : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT ColorMask : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT ClipPlane : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT ClipPlane : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT SeamlessCubemap : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT SeamlessCubemap : public GenericState { }; -class Q_AUTOTEST_EXPORT StencilOp : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT StencilOp : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT StencilMask : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT StencilMask : public GenericState { public: void updateProperties(const QRenderState *node) override; }; -class Q_AUTOTEST_EXPORT LineWidth : public GenericState +class Q_3DRENDERSHARED_PRIVATE_EXPORT LineWidth : public GenericState { public: void updateProperties(const QRenderState *node) override; diff --git a/src/render/renderstates/renderstateset.cpp b/src/render/renderstates/renderstateset.cpp new file mode 100644 index 000000000..6b66d2dd7 --- /dev/null +++ b/src/render/renderstates/renderstateset.cpp @@ -0,0 +1,150 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "renderstateset_p.h" + +#include + +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +RenderStateSet::RenderStateSet() + : m_stateMask(0) +{ +} + +RenderStateSet::~RenderStateSet() +{ +} + +template<> +void RenderStateSet::addState(const StateVariant &ds) +{ + m_states.push_back(ds); + m_stateMask |= ds.type; +} + +int RenderStateSet::changeCost(RenderStateSet *previousState) +{ + if (previousState == this) + return 0; + + int cost = 0; + + // first, find cost of any resets + StateMaskSet invOurState = ~stateMask(); + StateMaskSet stateToReset = previousState->stateMask() & invOurState; + + std::bitset<64> bs(stateToReset); + cost += int(bs.count()); + + // now, find out how many states we're changing + for (const StateVariant &ds : qAsConst(m_states)) { + // if the other state contains matching, then doesn't + // contribute to cost at all + if (previousState->contains(ds)) + continue; + + // flat cost for now; could be replaced with a cost() method on + // RenderState + cost += 2; + } + + return cost; +} + +StateMaskSet RenderStateSet::stateMask() const +{ + return m_stateMask; +} + +// This modifies our state to add states from others +// if we don't already contain a state with that type set +void RenderStateSet::merge(RenderStateSet *other) +{ + m_stateMask |= other->stateMask(); + const QVector otherStates = other->states(); + + // We only add states which are new (different type) + for (const StateVariant &otherState : otherStates) { + const bool canAdd = canAddStateOfType(otherState.type); + if (canAdd) + m_states.push_back(otherState); + } +} + +bool RenderStateSet::canAddStateOfType(StateMask type) const +{ + return !hasStateOfType(type) || allowMultipleStatesOfType(type); +} + +bool RenderStateSet::hasStateOfType(StateMask type) const +{ + return (type & stateMask()); +} + +bool RenderStateSet::allowMultipleStatesOfType(StateMask type) const +{ + return (type == BlendEquationArgumentsMask) || + (type == ClipPlaneMask); +} + +bool RenderStateSet::contains(const StateVariant &ds) const +{ + // trivial reject using the state mask bits + if (!(ds.type & stateMask())) + return false; + + for (const StateVariant &rs : m_states) { + if (rs == ds) + return true; + } + return false; +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/src/render/renderstates/renderstateset_p.h b/src/render/renderstates/renderstateset_p.h new file mode 100644 index 000000000..119f1edca --- /dev/null +++ b/src/render/renderstates/renderstateset_p.h @@ -0,0 +1,122 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_RENDERSTATE_H +#define QT3DRENDER_RENDER_RENDERSTATE_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class QRenderState; + +namespace Render { + +class RenderState; + +class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderStateSet +{ +public: + RenderStateSet(); + ~RenderStateSet(); + + template + void addState(const GenericState &state) + { + addState(StateVariant::fromValue(state)); + } + + /** + * @brief changeCost - metric of cost to change to this state-set from + * a candidate previous state-set. This is used to find an optimal + * ordering of state-sets when sending draw commands. + * @param previousState + * @return + */ + int changeCost(RenderStateSet* previousState); + + StateMaskSet stateMask() const; + void merge(RenderStateSet *other); + + QVector states() const { return m_states; } + + bool canAddStateOfType(StateMask type) const; + + /** + * @brief contains - check if this set contains a matching piece of state + * @param ds + * @return + */ + bool contains(const StateVariant &ds) const; + +private: + bool hasStateOfType(StateMask type) const; + bool allowMultipleStatesOfType(StateMask type) const; + +private: + StateMaskSet m_stateMask; + QVector m_states; +}; + +template<> +Q_3DRENDERSHARED_PRIVATE_EXPORT void RenderStateSet::addState(const StateVariant &state); + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_RENDERSTATE_H diff --git a/src/render/renderstates/statevariant_p.h b/src/render/renderstates/statevariant_p.h index ef6c80744..1926bb937 100644 --- a/src/render/renderstates/statevariant_p.h +++ b/src/render/renderstates/statevariant_p.h @@ -58,7 +58,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { -struct Q_AUTOTEST_EXPORT StateVariant +struct Q_3DRENDERSHARED_PRIVATE_EXPORT StateVariant { StateMask type; diff --git a/src/render/services/vsyncframeadvanceservice_p.h b/src/render/services/vsyncframeadvanceservice_p.h index c57c81a79..81d601e3e 100644 --- a/src/render/services/vsyncframeadvanceservice_p.h +++ b/src/render/services/vsyncframeadvanceservice_p.h @@ -52,6 +52,7 @@ // #include +#include QT_BEGIN_NAMESPACE @@ -61,7 +62,7 @@ namespace Render { class VSyncFrameAdvanceServicePrivate; -class Q_AUTOTEST_EXPORT VSyncFrameAdvanceService final : public Qt3DCore::QAbstractFrameAdvanceService +class Q_3DRENDERSHARED_PRIVATE_EXPORT VSyncFrameAdvanceService final : public Qt3DCore::QAbstractFrameAdvanceService { public: explicit VSyncFrameAdvanceService(bool drivenByRenderThread); diff --git a/src/render/texture/qtexture.cpp b/src/render/texture/qtexture.cpp index 7f662dfc5..6b7b92166 100644 --- a/src/render/texture/qtexture.cpp +++ b/src/render/texture/qtexture.cpp @@ -57,7 +57,7 @@ #include #include #include -#include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/texture/qtextureimagedata_p.h b/src/render/texture/qtextureimagedata_p.h index d9a0952de..14095e2eb 100644 --- a/src/render/texture/qtextureimagedata_p.h +++ b/src/render/texture/qtextureimagedata_p.h @@ -52,12 +52,13 @@ // #include "qtextureimagedata.h" +#include QT_BEGIN_NAMESPACE namespace Qt3DRender { -class QTextureImageDataPrivate +class Q_3DRENDERSHARED_PRIVATE_EXPORT QTextureImageDataPrivate { public: QTextureImageDataPrivate(); diff --git a/src/render/texture/texture.cpp b/src/render/texture/texture.cpp index 795c5844e..dab037568 100644 --- a/src/render/texture/texture.cpp +++ b/src/render/texture/texture.cpp @@ -47,7 +47,7 @@ #include #include -#include +#include #include QT_BEGIN_NAMESPACE diff --git a/src/render/texture/texture_p.h b/src/render/texture/texture_p.h index 83a05ebcc..61011bb68 100644 --- a/src/render/texture/texture_p.h +++ b/src/render/texture/texture_p.h @@ -128,7 +128,7 @@ struct TextureParameters * Will query the TextureImplManager for an instance of TextureImpl that matches it's * properties. */ -class Q_AUTOTEST_EXPORT Texture : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT Texture : public BackendNode { public: Texture(); diff --git a/src/render/texture/texturedatamanager_p.h b/src/render/texture/texturedatamanager_p.h new file mode 100644 index 000000000..61ebd1125 --- /dev/null +++ b/src/render/texture/texturedatamanager_p.h @@ -0,0 +1,227 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_TEXTUREDATAMANAGER_H +#define QT3DRENDER_RENDER_TEXTUREDATAMANAGER_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +/** + * The texture data managers associates each texture data generator + * with the data objects generated by them. That is, either + * + * QTextureImageDataGenerator -> QTextureImageData, or + * QTextureGenerator -> QTextureData + * + * This way, texture classes only need to refer to the texture functors used. + * Aspect jobs will make sure that at the start of each frame, all generators + * registered with the GeneratorDataManagers have been executed. + * + * This guarantees that no texture data generator is executed twice. + * + * Each Generator is associated with a number of textures that reference it. + * If the last texture disassociates from a generator, the QTextureData will + * be deleted. + */ +template +class GeneratorDataManager +{ +public: + GeneratorDataManager() {} + + /*! + * If no data for the given generator exists, make sure that the + * generators are executed the next frame. Reference generator by + * given texture + * + * Returns true if the Entry for a given generator had to be created + */ + bool requestData(const GeneratorPtr &generator, ReferencedType r) + { + QMutexLocker lock(&m_mutex); + + Entry *entry = findEntry(generator); + const bool needsToBeCreated = (entry == nullptr); + if (needsToBeCreated) + entry = createEntry(generator); + Q_ASSERT(entry); + if (!entry->referencingObjects.contains(r)) + entry->referencingObjects.push_back(r); + return needsToBeCreated; + } + + /*! + * Dereference given generator from texture. If no other textures still reference + * the generator, the associated data will be deleted + */ + void releaseData(const GeneratorPtr &generator, ReferencedType r) + { + QMutexLocker lock(&m_mutex); + + const auto end = m_data.end(); + for (auto it = m_data.begin(); it != end; ++it) { + Entry &entry = *it; + if (*entry.generator == *generator) { + entry.referencingObjects.removeAll(r); + // delete, if that was the last reference + if (entry.referencingObjects.empty()) { + m_data.erase(it); + return; + } + } + } + } + + /*! + * Return data associated with given generator, if existent + */ + DataPtr getData(const GeneratorPtr &generator) + { + QMutexLocker lock(&m_mutex); + + const Entry *entry = findEntry(generator); + return entry ? entry->data : DataPtr(); + } + + /*! + * Returns all generators that were not yet executed + */ + QVector pendingGenerators() + { + QMutexLocker lock(&m_mutex); + + QVector ret; + for (const Entry &entry : m_data) + if (!entry.data && !ret.contains(entry.generator)) + ret.push_back(entry.generator); + return ret; + } + + /*! + * Assigns a piece of data to the generator that was used to + * create it. + */ + void assignData(const GeneratorPtr &generator, const DataPtr &data) + { + QMutexLocker lock(&m_mutex); + + Entry *entry = findEntry(generator); + if (!entry) { + qWarning() << "[TextureDataManager] assignData() called with non-existent generator"; + return; + } + entry->data = data; + } + + bool contains(const GeneratorPtr &generator) + { + return findEntry(generator) != nullptr; + } + +private: + + struct Entry { + GeneratorPtr generator; + QVector referencingObjects; + DataPtr data; + }; + + /*! + * Helper function: return entry for given generator if it exists, nullptr + * otherwise. + */ + Entry* findEntry(const GeneratorPtr &generator) + { + for (int i = 0, sz = m_data.size(); i < sz; ++i) + if (*m_data[i].generator == *generator) + return &m_data[i]; + return nullptr; + } + + Entry *createEntry(const GeneratorPtr &generator) + { + Entry newEntry; + newEntry.generator = generator; + + m_data.push_back(newEntry); + return &m_data.back(); + } + + QMutex m_mutex; + QVector m_data; +}; + +class QT3DRENDERSHARED_PRIVATE_EXPORT TextureDataManager + : public GeneratorDataManager +{ +}; + +class QT3DRENDERSHARED_PRIVATE_EXPORT TextureImageDataManager + : public GeneratorDataManager +{ +}; + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE + +#endif // TEXTUREDATAMANAGER_H diff --git a/src/render/texture/textureimage_p.h b/src/render/texture/textureimage_p.h index ced8f1ad2..42ef242a7 100644 --- a/src/render/texture/textureimage_p.h +++ b/src/render/texture/textureimage_p.h @@ -70,7 +70,7 @@ class TextureImageDataManager; * Backend class for QAbstractTextureImage. * Will only hold the generator and some info values. */ -class Q_AUTOTEST_EXPORT TextureImage : public BackendNode +class Q_3DRENDERSHARED_PRIVATE_EXPORT TextureImage : public BackendNode { public: TextureImage(); diff --git a/src/src.pro b/src/src.pro index 0a3ed8cb7..047e67bf2 100644 --- a/src/src.pro +++ b/src/src.pro @@ -100,6 +100,11 @@ src_plugins_geometryloaders.file = $$PWD/plugins/geometryloaders/geometryloaders src_plugins_geometryloaders.target = sub-plugins-geometryloaders src_plugins_geometryloaders.depends = src_render src_extras +# Qt3D Renderer plugins +src_plugins_renderers.file = $$PWD/plugins/renderers/renderers.pro +src_plugins_renderers.target = sub-plugins-renderers +src_plugins_renderers.depends = src_render + qtHaveModule(quick) { # Qt3D Render plugins src_plugins_render.file = $$PWD/plugins/renderplugins/renderplugins.pro @@ -114,7 +119,11 @@ include($$OUT_PWD/core/qt3dcore-config.pri) qtConfig(qt3d-input): SUBDIRS += src_input qtConfig(qt3d-logic): SUBDIRS += src_logic -qtConfig(qt3d-render): SUBDIRS += src_render +qtConfig(qt3d-render) { + SUBDIRS += \ + src_render \ + src_plugins_renderers +} qtConfig(qt3d-animation) { SUBDIRS += src_animation qtConfig(qt3d-input): SUBDIRS += src_doc diff --git a/tests/auto/render/computecommand/tst_computecommand.cpp b/tests/auto/render/computecommand/tst_computecommand.cpp index 4dc6b4436..d6fa1d579 100644 --- a/tests/auto/render/computecommand/tst_computecommand.cpp +++ b/tests/auto/render/computecommand/tst_computecommand.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -43,20 +42,6 @@ #include "testpostmanarbiter.h" -// tst_Renderer is a friend class of Renderer -class tst_Renderer : public Qt3DRender::Render::Renderer -{ -public: - tst_Renderer() - : Qt3DRender::Render::Renderer(Qt3DRender::QRenderAspect::Synchronous) - {} - - ~tst_Renderer() { - shutdown(); - } -}; - - class tst_ComputeCommand : public Qt3DCore::QBackendNodeTester { Q_OBJECT @@ -271,80 +256,6 @@ private Q_SLOTS: QCOMPARE(backendComputeCommand.hasReachedFrameCount(), false); QCOMPARE(backendComputeCommand.frameCount(), 1); } - - void checkDisablesFrontend() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManager; - tst_Renderer renderer; - TestArbiter arbiter; - - Qt3DCore::QAspectManager manager; - Qt3DCore::QScene scene; - - Qt3DCore::QEntity rootEntity; - Qt3DCore::QNodePrivate::get(&rootEntity)->setScene(&scene); - - Qt3DRender::QComputeCommand computeCommand; - Qt3DRender::Render::ComputeCommand *backendComputeCommand = nullptr; - - renderer.setNodeManagers(&nodeManager); - - // WHEN - computeCommand.setParent(&rootEntity); - // RootEntity is the entry point to retrieve the scene instance for lookups - manager.setRootEntity(&rootEntity, {}); - - // THEN - QVERIFY(scene.lookupNode(computeCommand.id()) != nullptr); - - // WHEN - auto handle = nodeManager.computeJobManager()->getOrAcquireHandle(computeCommand.id()); - backendComputeCommand = nodeManager.computeJobManager()->data(handle); - - // WHEN - computeCommand.setWorkGroupX(256); - computeCommand.setWorkGroupY(512); - computeCommand.setWorkGroupZ(128); - computeCommand.setRunType(Qt3DRender::QComputeCommand::Manual); - computeCommand.trigger(1); - - Qt3DCore::QBackendNodePrivate::get(backendComputeCommand)->setArbiter(&arbiter); - backendComputeCommand->setRenderer(&renderer); - simulateInitializationSync(&computeCommand, backendComputeCommand); - - // THEN - QCOMPARE(backendComputeCommand->frameCount(),1); - QCOMPARE(backendComputeCommand->isEnabled(), true); - QCOMPARE(computeCommand.isEnabled(), true); - QCOMPARE(backendComputeCommand->hasReachedFrameCount(), false); - - // WHEN - backendComputeCommand->updateFrameCount(); - - // THEN - QCOMPARE(backendComputeCommand->frameCount(), 0); - QCOMPARE(backendComputeCommand->hasReachedFrameCount(), true); - - - // Still enabled as we have yet to notify the fronted - QCOMPARE(backendComputeCommand->isEnabled(), true); - QCOMPARE(computeCommand.isEnabled(), true); - - // WHEN - renderer.jobsDone(&manager); // so Renderer::sendDisablesToFrontend gets called - - // THEN - QCOMPARE(computeCommand.isEnabled(), false); - QCOMPARE(backendComputeCommand->hasReachedFrameCount(), false); - - // WHEN - backendComputeCommand->syncFromFrontEnd(&computeCommand, false); - - // THEN - QCOMPARE(backendComputeCommand->frameCount(), 0); - QCOMPARE(backendComputeCommand->isEnabled(), false); - } }; QTEST_MAIN(tst_ComputeCommand) diff --git a/tests/auto/render/effect/tst_effect.cpp b/tests/auto/render/effect/tst_effect.cpp index 369cdf793..2b145669e 100644 --- a/tests/auto/render/effect/tst_effect.cpp +++ b/tests/auto/render/effect/tst_effect.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include "qbackendnodetester.h" #include "testrenderer.h" diff --git a/tests/auto/render/filtercompatibletechniquejob/BLACKLIST b/tests/auto/render/filtercompatibletechniquejob/BLACKLIST deleted file mode 100644 index 7cbc7c4c0..000000000 --- a/tests/auto/render/filtercompatibletechniquejob/BLACKLIST +++ /dev/null @@ -1,6 +0,0 @@ -#[checkRunRendererRunning] -windows-7 -windows-7sp1 -#QTBUG-64271 -# Offscreen platform does not support OpenGL context creation -b2qt diff --git a/tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro b/tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro deleted file mode 100644 index 4f63e514b..000000000 --- a/tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app - -TARGET = tst_filtercompatibletechniquejob - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_filtercompatibletechniquejob.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp b/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp deleted file mode 100644 index 618709269..000000000 --- a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -class TestAspect : public Qt3DRender::QRenderAspect -{ -public: - TestAspect(Qt3DCore::QNode *root) - : Qt3DRender::QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) - , m_jobManager(new Qt3DCore::QAspectJobManager()) - , m_window(new QWindow()) - , m_contextCreationSuccessful(false) - { - m_window->setSurfaceType(QWindow::OpenGLSurface); - m_window->setGeometry(0, 0, 10, 10); - m_window->create(); - - if (!m_glContext.create()) { - qWarning() << "Failed to create OpenGL context"; - return; - } - - if (!m_glContext.makeCurrent(m_window.data())) { - qWarning() << "Failed to make OpenGL context current"; - return; - } - - m_contextCreationSuccessful = true; - - Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); - QRenderAspect::onRegistered(); - - QVector nodes; - Qt3DCore::QNodeVisitor v; - v.traverse(root, [&nodes](Qt3DCore::QNode *node) { - Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(node); - d->m_typeInfo = const_cast(Qt3DCore::QNodePrivate::findStaticMetaObject(node->metaObject())); - d->m_hasBackendNode = true; - nodes << node; - }); - - for (const auto node: nodes) - d_func()->createBackendNode({ - node->id(), - Qt3DCore::QNodePrivate::get(node)->m_typeInfo, - Qt3DCore::NodeTreeChange::Added, - node - }); - } - - ~TestAspect() - { - if (m_contextCreationSuccessful) - QRenderAspect::onUnregistered(); - } - - Qt3DRender::Render::NodeManagers *nodeManagers() const - { - return d_func()->m_renderer - ? d_func()->m_renderer->nodeManagers() : nullptr; - } - - bool contextCreationSuccessful() const - { - return m_contextCreationSuccessful; - } - - void initializeRenderer() - { - renderer()->setOpenGLContext(&m_glContext); - d_func()->m_renderer->initialize(); - renderer()->submissionContext()->beginDrawing(m_window.data()); - } - - Render::Renderer *renderer() const - { - return static_cast(d_func()->m_renderer); - } - - void onRegistered() { QRenderAspect::onRegistered(); } - void onUnregistered() { QRenderAspect::onUnregistered(); } - -private: - QScopedPointer m_jobManager; - QScopedPointer m_window; - QOpenGLContext m_glContext; - bool m_contextCreationSuccessful; -}; - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -namespace { - -Qt3DCore::QEntity *buildTestScene() -{ - Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); - - // FrameGraph - Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); - renderSettings->setActiveFrameGraph(new Qt3DRender::QViewport()); - root->addComponent(renderSettings); - - // Scene - Qt3DRender::QTechnique *gl2Technique = new Qt3DRender::QTechnique(root); - gl2Technique->graphicsApiFilter()->setApi(Qt3DRender::QGraphicsApiFilter::OpenGL); - gl2Technique->graphicsApiFilter()->setMajorVersion(2); - gl2Technique->graphicsApiFilter()->setMinorVersion(0); - gl2Technique->graphicsApiFilter()->setProfile(Qt3DRender::QGraphicsApiFilter::NoProfile); - - Qt3DRender::QTechnique *gl3Technique = new Qt3DRender::QTechnique(root); - gl3Technique->graphicsApiFilter()->setApi(Qt3DRender::QGraphicsApiFilter::OpenGL); - gl3Technique->graphicsApiFilter()->setMajorVersion(3); - gl3Technique->graphicsApiFilter()->setMinorVersion(2); - gl3Technique->graphicsApiFilter()->setProfile(Qt3DRender::QGraphicsApiFilter::CoreProfile); - - Qt3DRender::QTechnique *es2Technique = new Qt3DRender::QTechnique(root); - es2Technique->graphicsApiFilter()->setApi(Qt3DRender::QGraphicsApiFilter::OpenGLES); - es2Technique->graphicsApiFilter()->setMajorVersion(2); - es2Technique->graphicsApiFilter()->setMinorVersion(0); - es2Technique->graphicsApiFilter()->setProfile(Qt3DRender::QGraphicsApiFilter::NoProfile); - - return root; -} - -} // anonymous - -class tst_FilterCompatibleTechniqueJob : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - - void initTestCase() - { - QSurfaceFormat format; -#ifdef QT_OPENGL_ES_2 - format.setRenderableType(QSurfaceFormat::OpenGLES); -#else - if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) { - format.setVersion(4, 3); - format.setProfile(QSurfaceFormat::CoreProfile); - } -#endif - format.setDepthBufferSize(24); - format.setSamples(4); - format.setStencilBufferSize(8); - QSurfaceFormat::setDefaultFormat(format); - } - - void checkInitialState() - { - // GIVEN - Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; - - // THEN - QVERIFY(backendFilterCompatibleTechniqueJob.manager() == nullptr); - QVERIFY(backendFilterCompatibleTechniqueJob.renderer() == nullptr); - - // WHEN - Qt3DRender::Render::TechniqueManager techniqueManager; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - backendFilterCompatibleTechniqueJob.setManager(&techniqueManager); - backendFilterCompatibleTechniqueJob.setRenderer(&renderer); - - // THEN - QCOMPARE(backendFilterCompatibleTechniqueJob.manager(), &techniqueManager); - QCOMPARE(backendFilterCompatibleTechniqueJob.renderer(), &renderer); - - renderer.shutdown(); - } - - void checkRunRendererRunning() - { - // GIVEN - Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; - Qt3DRender::TestAspect testAspect(buildTestScene()); - - const bool unableToCreateContext = !testAspect.contextCreationSuccessful(); - - if (unableToCreateContext) - QSKIP("Initialization failed, unable to create GL context"); - - // WHEN - Qt3DRender::Render::NodeManagers *nodeManagers = testAspect.nodeManagers(); - QVERIFY(nodeManagers); - Qt3DRender::Render::TechniqueManager *techniqueManager = nodeManagers->techniqueManager(); - QVERIFY(techniqueManager); - backendFilterCompatibleTechniqueJob.setManager(techniqueManager); - backendFilterCompatibleTechniqueJob.setRenderer(testAspect.renderer()); - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.renderer()->isRunning(), true); - QCOMPARE(testAspect.renderer()->submissionContext()->isInitialized(), true); - const QVector handles = testAspect.nodeManagers()->techniqueManager()->activeHandles(); - QCOMPARE(handles.size(), 3); - - // WHEN - backendFilterCompatibleTechniqueJob.run(); - - // THEN -> empty if job ran properly - const QVector dirtyTechniquesId = testAspect.nodeManagers()->techniqueManager()->takeDirtyTechniques(); - QCOMPARE(dirtyTechniquesId.size(), 0); - - // Check at least one technique is valid - bool foundValid = false; - for (const auto handle: handles) { - Qt3DRender::Render::Technique *technique = testAspect.nodeManagers()->techniqueManager()->data(handle); - foundValid |= technique->isCompatibleWithRenderer(); - } - QCOMPARE(foundValid, true); - } -}; - -QTEST_MAIN(tst_FilterCompatibleTechniqueJob) - -#include "tst_filtercompatibletechniquejob.moc" diff --git a/tests/auto/render/glshadermanager/glshadermanager.pro b/tests/auto/render/glshadermanager/glshadermanager.pro deleted file mode 100644 index 27aadf84f..000000000 --- a/tests/auto/render/glshadermanager/glshadermanager.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app - -TARGET = tst_glshadermanager - -QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_glshadermanager.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/glshadermanager/tst_glshadermanager.cpp b/tests/auto/render/glshadermanager/tst_glshadermanager.cpp deleted file mode 100644 index c18fb4793..000000000 --- a/tests/auto/render/glshadermanager/tst_glshadermanager.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include "qbackendnodetester.h" -#include "testrenderer.h" - -class tst_GLShaderManager : public Qt3DCore::QBackendNodeTester -{ - Q_OBJECT - -private Q_SLOTS: - void adopt(); - void lookupResource(); - void abandon(); - void insertAfterRemoval(); -}; - -void tst_GLShaderManager::adopt() -{ - // GIVEN - Qt3DRender::Render::GLShaderManager cache; - Qt3DRender::QShaderProgram frontendShader1; - Qt3DRender::QShaderProgram frontendShader2; - TestRenderer renderer; - Qt3DRender::Render::Shader backendShaderNode1; - Qt3DRender::Render::Shader backendShaderNode2; - - backendShaderNode1.setRenderer(&renderer); - backendShaderNode2.setRenderer(&renderer); - simulateInitialization(&frontendShader1, &backendShaderNode1); - simulateInitialization(&frontendShader2, &backendShaderNode2); - - // THEN - QVERIFY(cache.lookupResource(backendShaderNode1.peerId()) == nullptr); - QVERIFY(cache.lookupResource(backendShaderNode2.peerId()) == nullptr); - QVERIFY(backendShaderNode1.peerId() != backendShaderNode2.peerId()); - - // WHEN - Qt3DRender::Render::GLShader *glShader1 = cache.createOrAdoptExisting(&backendShaderNode1); - - // THEN - QVERIFY(glShader1 != nullptr); - QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); - QCOMPARE(shaderNodeIds.size(), 1); - QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); - - // WHEN - Qt3DRender::Render::GLShader *glShader2 = cache.createOrAdoptExisting(&backendShaderNode2); - - // THEN - QCOMPARE(glShader1, glShader2); - - shaderNodeIds = cache.shaderIdsForProgram(glShader2); - QCOMPARE(shaderNodeIds.size(), 2); - QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); - QCOMPARE(shaderNodeIds.last(), backendShaderNode2.peerId()); -} - -void tst_GLShaderManager::lookupResource() -{ - // GIVEN - Qt3DRender::Render::GLShaderManager cache; - Qt3DRender::QShaderProgram frontendShader1; - Qt3DRender::QShaderProgram frontendShader2; - TestRenderer renderer; - Qt3DRender::Render::Shader backendShaderNode1; - Qt3DRender::Render::Shader backendShaderNode2; - - backendShaderNode1.setRenderer(&renderer); - backendShaderNode2.setRenderer(&renderer); - simulateInitialization(&frontendShader1, &backendShaderNode1); - simulateInitialization(&frontendShader2, &backendShaderNode2); - - // WHEN - cache.createOrAdoptExisting(&backendShaderNode1); - cache.createOrAdoptExisting(&backendShaderNode2); - - // THEN - Qt3DRender::Render::GLShader *glShader1 = cache.lookupResource(backendShaderNode1.peerId()); - Qt3DRender::Render::GLShader *glShader2 = cache.lookupResource(backendShaderNode2.peerId()); - QVERIFY(glShader1 != nullptr); - QCOMPARE(glShader1, glShader2); - const QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); - QCOMPARE(shaderNodeIds.size(), 2); - QVERIFY(shaderNodeIds.contains(frontendShader1.id())); - QVERIFY(shaderNodeIds.contains(frontendShader2.id())); -} - -void tst_GLShaderManager::abandon() -{ - // GIVEN - Qt3DRender::Render::GLShaderManager cache; - Qt3DRender::QShaderProgram frontendShader1; - Qt3DRender::QShaderProgram frontendShader2; - TestRenderer renderer; - Qt3DRender::Render::Shader backendShaderNode1; - Qt3DRender::Render::Shader backendShaderNode2; - - backendShaderNode1.setRenderer(&renderer); - backendShaderNode2.setRenderer(&renderer); - simulateInitialization(&frontendShader1, &backendShaderNode1); - simulateInitialization(&frontendShader2, &backendShaderNode2); - cache.createOrAdoptExisting(&backendShaderNode1); - cache.createOrAdoptExisting(&backendShaderNode2); - - // WHEN - Qt3DRender::Render::GLShader *glShader = cache.lookupResource(backendShaderNode1.peerId()); - cache.abandon(glShader, &backendShaderNode1); - - // THEN - QVector shaderNodeIds = cache.shaderIdsForProgram(glShader); - QVERIFY(cache.takeAbandonned().isEmpty()); - QCOMPARE(shaderNodeIds.size(), 1); - QCOMPARE(shaderNodeIds.first(), backendShaderNode2.peerId()); - - // WHEN - cache.abandon(glShader, &backendShaderNode2); - - // THEN - shaderNodeIds = cache.shaderIdsForProgram(glShader); - QCOMPARE(shaderNodeIds.size(), 0); - const QVector releasedShaders = cache.takeAbandonned(); - QCOMPARE(releasedShaders.size(), 1); - QCOMPARE(releasedShaders.first(), glShader); -} - -void tst_GLShaderManager::insertAfterRemoval() -{ - // GIVEN - Qt3DRender::Render::GLShaderManager cache; - Qt3DRender::QShaderProgram frontendShader; - TestRenderer renderer; - Qt3DRender::Render::Shader backendShaderNode; - - - backendShaderNode.setRenderer(&renderer); - simulateInitialization(&frontendShader, &backendShaderNode); - - // WHEN - Qt3DRender::Render::GLShader *apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); - const Qt3DRender::Render::GLShader *originalApiShader = apiShader1; - - // THEN - auto apiShader2 = cache.lookupResource(frontendShader.id()); - QVERIFY(apiShader1 != nullptr); - QVERIFY(apiShader2 != nullptr); - QVERIFY(apiShader1 == originalApiShader); - QVERIFY(apiShader1 == apiShader2); - - // WHEN - cache.abandon(apiShader1, &backendShaderNode); - - // THEN - Qt3DRender::Render::GLShader *apiShaderEmpty = cache.lookupResource(frontendShader.id()); - QVERIFY(apiShaderEmpty == nullptr); - - // WHEN - apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); - cache.purge(); - apiShader2 = cache.lookupResource(frontendShader.id()); - - // THEN - QVERIFY(apiShader1 != nullptr); - QVERIFY(apiShader2 != nullptr); - QVERIFY(apiShader1 == apiShader2); - QVERIFY(apiShader2 == originalApiShader); -} - -QTEST_APPLESS_MAIN(tst_GLShaderManager) - -#include "tst_glshadermanager.moc" diff --git a/tests/auto/render/graphicshelpergl2/graphicshelpergl2.pro b/tests/auto/render/graphicshelpergl2/graphicshelpergl2.pro deleted file mode 100644 index b27060635..000000000 --- a/tests/auto/render/graphicshelpergl2/graphicshelpergl2.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = app - -TARGET = tst_graphicshelpergl2 - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib openglextensions - -CONFIG += testcase - -SOURCES += \ - tst_graphicshelpergl2.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/graphicshelpergl2/tst_graphicshelpergl2.cpp b/tests/auto/render/graphicshelpergl2/tst_graphicshelpergl2.cpp deleted file mode 100644 index ffafc2312..000000000 --- a/tests/auto/render/graphicshelpergl2/tst_graphicshelpergl2.cpp +++ /dev/null @@ -1,1605 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef QT_OPENGL_ES_2 - -#define TEST_SHOULD_BE_PERFORMED 1 - -QT_BEGIN_NAMESPACE - -using namespace Qt3DRender; -using namespace Qt3DRender::Render; - -namespace { - -const QByteArray vertCode = QByteArrayLiteral( - "#version 120\n" \ - "attribute vec3 vertexPosition;\n" \ - "attribute vec2 vertexTexCoord;\n" \ - "varying vec2 texCoord;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vertexTexCoord;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( - "#version 120\n" \ - "uniform float multiplier;\n" \ - "uniform vec2 multiplierVec2;\n" \ - "uniform vec3 multiplierVec3;\n" \ - "uniform vec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ - " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsInt = QByteArrayLiteral( - "#version 120\n" \ - "uniform int multiplier;\n" \ - "uniform ivec2 multiplierVec2;\n" \ - "uniform ivec3 multiplierVec3;\n" \ - "uniform ivec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ - " gl_FragColor = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( - "#version 120\n" \ - "uniform mat2 m2;\n" \ - "uniform mat2x3 m23;\n" \ - "uniform mat3x2 m32;\n" \ - "uniform mat2x4 m24;\n" \ - "uniform mat4x2 m42;\n" \ - "uniform mat3 m3;\n" \ - "uniform mat3x4 m34;\n" \ - "uniform mat4x3 m43;\n" \ - "uniform mat4 m4;\n" \ - "void main()\n" \ - "{\n" \ - " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ - " gl_FragColor = vec4(1, 0, 0, 1) * lengthSum;\n" \ - "}\n"); - - -const QByteArray fragCodeSamplers = QByteArrayLiteral( - "#version 120\n" \ - "varying vec2 texCoord;\n" \ - "uniform sampler1D s1;\n" \ - "uniform sampler2D s2;\n" \ - "uniform sampler3D s3;\n" \ - "uniform samplerCube scube;\n" \ - "void main()\n" \ - "{\n" \ - " gl_FragColor = vec4(1, 0, 0, 1) *" \ - " texture1D(s1, texCoord.x) *" \ - " texture2D(s2, texCoord) *" \ - " texture3D(s3, vec3(texCoord, 0.0)) *" \ - " textureCube(scube, vec3(texCoord, 0));\n" \ - "}\n"); - -} // anonymous - -class tst_GraphicsHelperGL2 : public QObject -{ - Q_OBJECT -private Q_SLOTS: - - void init() - { - m_window.reset(new QWindow); - m_window->setSurfaceType(QWindow::OpenGLSurface); - m_window->setGeometry(0, 0, 10, 10); - m_window->create(); - - QSurfaceFormat format; - format.setVersion(2, 0); - format.setProfile(QSurfaceFormat::NoProfile); - format.setDepthBufferSize(24); - format.setSamples(4); - format.setStencilBufferSize(8); - m_window->setFormat(format); - m_glContext.setFormat(format); - - if (!m_glContext.create()) { - qWarning() << "Failed to create OpenGL context"; - return; - } - - if (!m_glContext.makeCurrent(m_window.data())) { - qWarning() << "Failed to make OpenGL context current"; - return; - } - - if ((m_func = m_glContext.versionFunctions()) != nullptr) { - if (m_glContext.hasExtension(QByteArrayLiteral("GL_ARB_framebuffer_object"))) { - m_fboFuncs = new QOpenGLExtension_ARB_framebuffer_object(); - m_fboFuncs->initializeOpenGLFunctions(); - } - m_glHelper.initializeHelper(&m_glContext, m_func); - m_initializationSuccessful = true; - } - } - - void cleanup() - { - m_glContext.doneCurrent(); - } - - void alphaTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Deprecated - } - - void bindBufferBase() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // Not supported by GL2 - } - - void bindFragDataLocation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void bindFrameBufferAttachment() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - - // GIVEN - GLuint fboId; - m_fboFuncs->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA32F); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture.create()) - qWarning() << "Texture creation failed"; - texture.allocateStorage(); - QVERIFY(texture.isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_fboFuncs->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureAttachmentId = 0; - m_fboFuncs->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, - &textureAttachmentId); - QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); - - // Restore state - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_fboFuncs->glDeleteFramebuffers(1, &fboId); - } - - void bindFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - - // GIVEN - GLuint fboId; - m_fboFuncs->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); - - // THEN - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundindFBOId = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // Cleanup - m_fboFuncs->glDeleteFramebuffers(1, &fboId); - } - - void bindShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void bindUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void blendEquation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - GLint equation = 0; - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_ADD); - - // WHEN - m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); - - // THEN - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); - } - - void blendFunci() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void blendFuncSeparatei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void boundFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - - // GIVEN - GLuint fboId; - m_fboFuncs->glGenFramebuffers(1, &fboId); - - // WHEN - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - // THEN - GLint boundBuffer = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); - QCOMPARE(GLuint(boundBuffer), fboId); - - // THEN - QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); - - // Reset state - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_fboFuncs->glDeleteFramebuffers(1, &fboId); - } - - void checkFrameBufferComplete() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - - // GIVEN - GLuint fboId; - m_fboFuncs->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_fboFuncs->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - QVERIFY(m_glHelper.checkFrameBufferComplete()); - - // Restore - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_fboFuncs->glDeleteFramebuffers(1, &fboId); - } - - void clearBufferf() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void createFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - - // WHEN - const GLuint fboId = m_glHelper.createFrameBufferObject(); - - // THEN - QVERIFY(fboId != 0); - - // Restore - m_fboFuncs->glDeleteFramebuffers(1, &fboId); - } - - void depthMask() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - GLboolean depthWritingEnabled = false; - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - - // THEN - QVERIFY(depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_FALSE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(!depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_TRUE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(depthWritingEnabled); - } - - void depthTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - m_func->glDisable(GL_DEPTH_TEST); - m_func->glDepthFunc(GL_LESS); - - // WHEN - m_glHelper.depthTest(GL_LEQUAL); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - GLint depthMode = 0; - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LEQUAL); - - // WHEN - m_glHelper.depthTest(GL_LESS); - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LESS); - } - - void disableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - m_func->glEnable(GL_CLIP_DISTANCE0 + 5); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - - // WHEN - m_glHelper.disableClipPlane(5); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - } - - void disablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void disablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void drawBuffers() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - - // GIVEN - GLuint fboId; - m_fboFuncs->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - QOpenGLTexture *textures[4]; - - // Create 4 attachments - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - // THEN - GLenum status = m_fboFuncs->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // WHEN - GLenum bufferEnum = GL_COLOR_ATTACHMENT4; - m_func->glDrawBuffers(1, &bufferEnum); - - // THEN - GLint enumValue = -1; - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); - - // WHEN - GLint newBufferEnum = 2; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // WHEN - newBufferEnum = 0; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // Restore - m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_fboFuncs->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void enableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - m_func->glDisable(GL_CLIP_DISTANCE0 + 4); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - - // WHEN - m_glHelper.enableClipPlane(4); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - } - - void enablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void enablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void enableVertexAttribute() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); - QVERIFY(shaderProgram.link()); - shaderProgram.bind(); - - // WHEN - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void frontFace() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - m_func->glFrontFace(GL_CW); - - // THEN - GLint face = 0; - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CW); - - // WHEN - m_glHelper.frontFace(GL_CCW); - - // THEN - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CCW); - } - - void getRenderBufferDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void getTextureDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - - // WHEN - const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - } - - void pointSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // WHEN - m_glHelper.pointSize(false, 0.5f); - // THEN - GLfloat size = 0.0f; - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 0.5f); - } - - void maxClipPlaneCount() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - GLint maxCount = -1; - m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); - - // THEN - QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); - } - - void programUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // Not supported by GL2 - } - - void programAttributesAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeAttributes.size(), 2); - std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_name < b.m_name; }); - - const ShaderAttribute attribute1 = activeAttributes.at(0); - QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); - QCOMPARE(attribute1.m_size, 1); - QCOMPARE(attribute1.m_location, shaderProgram.attributeLocation("vertexPosition")); - QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); - - const ShaderAttribute attribute2 = activeAttributes.at(1); - QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); - QCOMPARE(attribute2.m_size, 1); - QCOMPARE(attribute2.m_location, shaderProgram.attributeLocation("vertexTexCoord")); - QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); - } - - void programUniformsAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniforms.size(), 4); - std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_name < b.m_name; }); - - const ShaderUniform uniform1 = activeUniforms.at(0); - QCOMPARE(uniform1.m_location, shaderProgram.uniformLocation("multiplier")); - QCOMPARE(uniform1.m_offset, -1); - QCOMPARE(uniform1.m_blockIndex, -1); - QCOMPARE(uniform1.m_arrayStride, -1); - QCOMPARE(uniform1.m_matrixStride, -1); - QCOMPARE(uniform1.m_size, 1); - QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); - QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); - - const ShaderUniform uniform2 = activeUniforms.at(1); - QCOMPARE(uniform2.m_location, shaderProgram.uniformLocation("multiplierVec2")); - QCOMPARE(uniform2.m_offset, -1); - QCOMPARE(uniform2.m_blockIndex, -1); - QCOMPARE(uniform2.m_arrayStride, -1); - QCOMPARE(uniform2.m_matrixStride, -1); - QCOMPARE(uniform2.m_size, 1); - QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); - QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); - - const ShaderUniform uniform3 = activeUniforms.at(2); - QCOMPARE(uniform3.m_location, shaderProgram.uniformLocation("multiplierVec3")); - QCOMPARE(uniform3.m_offset, -1); - QCOMPARE(uniform3.m_blockIndex, -1); - QCOMPARE(uniform3.m_arrayStride, -1); - QCOMPARE(uniform3.m_matrixStride, -1); - QCOMPARE(uniform3.m_size, 1); - QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); - QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); - - const ShaderUniform uniform4 = activeUniforms.at(3); - QCOMPARE(uniform4.m_location, shaderProgram.uniformLocation("multiplierVec4")); - QCOMPARE(uniform4.m_offset, -1); - QCOMPARE(uniform4.m_blockIndex, -1); - QCOMPARE(uniform4.m_arrayStride, -1); - QCOMPARE(uniform4.m_matrixStride, -1); - QCOMPARE(uniform4.m_size, 1); - QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); - QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); - } - - void programShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void releaseFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - if (!m_fboFuncs) - QSKIP("FBO not supported by OpenGL 2.0"); - // GIVEN - GLuint fboId; - m_fboFuncs->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.releaseFrameBufferObject(fboId); - - // THEN - QVERIFY(!m_fboFuncs->glIsFramebuffer(fboId)); - } - - void setMSAAEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - m_func->glDisable(GL_MULTISAMPLE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - } - - void setAlphaCoverageEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - } - - void setClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // Deprecated in 3.3 core - } - - void setSeamlessCubemap() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported in GL2 - } - - void setVerticesPerPatch() - { - // Not supported in GL2 - } - -#define SUPPORTS_FEATURE(Feature, IsSupported) \ - QVERIFY(m_glHelper.supportsFeature(Feature) == IsSupported); - - void supportsFeature() - { - SUPPORTS_FEATURE(GraphicsHelperInterface::MRT, (m_fboFuncs != nullptr)); - SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::BindableFragmentOutputs, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::PrimitiveRestart, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::RenderBufferDimensionRetrieval, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::TextureDimensionRetrieval, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::ShaderStorageObject, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::Compute, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::DrawBuffersBlend, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::Tessellation, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::BlitFramebuffer, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::IndirectDrawing, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::MapBuffer, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::Fences, false); - } - - -#define ADD_UNIFORM_ENTRY(FragShader, Name, Type, ComponentSize, ExpectedRawSize) \ - QTest::newRow(#FragShader"_"#Type) << FragShader << QStringLiteral(Name) << Type << ComponentSize << ExpectedRawSize; - - void uniformsByteSize_data() - { - QTest::addColumn("fragShader"); - QTest::addColumn("name"); - QTest::addColumn("type"); - QTest::addColumn("componentSize"); - QTest::addColumn("expectedByteSize"); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplier", GL_FLOAT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec2", GL_FLOAT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec3",GL_FLOAT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec4", GL_FLOAT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplier", GL_INT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec2", GL_INT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec3", GL_INT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec4", GL_INT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m2", GL_FLOAT_MAT2, 1, 4 * 2 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m23", GL_FLOAT_MAT2x3, 1, 4 * 2 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m32", GL_FLOAT_MAT3x2, 1, 4 * 3 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m24", GL_FLOAT_MAT2x4, 1, 4 * 2 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m42", GL_FLOAT_MAT4x2, 1, 4 * 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m3", GL_FLOAT_MAT3, 1, 4 * 3 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m34", GL_FLOAT_MAT3x4, 1, 4 * 3 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m43", GL_FLOAT_MAT4x3, 1, 4 * 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m4", GL_FLOAT_MAT4, 1, 4 * 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s1", GL_SAMPLER_1D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2", GL_SAMPLER_2D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s3", GL_SAMPLER_3D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "scube", GL_SAMPLER_CUBE, 1, 4); - } - - void uniformsByteSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QFETCH(QByteArray, fragShader); - QFETCH(QString, name); - QFETCH(int, type); - QFETCH(int, componentSize); - QFETCH(int, expectedByteSize); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); - QVERIFY(shaderProgram.link()); - - GLint location = shaderProgram.uniformLocation(name); - // WHEN - const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - ShaderUniform matchingUniform; - for (const ShaderUniform &u : activeUniforms) { - if (u.m_location == location) { - matchingUniform = u; - break; - } - } - - // THEN - QCOMPARE(matchingUniform.m_location, location); - QCOMPARE(matchingUniform.m_type, GLuint(type)); - QCOMPARE(matchingUniform.m_size, componentSize); - - // WHEN - const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); - - // THEN - QCOMPARE(expectedByteSize, computedRawByteSize); - - // Restore - m_func->glUseProgram(0); - } - - void useProgram() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - - // THEN - QVERIFY(shaderProgram.link()); - - GLint currentProg = 0; - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - - // WHEN - m_glHelper.useProgram(shaderProgram.programId()); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QCOMPARE(GLuint(currentProg), shaderProgram.programId()); - - // WHEN - m_glHelper.useProgram(0); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - } - - void vertexAttribDivisor() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not available in 3.2 - } - - void vertexAttributePointer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); - QVERIFY(shaderProgram.link()); - - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - - const int vertexCount = 99; - QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); - positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - positionBuffer.create(); - positionBuffer.bind(); - positionBuffer.allocate(vertexCount * sizeof(QVector3D)); - - QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); - texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - texCoordBuffer.create(); - texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); - - // WHEN - shaderProgram.bind(); - positionBuffer.bind(); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); - - texCoordBuffer.bind(); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void glUniform1fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat value = 883.0f; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1fv(location, 1, &value); - - // THEN - GLfloat setValue = 0.0f; - m_func->glGetUniformfv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[2] = { 383.0f, 427.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2fv(location, 1, values); - - // THEN - GLfloat setValues[2] = { 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3fv(location, 1, values); - - // THEN - GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4fv(location, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint value = 883; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1iv(location, 1, &value); - - // THEN - GLint setValue = 0; - m_func->glGetUniformiv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[2] = { 383, 427 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2iv(location, 1, values); - - // THEN - GLint setValues[2] = { 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[3] = { 572, 1340, 1584 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3iv(location, 1, values); - - // THEN - GLint setValues[3] = { 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[4] = { 454, 350, 883, 355 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4iv(location, 1, values); - - // THEN - GLint setValues[4] = { 0, 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniform2uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniform3uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniform4uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniformMatrix2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - const GLint location = shaderProgram.uniformLocation("m2"); - m_glHelper.glUniformMatrix2fv(location, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; - const GLint location = shaderProgram.uniformLocation("m3"); - m_glHelper.glUniformMatrix3fv(location, 1, values); - - // THEN - GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 9; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; - const GLint location = shaderProgram.uniformLocation("m4"); - m_glHelper.glUniformMatrix4fv(location, 1, values); - - // THEN - GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 16; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniformMatrix3x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniformMatrix2x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniformMatrix4x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniformMatrix3x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void glUniformMatrix4x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void blitFramebuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - -#define ADD_GL_TYPE_ENTRY(Type, Expected) \ - QTest::newRow(#Type) << Type << Expected; - - void uniformTypeFromGLType_data() - { - QTest::addColumn("glType"); - QTest::addColumn("expected"); - - ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); - ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); - ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); - ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); - ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); - } - - void uniformTypeFromGLType() - { - // GIVEN - QFETCH(int, glType); - QFETCH(UniformType, expected); - - // WHEN - UniformType computed = m_glHelper.uniformTypeFromGLType(glType); - - // THEN - QCOMPARE(computed, expected); - } - - void drawBuffer() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void readBuffer() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void fenceSync() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void clientWaitSync() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void waitSync() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void wasSyncSignaled() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void deleteSync() - { - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - // Not supported by GL2 - } - - void rasterMode() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_POLYGON_MODE, &p); - QCOMPARE(p, GL_LINE); - } - -private: - QScopedPointer m_window; - QOpenGLContext m_glContext; - GraphicsHelperGL2 m_glHelper; - QOpenGLFunctions_2_0 *m_func = nullptr; - QOpenGLExtension_ARB_framebuffer_object *m_fboFuncs = nullptr; - bool m_initializationSuccessful = false; -}; - -QT_END_NAMESPACE - -#endif - -int main(int argc, char *argv[]) -{ -#ifdef TEST_SHOULD_BE_PERFORMED - QGuiApplication app(argc, argv); - app.setAttribute(Qt::AA_Use96Dpi, true); - tst_GraphicsHelperGL2 tc; - QTEST_SET_MAIN_SOURCE_PATH - return QTest::qExec(&tc, argc, argv); -#endif - return 0; -} - -#ifdef TEST_SHOULD_BE_PERFORMED -#include "tst_graphicshelpergl2.moc" -#endif diff --git a/tests/auto/render/graphicshelpergl3_2/graphicshelpergl3_2.pro b/tests/auto/render/graphicshelpergl3_2/graphicshelpergl3_2.pro deleted file mode 100644 index 5d8bf60fd..000000000 --- a/tests/auto/render/graphicshelpergl3_2/graphicshelpergl3_2.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = app - -TARGET = tst_graphicshelpergl3_2 - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += \ - tst_graphicshelpergl3_2.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp b/tests/auto/render/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp deleted file mode 100644 index 840a7f6da..000000000 --- a/tests/auto/render/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp +++ /dev/null @@ -1,2294 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(QT_OPENGL_ES_2) && defined(QT_OPENGL_3_2) - -#define TEST_SHOULD_BE_PERFORMED 1 - -using namespace Qt3DRender; -using namespace Qt3DRender::Render; - -namespace { - -const QByteArray vertCode = QByteArrayLiteral( - "#version 150 core\n" \ - "in vec3 vertexPosition;\n" \ - "in vec2 vertexTexCoord;\n" \ - "out vec2 texCoord;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vertexTexCoord;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray vertCodeUniformBuffer = QByteArrayLiteral( - "#version 150 core\n" \ - "in vec3 vertexPosition;\n" \ - "in vec2 vertexTexCoord;\n" \ - "in int vertexColorIndex;\n" \ - "out vec2 texCoord;\n" \ - "flat out int colorIndex;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vertexTexCoord;\n" \ - " colorIndex = vertexColorIndex;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeFragOutputs = QByteArrayLiteral( - "#version 150 core\n" \ - "out vec4 color;\n" \ - "out vec2 temp;\n" \ - "void main()\n" \ - "{\n" \ - " color = vec4(1.0, 0.0, 0.0, 1.0);\n" \ - " temp = vec2(1.0, 0.3);\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( - "#version 150 core\n" \ - "out vec4 color;\n" \ - "uniform float multiplier;\n" \ - "uniform vec2 multiplierVec2;\n" \ - "uniform vec3 multiplierVec3;\n" \ - "uniform vec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ - " color = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsInt = QByteArrayLiteral( - "#version 150 core\n" \ - "out vec4 color;\n" \ - "uniform int multiplier;\n" \ - "uniform ivec2 multiplierVec2;\n" \ - "uniform ivec3 multiplierVec3;\n" \ - "uniform ivec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ - " color = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsUInt = QByteArrayLiteral( - "#version 150 core\n" \ - "out vec4 color;\n" \ - "uniform uint multiplier;\n" \ - "uniform uvec2 multiplierVec2;\n" \ - "uniform uvec3 multiplierVec3;\n" \ - "uniform uvec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " uvec4 randomMult = multiplierVec4 + uvec4(multiplierVec3, 0) + uvec4(multiplierVec2, 0, 0);\n" \ - " color = uvec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( - "#version 150 core\n" \ - "out vec4 color;\n" \ - "uniform mat2 m2;\n" \ - "uniform mat2x3 m23;\n" \ - "uniform mat3x2 m32;\n" \ - "uniform mat2x4 m24;\n" \ - "uniform mat4x2 m42;\n" \ - "uniform mat3 m3;\n" \ - "uniform mat3x4 m34;\n" \ - "uniform mat4x3 m43;\n" \ - "uniform mat4 m4;\n" \ - "void main()\n" \ - "{\n" \ - " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ - " color = vec4(1, 0, 0, 1) * lengthSum;\n" \ - "}\n"); - -const QByteArray fragCodeUniformBuffer = QByteArrayLiteral( - "#version 150 core\n" \ - "out vec4 color;\n" \ - "in vec2 texCoord;\n" \ - "flat in int colorIndex;\n" \ - "uniform ColorArray\n" \ - "{\n" \ - " vec4 colors[256];\n" \ - "};\n" \ - "void main()\n" \ - "{\n" \ - " color = colors[colorIndex] + vec4(texCoord.s, texCoord.t, 0.0, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeSamplers = QByteArrayLiteral( - "#version 150 core\n" \ - "in vec2 texCoord;\n" \ - "out vec4 color;\n" \ - "uniform sampler1D s1;\n" \ - "uniform sampler2D s2;\n" \ - "uniform sampler2DArray s2a;\n" \ - "uniform sampler3D s3;\n" \ - "uniform samplerCube scube;\n" \ - "uniform sampler2DRect srect;\n" \ - "void main()\n" \ - "{\n" \ - " color = vec4(1, 0, 0, 1) *" \ - " texture(s1, texCoord.x) *" \ - " texture(s2, texCoord) *" \ - " texture(s2a, vec3(texCoord, 0.0)) *" \ - " texture(s3, vec3(texCoord, 0.0)) *" \ - " texture(scube, vec3(texCoord, 0)) *" \ - " texture(srect, texCoord);\n" \ - "}\n"); - -} // anonymous - -class tst_GraphicsHelperGL3_2 : public QObject -{ - Q_OBJECT -private Q_SLOTS: - - void init() - { - m_window.reset(new QWindow); - m_window->setSurfaceType(QWindow::OpenGLSurface); - m_window->setGeometry(0, 0, 10, 10); - m_window->create(); - - QSurfaceFormat format; - format.setVersion(3, 2); - format.setProfile(QSurfaceFormat::CoreProfile); - format.setDepthBufferSize(24); - format.setSamples(4); - format.setStencilBufferSize(8); - m_window->setFormat(format); - m_glContext.setFormat(format); - - if (!m_glContext.create()) { - qWarning() << "Failed to create OpenGL context"; - return; - } - - if (!m_glContext.makeCurrent(m_window.data())) { - qWarning() << "Failed to make OpenGL context current"; - return; - } - - if ((m_func = m_glContext.versionFunctions()) != nullptr) { - m_glHelper.initializeHelper(&m_glContext, m_func); - m_initializationSuccessful = true; - } - } - - void cleanup() - { - m_glContext.doneCurrent(); - } - - void alphaTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - // Deprecated - } - - void bindBufferBase() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint bufferId = 0; - // WHEN - m_func->glGenBuffers(1, &bufferId); - // THEN - QVERIFY(bufferId != 0); - - - // WHEN - m_func->glBindBuffer(GL_UNIFORM_BUFFER, bufferId); - m_glHelper.bindBufferBase(GL_UNIFORM_BUFFER, 2, bufferId); - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundToPointBufferId = 0; - m_func->glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, 2, &boundToPointBufferId); - QVERIFY(boundToPointBufferId == GLint(bufferId)); - - // Restore to sane state - m_func->glBindBuffer(GL_UNIFORM_BUFFER, 0); - m_func->glDeleteBuffers(1, &bufferId); - } - - void bindFragDataLocation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); - - // WHEN - QHash fragLocations; - fragLocations.insert(QStringLiteral("temp"), 2); - fragLocations.insert(QStringLiteral("color"), 1); - m_glHelper.bindFragDataLocation(shaderProgram.programId(), fragLocations); - - // THEN - QVERIFY(shaderProgram.link()); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - const GLint tempLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "temp"); - const GLint colorLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "color"); - QCOMPARE(tempLocation, 2); - QCOMPARE(colorLocation, 1); - } - - void bindFrameBufferAttachment() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA32F); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture.create()) - qWarning() << "Texture creation failed"; - texture.allocateStorage(); - QVERIFY(texture.isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureAttachmentId = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, - &textureAttachmentId); - QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void bindFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); - - // THEN - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundindFBOId = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // Cleanup - m_func->glDeleteFramebuffers(1, &fboId); - } - - void bindShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - // Not supported in OpenGL 3.2 - } - - void bindUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - // WHEN - GLint index = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); - m_glHelper.bindUniformBlock(shaderProgram.programId(), index, 1); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void blendEquation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLint equation = 0; - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_ADD); - - // WHEN - m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); - - // THEN - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); - } - - void blendFunci() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - // Not supported by OpenGL 3.2 - } - - void blendFuncSeparatei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // Not supported by OpenGL 3.2 - } - - void boundFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - // THEN - GLint boundBuffer = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); - QCOMPARE(GLuint(boundBuffer), fboId); - - // THEN - QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); - - // Reset state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void checkFrameBufferComplete() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - QVERIFY(m_glHelper.checkFrameBufferComplete()); - - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void clearBufferf() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - // Create 4 attachments - QOpenGLTexture *textures[4]; - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // Set Draw buffers - GLenum clearBufferEnum = GL_COLOR_ATTACHMENT3; - m_func->glDrawBuffers(1, &clearBufferEnum); - - const GLint bufferIndex = 0; // index of the element in the draw buffers - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // WHEN - const QVector4D clearValue1 = QVector4D(0.5f, 0.2f, 0.4f, 0.8f); - m_func->glClearBufferfv(GL_COLOR, bufferIndex, reinterpret_cast(&clearValue1)); - error = m_func->glGetError(); - QVERIFY(error == 0); - - // THEN - QVector colors(512 * 512); - textures[3]->bind(); - m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); - textures[3]->release(); - for (const QVector4D c : colors) { - QVERIFY(c == clearValue1); - } - - // WHEN - const QVector4D clearValue2 = QVector4D(0.4f, 0.5f, 0.4f, 1.0f); - m_glHelper.clearBufferf(bufferIndex, clearValue2); - - // THEN - textures[3]->bind(); - m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); - textures[3]->release(); - for (const QVector4D c : colors) { - QVERIFY(c == clearValue2); - } - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void createFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // WHEN - const GLuint fboId = m_glHelper.createFrameBufferObject(); - - // THEN - QVERIFY(fboId != 0); - - // Restore - m_func->glDeleteFramebuffers(1, &fboId); - } - - void depthMask() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLboolean depthWritingEnabled = false; - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - - // THEN - QVERIFY(depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_FALSE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(!depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_TRUE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(depthWritingEnabled); - } - - void depthTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_DEPTH_TEST); - m_func->glDepthFunc(GL_LESS); - - // WHEN - m_glHelper.depthTest(GL_LEQUAL); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - GLint depthMode = 0; - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LEQUAL); - - // WHEN - m_glHelper.depthTest(GL_LESS); - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LESS); - } - - void disableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_CLIP_DISTANCE0 + 5); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - - // WHEN - m_glHelper.disableClipPlane(5); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - } - - void disablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glEnablei(GL_BLEND, 2); - - // THEN - QVERIFY(m_func->glIsEnabledi(GL_BLEND, 2)); - - // WHEN - m_glHelper.disablei(GL_BLEND, 2); - - // THEN - QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 2)); - } - - void disablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_PRIMITIVE_RESTART); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - - // WHEN - m_glHelper.disablePrimitiveRestart(); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - } - - void drawBuffers() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - QOpenGLTexture *textures[4]; - - // Create 4 attachments - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // WHEN - GLenum bufferEnum = GL_COLOR_ATTACHMENT4; - m_func->glDrawBuffers(1, &bufferEnum); - - // THEN - GLint enumValue = -1; - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); - - // WHEN - GLint newBufferEnum = 2; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // WHEN - newBufferEnum = 0; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void enableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_CLIP_DISTANCE0 + 4); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - - // WHEN - m_glHelper.enableClipPlane(4); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - } - - void enablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisablei(GL_BLEND, 4); - - // THEN - QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 4)); - - // WHEN - m_glHelper.enablei(GL_BLEND, 4); - - // THEN - QVERIFY(m_func->glIsEnabledi(GL_BLEND, 4)); - } - - void enablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_PRIMITIVE_RESTART); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - - // WHEN - m_glHelper.enablePrimitiveRestart(883); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - GLint restartIndex = 0; - m_func->glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX, &restartIndex); - QCOMPARE(restartIndex, 883); - - // Restore - m_func->glDisable(GL_PRIMITIVE_RESTART); - } - - void enableVertexAttribute() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - shaderProgram.bind(); - - // WHEN - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void frontFace() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glFrontFace(GL_CW); - - // THEN - GLint face = 0; - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CW); - - // WHEN - m_glHelper.frontFace(GL_CCW); - - // THEN - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CCW); - } - - void getRenderBufferDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint renderBufferId = 0; - m_func->glGenRenderbuffers(1, &renderBufferId); - QVERIFY(renderBufferId != 0); - - // WHEN - m_func->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_func->glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, 512, 512); - m_func->glBindRenderbuffer(GL_RENDERBUFFER, 0); - const QSize dimensions = m_glHelper.getRenderBufferDimensions(renderBufferId); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - - // Restore - m_func->glDeleteRenderbuffers(1, &renderBufferId); - } - - void getTextureDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - - // WHEN - const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - } - - void pointSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_PROGRAM_POINT_SIZE); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); - GLfloat size = 0; - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 1.0f); - - // WHEN - m_glHelper.pointSize(false, 0.5f); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 0.5f); - } - - void maxClipPlaneCount() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLint maxCount = -1; - m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); - - // THEN - QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); - } - - void programUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - // WHEN - const QVector activeUniformBlocks = m_glHelper.programUniformBlocks(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniformBlocks.size(), 1); - const ShaderUniformBlock uniformBlock = activeUniformBlocks.first(); - - QCOMPARE(uniformBlock.m_activeUniformsCount, 1); - QCOMPARE(uniformBlock.m_name, QStringLiteral("ColorArray")); - - GLint blockIndex = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); - GLint blockBinding = -1; - m_func->glGetActiveUniformBlockiv(shaderProgram.programId(), blockIndex, GL_UNIFORM_BLOCK_BINDING, &blockBinding); - QCOMPARE(blockIndex, uniformBlock.m_index); - QCOMPARE(blockBinding, uniformBlock.m_binding); - } - - void programAttributesAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeAttributes.size(), 2); - std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_name < b.m_name; }); - - const ShaderAttribute attribute1 = activeAttributes.at(0); - QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); - QCOMPARE(attribute1.m_size, 1); - QCOMPARE(attribute1.m_location, shaderProgram.attributeLocation("vertexPosition")); - QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); - - const ShaderAttribute attribute2 = activeAttributes.at(1); - QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); - QCOMPARE(attribute2.m_size, 1); - QCOMPARE(attribute2.m_location, shaderProgram.attributeLocation("vertexTexCoord")); - QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); - } - - void programUniformsAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniforms.size(), 4); - std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_name < b.m_name; }); - - const ShaderUniform uniform1 = activeUniforms.at(0); - QCOMPARE(uniform1.m_location, shaderProgram.uniformLocation("multiplier")); - QCOMPARE(uniform1.m_offset, -1); - QCOMPARE(uniform1.m_blockIndex, -1); - QCOMPARE(uniform1.m_arrayStride, -1); - QCOMPARE(uniform1.m_matrixStride, -1); - QCOMPARE(uniform1.m_size, 1); - QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); - QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); - - const ShaderUniform uniform2 = activeUniforms.at(1); - QCOMPARE(uniform2.m_location, shaderProgram.uniformLocation("multiplierVec2")); - QCOMPARE(uniform2.m_offset, -1); - QCOMPARE(uniform2.m_blockIndex, -1); - QCOMPARE(uniform2.m_arrayStride, -1); - QCOMPARE(uniform2.m_matrixStride, -1); - QCOMPARE(uniform2.m_size, 1); - QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); - QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); - - const ShaderUniform uniform3 = activeUniforms.at(2); - QCOMPARE(uniform3.m_location, shaderProgram.uniformLocation("multiplierVec3")); - QCOMPARE(uniform3.m_offset, -1); - QCOMPARE(uniform3.m_blockIndex, -1); - QCOMPARE(uniform3.m_arrayStride, -1); - QCOMPARE(uniform3.m_matrixStride, -1); - QCOMPARE(uniform3.m_size, 1); - QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); - QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); - - const ShaderUniform uniform4 = activeUniforms.at(3); - QCOMPARE(uniform4.m_location, shaderProgram.uniformLocation("multiplierVec4")); - QCOMPARE(uniform4.m_offset, -1); - QCOMPARE(uniform4.m_blockIndex, -1); - QCOMPARE(uniform4.m_arrayStride, -1); - QCOMPARE(uniform4.m_matrixStride, -1); - QCOMPARE(uniform4.m_size, 1); - QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); - QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); - } - - void programShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // Not supported in 3.2 - } - - void releaseFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.releaseFrameBufferObject(fboId); - - // THEN - QVERIFY(!m_func->glIsFramebuffer(fboId)); - } - - void setMSAAEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_MULTISAMPLE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - } - - void setAlphaCoverageEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - } - - void setClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // Deprecated in 3.3 core - } - - void setSeamlessCubemap() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - } - - void setVerticesPerPatch() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - } - -#define SUPPORTS_FEATURE(Feature, IsSupported) \ - QVERIFY(m_glHelper.supportsFeature(Feature) == IsSupported); - - void supportsFeature() - { - SUPPORTS_FEATURE(GraphicsHelperInterface::MRT, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::BindableFragmentOutputs, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::PrimitiveRestart, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::RenderBufferDimensionRetrieval, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::TextureDimensionRetrieval, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::ShaderStorageObject, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::Compute, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::DrawBuffersBlend, false); - // Tesselation could be true or false depending on extensions so not tested - SUPPORTS_FEATURE(GraphicsHelperInterface::BlitFramebuffer, true); - } - - -#define ADD_UNIFORM_ENTRY(FragShader, Name, Type, ComponentSize, ExpectedRawSize) \ - QTest::newRow(#FragShader"_"#Type) << FragShader << QStringLiteral(Name) << Type << ComponentSize << ExpectedRawSize; - - void uniformsByteSize_data() - { - QTest::addColumn("fragShader"); - QTest::addColumn("name"); - QTest::addColumn("type"); - QTest::addColumn("componentSize"); - QTest::addColumn("expectedByteSize"); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplier", GL_FLOAT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec2", GL_FLOAT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec3",GL_FLOAT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec4", GL_FLOAT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplier", GL_INT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec2", GL_INT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec3", GL_INT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec4", GL_INT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplier", GL_UNSIGNED_INT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec2", GL_UNSIGNED_INT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec3", GL_UNSIGNED_INT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec4", GL_UNSIGNED_INT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m2", GL_FLOAT_MAT2, 1, 4 * 2 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m23", GL_FLOAT_MAT2x3, 1, 4 * 2 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m32", GL_FLOAT_MAT3x2, 1, 4 * 3 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m24", GL_FLOAT_MAT2x4, 1, 4 * 2 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m42", GL_FLOAT_MAT4x2, 1, 4 * 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m3", GL_FLOAT_MAT3, 1, 4 * 3 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m34", GL_FLOAT_MAT3x4, 1, 4 * 3 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m43", GL_FLOAT_MAT4x3, 1, 4 * 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m4", GL_FLOAT_MAT4, 1, 4 * 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s1", GL_SAMPLER_1D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2", GL_SAMPLER_2D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2a", GL_SAMPLER_2D_ARRAY, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s3", GL_SAMPLER_3D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "scube", GL_SAMPLER_CUBE, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "srect", GL_SAMPLER_2D_RECT, 1, 4); - } - - void uniformsByteSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QFETCH(QByteArray, fragShader); - QFETCH(QString, name); - QFETCH(int, type); - QFETCH(int, componentSize); - QFETCH(int, expectedByteSize); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); - QVERIFY(shaderProgram.link()); - - GLint location = shaderProgram.uniformLocation(name); - // WHEN - const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - ShaderUniform matchingUniform; - for (const ShaderUniform &u : activeUniforms) { - if (u.m_location == location) { - matchingUniform = u; - break; - } - } - - - // THEN - QCOMPARE(matchingUniform.m_location, location); - QCOMPARE(matchingUniform.m_type, GLuint(type)); - QCOMPARE(matchingUniform.m_size, componentSize); - - // WHEN - const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); - - // THEN - QCOMPARE(expectedByteSize, computedRawByteSize); - - // Restore - m_func->glUseProgram(0); - } - - void useProgram() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); - - // THEN - QVERIFY(shaderProgram.link()); - - GLint currentProg = 0; - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - - // WHEN - m_glHelper.useProgram(shaderProgram.programId()); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QCOMPARE(GLuint(currentProg), shaderProgram.programId()); - - // WHEN - m_glHelper.useProgram(0); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - } - - void vertexAttribDivisor() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - // Not available in 3.2 - } - - void vertexAttributePointer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); - - const int vertexCount = 99; - QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); - positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - positionBuffer.create(); - positionBuffer.bind(); - positionBuffer.allocate(vertexCount * sizeof(QVector3D)); - - QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); - texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - texCoordBuffer.create(); - texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); - - QOpenGLBuffer colorIndexBuffer(QOpenGLBuffer::VertexBuffer); - colorIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - colorIndexBuffer.create(); - colorIndexBuffer.allocate(vertexCount * sizeof(int)); - - // WHEN - shaderProgram.bind(); - positionBuffer.bind(); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); - - texCoordBuffer.bind(); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); - - colorIndexBuffer.bind(); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - m_glHelper.vertexAttributePointer(GL_INT, colorIndexLocation, 1, GL_INT, GL_TRUE, 0, 0); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void glUniform1fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat value = 883.0f; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1fv(location, 1, &value); - - // THEN - GLfloat setValue = 0.0f; - m_func->glGetUniformfv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[2] = { 383.0f, 427.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2fv(location, 1, values); - - // THEN - GLfloat setValues[2] = { 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3fv(location, 1, values); - - // THEN - GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4fv(location, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint value = 883; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1iv(location, 1, &value); - - // THEN - GLint setValue = 0; - m_func->glGetUniformiv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[2] = { 383, 427 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2iv(location, 1, values); - - // THEN - GLint setValues[2] = { 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[3] = { 572, 1340, 1584 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3iv(location, 1, values); - - // THEN - GLint setValues[3] = { 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[4] = { 454, 350, 883, 355 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4iv(location, 1, values); - - // THEN - GLint setValues[4] = { 0, 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint value = 883U; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1uiv(location, 1, &value); - - // THEN - GLuint setValue = 0U; - m_func->glGetUniformuiv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[2] = { 383U, 427U }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2uiv(location, 1, values); - - // THEN - GLuint setValues[2] = { 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[3] = { 572U, 1340U, 1584U }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3uiv(location, 1, values); - - // THEN - GLuint setValues[3] = { 0U, 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[4] = { 454U, 350U, 883U, 355U }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4uiv(location, 1, values); - - // THEN - GLuint setValues[4] = { 0U, 0U, 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - const GLint location = shaderProgram.uniformLocation("m2"); - m_glHelper.glUniformMatrix2fv(location, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; - const GLint location = shaderProgram.uniformLocation("m3"); - m_glHelper.glUniformMatrix3fv(location, 1, values); - - // THEN - GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 9; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; - const GLint location = shaderProgram.uniformLocation("m4"); - m_glHelper.glUniformMatrix4fv(location, 1, values); - - // THEN - GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 16; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m23"); - m_glHelper.glUniformMatrix2x3fv(location, 1, values); - - // THEN - GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 6; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m32"); - m_glHelper.glUniformMatrix3x2fv(location, 1, values); - - // THEN - GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 6; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m24"); - m_glHelper.glUniformMatrix2x4fv(location, 1, values); - - // THEN - GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 8; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m42"); - m_glHelper.glUniformMatrix4x2fv(location, 1, values); - - // THEN - GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 8; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f}; - const GLint location = shaderProgram.uniformLocation("m34"); - m_glHelper.glUniformMatrix3x4fv(location, 1, values); - - // THEN - GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 12; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m43"); - m_glHelper.glUniformMatrix4x3fv(location, 1, values); - - // THEN - GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 12; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void blitFramebuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - GLint maxSamples; - m_func->glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); - if (maxSamples < 1) - QSKIP("This test requires an implementation that supports multisampled textures"); - - // GIVEN - GLuint fbos[2]; - GLuint fboTextures[2]; - - m_func->glGenFramebuffers(2, fbos); - m_func->glGenTextures(2, fboTextures); - - m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fboTextures[0]); - m_func->glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, maxSamples, GL_RGBA8, 10, 10, true); - m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); - - m_func->glBindTexture(GL_TEXTURE_2D, fboTextures[1]); - m_func->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 10, 10, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); - m_func->glBindTexture(GL_TEXTURE_2D, 0); - - m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[1]); - m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[1], 0); - - GLenum status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[0]); - m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[0], 0); - - status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - m_func->glEnable(GL_MULTISAMPLE); - m_func->glClearColor(0.2f, 0.2f, 0.2f, 0.2f); - m_func->glClear(GL_COLOR_BUFFER_BIT); - m_func->glDisable(GL_MULTISAMPLE); - - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); - - // WHEN - m_glHelper.blitFramebuffer(0,0,10,10,0,0,10,10, GL_COLOR_BUFFER_BIT, GL_NEAREST); - - m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[1]); - - GLuint result[10*10]; - m_func->glReadPixels(0,0,10,10,GL_RGBA, GL_UNSIGNED_BYTE, result); - - // THEN - GLuint v = (0.2f) * 255; - v = v | (v<<8) | (v<<16) | (v<<24); - for (GLuint value : result) { - QCOMPARE(value, v); - } - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - - m_func->glDeleteFramebuffers(2, fbos); - m_func->glDeleteTextures(2, fboTextures); - } - -#define ADD_GL_TYPE_ENTRY(Type, Expected) \ - QTest::newRow(#Type) << Type << Expected; - - void uniformTypeFromGLType_data() - { - QTest::addColumn("glType"); - QTest::addColumn("expected"); - - ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); - ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); - ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); - ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT, UniformType::UInt); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC2, UniformType::UIVec2); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC3, UniformType::UIVec3); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC4, UniformType::UIVec4); - ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x3, UniformType::Mat2x3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x4, UniformType::Mat2x4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x2, UniformType::Mat3x2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x2, UniformType::Mat4x2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x3, UniformType::Mat4x3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x4, UniformType::Mat3x4); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_RECT, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE, UniformType::Sampler); - } - - void uniformTypeFromGLType() - { - // GIVEN - QFETCH(int, glType); - QFETCH(UniformType, expected); - - // WHEN - UniformType computed = m_glHelper.uniformTypeFromGLType(glType); - - // THEN - QCOMPARE(computed, expected); - } - - void drawBuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.drawBuffer(GL_FRONT); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // THEN - GLint p; - m_func->glGetIntegerv(GL_DRAW_BUFFER, &p); - QCOMPARE(p, GL_FRONT); - } - - void readBuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.readBuffer(GL_FRONT); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_READ_BUFFER, &p); - QCOMPARE(p, GL_FRONT); - } - - void fenceSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - - // THEN - QVERIFY(sync != nullptr); - QCOMPARE(m_func->glIsSync(sync), GL_TRUE); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void clientWaitSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - QElapsedTimer t; - t.start(); - - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - - m_glHelper.clientWaitSync(sync, 1000000); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - qDebug() << t.nsecsElapsed(); - } - - void waitSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_func->glFlush(); - m_glHelper.waitSync(sync); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void wasSyncSignaled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_func->glFlush(); - m_glHelper.waitSync(sync); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // Shouldn't loop forever - while (!m_glHelper.wasSyncSignaled(sync)) - ; - } - - void deleteSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_glHelper.clientWaitSync(sync, GLuint64(-1)); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - QVERIFY(m_glHelper.wasSyncSignaled(sync) == true); - - // WHEN - m_glHelper.deleteSync(sync); - - // THEN - QCOMPARE(m_func->glIsSync(sync), GL_FALSE); - } - - void rasterMode() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.2 functions not supported"); - - m_func->glGetError(); - - m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_POLYGON_MODE, &p); - QCOMPARE(p, GL_LINE); - } - -private: - QScopedPointer m_window; - QOpenGLContext m_glContext; - GraphicsHelperGL3_2 m_glHelper; - QOpenGLFunctions_3_2_Core *m_func = nullptr; - bool m_initializationSuccessful = false; -}; - -#endif - -int main(int argc, char *argv[]) -{ -#ifdef TEST_SHOULD_BE_PERFORMED - QGuiApplication app(argc, argv); - app.setAttribute(Qt::AA_Use96Dpi, true); - tst_GraphicsHelperGL3_2 tc; - QTEST_SET_MAIN_SOURCE_PATH - return QTest::qExec(&tc, argc, argv); -#endif - return 0; -} - -#ifdef TEST_SHOULD_BE_PERFORMED -#include "tst_graphicshelpergl3_2.moc" -#endif diff --git a/tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro b/tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro deleted file mode 100644 index 36bda15b2..000000000 --- a/tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = app - -TARGET = tst_graphicshelpergl3_3 - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += \ - tst_graphicshelpergl3_3.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp b/tests/auto/render/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp deleted file mode 100644 index 874c83f0b..000000000 --- a/tests/auto/render/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp +++ /dev/null @@ -1,2393 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(QT_OPENGL_ES_2) && defined(QT_OPENGL_3_2) - -#define TEST_SHOULD_BE_PERFORMED 1 - -using namespace Qt3DRender; -using namespace Qt3DRender::Render; - -namespace { - -const QByteArray vertCode = QByteArrayLiteral( - "#version 330 core\n" \ - "in vec3 vertexPosition;\n" \ - "in vec2 vertexTexCoord;\n" \ - "out vec2 texCoord;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vertexTexCoord;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray vertCodeUniformBuffer = QByteArrayLiteral( - "#version 330 core\n" \ - "in vec3 vertexPosition;\n" \ - "in vec2 vertexTexCoord;\n" \ - "in int vertexColorIndex;\n" \ - "out vec2 texCoord;\n" \ - "flat out int colorIndex;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vertexTexCoord;\n" \ - " colorIndex = vertexColorIndex;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeFragOutputs = QByteArrayLiteral( - "#version 330 core\n" \ - "out vec4 color;\n" \ - "out vec2 temp;\n" \ - "void main()\n" \ - "{\n" \ - " color = vec4(1.0, 0.0, 0.0, 1.0);\n" \ - " temp = vec2(1.0, 0.3);\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( - "#version 330 core\n" \ - "out vec4 color;\n" \ - "uniform float multiplier;\n" \ - "uniform vec2 multiplierVec2;\n" \ - "uniform vec3 multiplierVec3;\n" \ - "uniform vec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ - " color = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsInt = QByteArrayLiteral( - "#version 330 core\n" \ - "out ivec4 color;\n" \ - "uniform int multiplier;\n" \ - "uniform ivec2 multiplierVec2;\n" \ - "uniform ivec3 multiplierVec3;\n" \ - "uniform ivec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ - " color = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsUInt = QByteArrayLiteral( - "#version 330 core\n" \ - "out uvec4 color;\n" \ - "uniform uint multiplier;\n" \ - "uniform uvec2 multiplierVec2;\n" \ - "uniform uvec3 multiplierVec3;\n" \ - "uniform uvec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " uvec4 randomMult = multiplierVec4 + uvec4(multiplierVec3, 0) + uvec4(multiplierVec2, 0, 0);\n" \ - " color = uvec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( - "#version 330 core\n" \ - "out vec4 color;\n" \ - "uniform mat2 m2;\n" \ - "uniform mat2x3 m23;\n" \ - "uniform mat3x2 m32;\n" \ - "uniform mat2x4 m24;\n" \ - "uniform mat4x2 m42;\n" \ - "uniform mat3 m3;\n" \ - "uniform mat3x4 m34;\n" \ - "uniform mat4x3 m43;\n" \ - "uniform mat4 m4;\n" \ - "void main()\n" \ - "{\n" \ - " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ - " color = vec4(1, 0, 0, 1) * lengthSum;\n" \ - "}\n"); - -const QByteArray fragCodeUniformBuffer = QByteArrayLiteral( - "#version 330 core\n" \ - "out vec4 color;\n" \ - "in vec2 texCoord;\n" \ - "flat in int colorIndex;\n" \ - "uniform ColorArray\n" \ - "{\n" \ - " vec4 colors[256];\n" \ - "};\n" \ - "void main()\n" \ - "{\n" \ - " color = colors[colorIndex] + vec4(texCoord.s, texCoord.t, 0.0, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeSamplers = QByteArrayLiteral( - "#version 330 core\n" \ - "in vec2 texCoord;\n" \ - "out vec4 color;\n" \ - "uniform sampler1D s1;\n" \ - "uniform sampler2D s2;\n" \ - "uniform sampler2DArray s2a;\n" \ - "uniform sampler3D s3;\n" \ - "uniform samplerCube scube;\n" \ - "uniform sampler2DRect srect;\n" \ - "void main()\n" \ - "{\n" \ - " color = vec4(1, 0, 0, 1) *" \ - " texture(s1, texCoord.x) *" \ - " texture(s2, texCoord) *" \ - " texture(s2a, vec3(texCoord, 0.0)) *" \ - " texture(s3, vec3(texCoord, 0.0)) *" \ - " texture(scube, vec3(texCoord, 0)) *" \ - " texture(srect, texCoord);\n" \ - "}\n"); - -} // anonymous - -class tst_GraphicsHelperGL3_3 : public QObject -{ - Q_OBJECT -private Q_SLOTS: - - void init() - { - m_window.reset(new QWindow); - m_window->setSurfaceType(QWindow::OpenGLSurface); - m_window->setGeometry(0, 0, 10, 10); - - QSurfaceFormat format; - format.setVersion(3, 3); - format.setProfile(QSurfaceFormat::CoreProfile); - format.setDepthBufferSize(24); - format.setSamples(4); - format.setStencilBufferSize(8); - m_window->setFormat(format); - m_glContext.setFormat(format); - - m_window->create(); - - if (!m_glContext.create()) { - qWarning() << "Failed to create OpenGL context"; - return; - } - - if (!m_glContext.makeCurrent(m_window.data())) { - qWarning() << "Failed to maed OpenGL context current"; - return; - } - - if ((m_func = m_glContext.versionFunctions()) != nullptr) { - m_glHelper.initializeHelper(&m_glContext, m_func); - m_initializationSuccessful = true; - } - } - - void cleanup() - { - m_glContext.doneCurrent(); - } - - void alphaTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - // Deprecated - } - - void bindBufferBase() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLuint bufferId = 0; - // WHEN - m_func->glGenBuffers(1, &bufferId); - // THEN - QVERIFY(bufferId != 0); - - - // WHEN - m_func->glBindBuffer(GL_UNIFORM_BUFFER, bufferId); - m_glHelper.bindBufferBase(GL_UNIFORM_BUFFER, 2, bufferId); - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundToPointBufferId = 0; - m_func->glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, 2, &boundToPointBufferId); - QVERIFY(boundToPointBufferId == GLint(bufferId)); - - // Restore to sane state - m_func->glBindBuffer(GL_UNIFORM_BUFFER, 0); - m_func->glDeleteBuffers(1, &bufferId); - } - - void bindFragDataLocation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); - - // WHEN - QHash fragLocations; - fragLocations.insert(QStringLiteral("temp"), 2); - fragLocations.insert(QStringLiteral("color"), 1); - m_glHelper.bindFragDataLocation(shaderProgram.programId(), fragLocations); - - // THEN - QVERIFY(shaderProgram.link()); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - const GLint tempLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "temp"); - const GLint colorLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "color"); - QCOMPARE(tempLocation, 2); - QCOMPARE(colorLocation, 1); - } - - void bindFrameBufferAttachment() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - { - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - - GLint maxAttachmentsCount = 0; - m_func->glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxAttachmentsCount); - - // THEN - QVERIFY(fboId != 0); - QVERIFY(maxAttachmentsCount >= 3); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture.create()) - qWarning() << "Texture creation failed"; - texture.allocateStorage(); - QVERIFY(texture.isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QCOMPARE(int(status), GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureAttachmentId = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, - &textureAttachmentId); - QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - { - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::TargetCubeMap); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA32F); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture.create()) - qWarning() << "Texture creation failed"; - texture.allocateStorage(); - QVERIFY(texture.isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - { // Check All Faces - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - attachment.m_face = Qt3DRender::QAbstractTexture::AllFaces; - - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureIsLayered = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_LAYERED, - &textureIsLayered); - QCOMPARE(textureIsLayered, GL_TRUE); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - { // Check Specific Faces - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - attachment.m_face = Qt3DRender::QAbstractTexture::CubeMapNegativeZ; - - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureFace = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, - &textureFace); - QCOMPARE(textureFace, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); - GLint textureIsLayered = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_LAYERED, - &textureIsLayered); - QCOMPARE(textureIsLayered, GL_FALSE); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - } - } - - void bindFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); - - // THEN - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundindFBOId = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // Cleanup - m_func->glDeleteFramebuffers(1, &fboId); - } - - void bindShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - // Not supported in OpenGL 3.3 - } - - void bindUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - // WHEN - GLint index = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); - m_glHelper.bindUniformBlock(shaderProgram.programId(), index, 1); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void blendEquation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLint equation = 0; - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_ADD); - - // WHEN - m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); - - // THEN - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); - } - - void blendFunci() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - // Not supported by OpenGL 3.3 - } - - void blendFuncSeparatei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // Not supported by OpenGL 3.3 - } - - void boundFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - // THEN - GLint boundBuffer = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); - QCOMPARE(GLuint(boundBuffer), fboId); - - // THEN - QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); - - // Reset state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void checkFrameBufferComplete() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - QVERIFY(m_glHelper.checkFrameBufferComplete()); - - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void clearBufferf() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - // Create 4 attachments - QOpenGLTexture *textures[4]; - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // Set Draw buffers - GLenum clearBufferEnum = GL_COLOR_ATTACHMENT3; - m_func->glDrawBuffers(1, &clearBufferEnum); - - const GLint bufferIndex = 0; // index of the element in the draw buffers - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // WHEN - const QVector4D clearValue1 = QVector4D(0.5f, 0.2f, 0.4f, 0.8f); - m_func->glClearBufferfv(GL_COLOR, bufferIndex, reinterpret_cast(&clearValue1)); - error = m_func->glGetError(); - QVERIFY(error == 0); - - // THEN - QVector colors(512 * 512); - textures[3]->bind(); - m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); - textures[3]->release(); - - for (const QVector4D c : colors) { - QVERIFY(c == clearValue1); - } - - // WHEN - const QVector4D clearValue2 = QVector4D(0.4f, 0.5f, 0.4f, 1.0f); - m_glHelper.clearBufferf(bufferIndex, clearValue2); - - // THEN - textures[3]->bind(); - m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); - textures[3]->release(); - for (const QVector4D c : colors) { - QVERIFY(c == clearValue2); - } - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void createFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // WHEN - const GLuint fboId = m_glHelper.createFrameBufferObject(); - - // THEN - QVERIFY(fboId != 0); - - // Restore - m_func->glDeleteFramebuffers(1, &fboId); - } - - void depthMask() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLboolean depthWritingEnabled = false; - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - - // THEN - QVERIFY(depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_FALSE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(!depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_TRUE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(depthWritingEnabled); - } - - void depthTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_DEPTH_TEST); - m_func->glDepthFunc(GL_LESS); - - // WHEN - m_glHelper.depthTest(GL_LEQUAL); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - GLint depthMode = 0; - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LEQUAL); - - // WHEN - m_glHelper.depthTest(GL_LESS); - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LESS); - } - - void disableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_CLIP_DISTANCE0 + 5); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - - // WHEN - m_glHelper.disableClipPlane(5); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - } - - void disablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glEnablei(GL_BLEND, 2); - - // THEN - QVERIFY(m_func->glIsEnabledi(GL_BLEND, 2)); - - // WHEN - m_glHelper.disablei(GL_BLEND, 2); - - // THEN - QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 2)); - } - - void disablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_PRIMITIVE_RESTART); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - - // WHEN - m_glHelper.disablePrimitiveRestart(); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - } - - void drawBuffers() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - QOpenGLTexture *textures[4]; - - // Create 4 attachments - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // WHEN - GLenum bufferEnum = GL_COLOR_ATTACHMENT4; - m_func->glDrawBuffers(1, &bufferEnum); - - // THEN - GLint enumValue = -1; - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); - - // WHEN - GLint newBufferEnum = 2; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // WHEN - newBufferEnum = 0; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void enableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_CLIP_DISTANCE0 + 4); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - - // WHEN - m_glHelper.enableClipPlane(4); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - } - - void enablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisablei(GL_BLEND, 4); - - // THEN - QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 4)); - - // WHEN - m_glHelper.enablei(GL_BLEND, 4); - - // THEN - QVERIFY(m_func->glIsEnabledi(GL_BLEND, 4)); - } - - void enablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_PRIMITIVE_RESTART); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - - // WHEN - m_glHelper.enablePrimitiveRestart(883); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - GLint restartIndex = 0; - m_func->glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX, &restartIndex); - QCOMPARE(restartIndex, 883); - - // Restore - m_func->glDisable(GL_PRIMITIVE_RESTART); - } - - void enableVertexAttribute() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - shaderProgram.bind(); - - // WHEN - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void frontFace() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glFrontFace(GL_CW); - - // THEN - GLint face = 0; - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CW); - - // WHEN - m_glHelper.frontFace(GL_CCW); - - // THEN - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CCW); - } - - void getRenderBufferDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLuint renderBufferId = 0; - m_func->glGenRenderbuffers(1, &renderBufferId); - QVERIFY(renderBufferId != 0); - - // WHEN - m_func->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_func->glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, 512, 512); - m_func->glBindRenderbuffer(GL_RENDERBUFFER, 0); - const QSize dimensions = m_glHelper.getRenderBufferDimensions(renderBufferId); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - - // Restore - m_func->glDeleteRenderbuffers(1, &renderBufferId); - } - - void getTextureDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - - // WHEN - const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - } - - void pointSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_PROGRAM_POINT_SIZE); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); - GLfloat size = 0; - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 1.0f); - - // WHEN - m_glHelper.pointSize(false, 0.5f); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 0.5f); - } - - void maxClipPlaneCount() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLint maxCount = -1; - m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); - - // THEN - QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); - } - - void programUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - // WHEN - const QVector activeUniformBlocks = m_glHelper.programUniformBlocks(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniformBlocks.size(), 1); - const ShaderUniformBlock uniformBlock = activeUniformBlocks.first(); - - QCOMPARE(uniformBlock.m_activeUniformsCount, 1); - QCOMPARE(uniformBlock.m_name, QStringLiteral("ColorArray")); - - GLint blockIndex = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); - GLint blockBinding = -1; - m_func->glGetActiveUniformBlockiv(shaderProgram.programId(), blockIndex, GL_UNIFORM_BLOCK_BINDING, &blockBinding); - QCOMPARE(blockIndex, uniformBlock.m_index); - QCOMPARE(blockBinding, uniformBlock.m_binding); - } - - void programAttributesAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeAttributes.size(), 2); - std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_name < b.m_name; }); - - const ShaderAttribute attribute1 = activeAttributes.at(0); - QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); - QCOMPARE(attribute1.m_size, 1); - QCOMPARE(attribute1.m_location, shaderProgram.attributeLocation("vertexPosition")); - QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); - - const ShaderAttribute attribute2 = activeAttributes.at(1); - QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); - QCOMPARE(attribute2.m_size, 1); - QCOMPARE(attribute2.m_location, shaderProgram.attributeLocation("vertexTexCoord")); - QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); - } - - void programUniformsAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniforms.size(), 4); - std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_name < b.m_name; }); - - const ShaderUniform uniform1 = activeUniforms.at(0); - QCOMPARE(uniform1.m_location, shaderProgram.uniformLocation("multiplier")); - QCOMPARE(uniform1.m_offset, -1); - QCOMPARE(uniform1.m_blockIndex, -1); - QCOMPARE(uniform1.m_arrayStride, -1); - QCOMPARE(uniform1.m_matrixStride, -1); - QCOMPARE(uniform1.m_size, 1); - QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); - QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); - - const ShaderUniform uniform2 = activeUniforms.at(1); - QCOMPARE(uniform2.m_location, shaderProgram.uniformLocation("multiplierVec2")); - QCOMPARE(uniform2.m_offset, -1); - QCOMPARE(uniform2.m_blockIndex, -1); - QCOMPARE(uniform2.m_arrayStride, -1); - QCOMPARE(uniform2.m_matrixStride, -1); - QCOMPARE(uniform2.m_size, 1); - QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); - QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); - - const ShaderUniform uniform3 = activeUniforms.at(2); - QCOMPARE(uniform3.m_location, shaderProgram.uniformLocation("multiplierVec3")); - QCOMPARE(uniform3.m_offset, -1); - QCOMPARE(uniform3.m_blockIndex, -1); - QCOMPARE(uniform3.m_arrayStride, -1); - QCOMPARE(uniform3.m_matrixStride, -1); - QCOMPARE(uniform3.m_size, 1); - QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); - QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); - - const ShaderUniform uniform4 = activeUniforms.at(3); - QCOMPARE(uniform4.m_location, shaderProgram.uniformLocation("multiplierVec4")); - QCOMPARE(uniform4.m_offset, -1); - QCOMPARE(uniform4.m_blockIndex, -1); - QCOMPARE(uniform4.m_arrayStride, -1); - QCOMPARE(uniform4.m_matrixStride, -1); - QCOMPARE(uniform4.m_size, 1); - QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); - QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); - } - - void programShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // Not supported in 3.3 - } - - void releaseFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.releaseFrameBufferObject(fboId); - - // THEN - QVERIFY(!m_func->glIsFramebuffer(fboId)); - } - - void setMSAAEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_MULTISAMPLE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - } - - void setAlphaCoverageEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - } - - void setClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // Deprecated in 3.3 core - } - - void setSeamlessCubemap() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - } - - void setVerticesPerPatch() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - } - -#define SUPPORTS_FEATURE(Feature, IsSupported) \ - QVERIFY(m_glHelper.supportsFeature(Feature) == IsSupported); - - void supportsFeature() - { - SUPPORTS_FEATURE(GraphicsHelperInterface::MRT, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::BindableFragmentOutputs, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::PrimitiveRestart, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::RenderBufferDimensionRetrieval, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::TextureDimensionRetrieval, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); - SUPPORTS_FEATURE(GraphicsHelperInterface::ShaderStorageObject, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::Compute, false); - SUPPORTS_FEATURE(GraphicsHelperInterface::DrawBuffersBlend, false); - // Tesselation could be true or false depending on extensions so not tested - SUPPORTS_FEATURE(GraphicsHelperInterface::BlitFramebuffer, true); - } - - -#define ADD_UNIFORM_ENTRY(FragShader, Name, Type, ComponentSize, ExpectedRawSize) \ - QTest::newRow(#FragShader"_"#Type) << FragShader << QStringLiteral(Name) << Type << ComponentSize << ExpectedRawSize; - - void uniformsByteSize_data() - { - QTest::addColumn("fragShader"); - QTest::addColumn("name"); - QTest::addColumn("type"); - QTest::addColumn("componentSize"); - QTest::addColumn("expectedByteSize"); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplier", GL_FLOAT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec2", GL_FLOAT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec3",GL_FLOAT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec4", GL_FLOAT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplier", GL_INT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec2", GL_INT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec3", GL_INT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec4", GL_INT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplier", GL_UNSIGNED_INT, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec2", GL_UNSIGNED_INT_VEC2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec3", GL_UNSIGNED_INT_VEC3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec4", GL_UNSIGNED_INT_VEC4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m2", GL_FLOAT_MAT2, 1, 4 * 2 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m23", GL_FLOAT_MAT2x3, 1, 4 * 2 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m32", GL_FLOAT_MAT3x2, 1, 4 * 3 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m24", GL_FLOAT_MAT2x4, 1, 4 * 2 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m42", GL_FLOAT_MAT4x2, 1, 4 * 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m3", GL_FLOAT_MAT3, 1, 4 * 3 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m34", GL_FLOAT_MAT3x4, 1, 4 * 3 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m43", GL_FLOAT_MAT4x3, 1, 4 * 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m4", GL_FLOAT_MAT4, 1, 4 * 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s1", GL_SAMPLER_1D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2", GL_SAMPLER_2D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2a", GL_SAMPLER_2D_ARRAY, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "s3", GL_SAMPLER_3D, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "scube", GL_SAMPLER_CUBE, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, "srect", GL_SAMPLER_2D_RECT, 1, 4); - } - - void uniformsByteSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QFETCH(QByteArray, fragShader); - QFETCH(QString, name); - QFETCH(int, type); - QFETCH(int, componentSize); - QFETCH(int, expectedByteSize); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); - QVERIFY(shaderProgram.link()); - - GLint location = shaderProgram.uniformLocation(name); - // WHEN - const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - ShaderUniform matchingUniform; - for (const ShaderUniform &u : activeUniforms) { - if (u.m_location == location) { - matchingUniform = u; - break; - } - } - - - // THEN - QCOMPARE(matchingUniform.m_location, location); - QCOMPARE(matchingUniform.m_type, GLuint(type)); - QCOMPARE(matchingUniform.m_size, componentSize); - - // WHEN - const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); - - // THEN - QCOMPARE(expectedByteSize, computedRawByteSize); - - // Restore - m_func->glUseProgram(0); - } - - - void useProgram() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); - - // THEN - QVERIFY(shaderProgram.link()); - - GLint currentProg = 0; - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - - // WHEN - m_glHelper.useProgram(shaderProgram.programId()); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QCOMPARE(GLuint(currentProg), shaderProgram.programId()); - - // WHEN - m_glHelper.useProgram(0); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - } - - void vertexAttribDivisor() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - } - - void vertexAttributePointer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); - - const int vertexCount = 99; - QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); - positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - positionBuffer.create(); - positionBuffer.bind(); - positionBuffer.allocate(vertexCount * sizeof(QVector3D)); - - QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); - texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - texCoordBuffer.create(); - texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); - - QOpenGLBuffer colorIndexBuffer(QOpenGLBuffer::VertexBuffer); - colorIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - colorIndexBuffer.create(); - colorIndexBuffer.allocate(vertexCount * sizeof(int)); - - // WHEN - shaderProgram.bind(); - positionBuffer.bind(); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); - - texCoordBuffer.bind(); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); - - colorIndexBuffer.bind(); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - m_glHelper.vertexAttributePointer(GL_INT, colorIndexLocation, 1, GL_INT, GL_TRUE, 0, 0); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void glUniform1fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat value = 883.0f; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1fv(location, 1, &value); - - // THEN - GLfloat setValue = 0.0f; - m_func->glGetUniformfv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[2] = { 383.0f, 427.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2fv(location, 1, values); - - // THEN - GLfloat setValues[2] = { 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3fv(location, 1, values); - - // THEN - GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4fv(location, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint value = 883; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1iv(location, 1, &value); - - // THEN - GLint setValue = 0; - m_func->glGetUniformiv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[2] = { 383, 427 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2iv(location, 1, values); - - // THEN - GLint setValues[2] = { 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[3] = { 572, 1340, 1584 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3iv(location, 1, values); - - // THEN - GLint setValues[3] = { 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[4] = { 454, 350, 883, 355 }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4iv(location, 1, values); - - // THEN - GLint setValues[4] = { 0, 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint value = 883U; - const GLint location = shaderProgram.uniformLocation("multiplier"); - m_glHelper.glUniform1uiv(location, 1, &value); - - // THEN - GLuint setValue = 0U; - m_func->glGetUniformuiv(shaderProgram.programId(), location, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[2] = { 383U, 427U }; - const GLint location = shaderProgram.uniformLocation("multiplierVec2"); - m_glHelper.glUniform2uiv(location, 1, values); - - // THEN - GLuint setValues[2] = { 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[3] = { 572U, 1340U, 1584U }; - const GLint location = shaderProgram.uniformLocation("multiplierVec3"); - m_glHelper.glUniform3uiv(location, 1, values); - - // THEN - GLuint setValues[3] = { 0U, 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[4] = { 454U, 350U, 883U, 355U }; - const GLint location = shaderProgram.uniformLocation("multiplierVec4"); - m_glHelper.glUniform4uiv(location, 1, values); - - // THEN - GLuint setValues[4] = { 0U, 0U, 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - const GLint location = shaderProgram.uniformLocation("m2"); - m_glHelper.glUniformMatrix2fv(location, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; - const GLint location = shaderProgram.uniformLocation("m3"); - m_glHelper.glUniformMatrix3fv(location, 1, values); - - // THEN - GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 9; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; - const GLint location = shaderProgram.uniformLocation("m4"); - m_glHelper.glUniformMatrix4fv(location, 1, values); - - // THEN - GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 16; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m23"); - m_glHelper.glUniformMatrix2x3fv(location, 1, values); - - // THEN - GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 6; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m32"); - m_glHelper.glUniformMatrix3x2fv(location, 1, values); - - // THEN - GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 6; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m24"); - m_glHelper.glUniformMatrix2x4fv(location, 1, values); - - // THEN - GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 8; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m42"); - m_glHelper.glUniformMatrix4x2fv(location, 1, values); - - // THEN - GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 8; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f}; - const GLint location = shaderProgram.uniformLocation("m34"); - m_glHelper.glUniformMatrix3x4fv(location, 1, values); - - // THEN - GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 12; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - const GLint location = shaderProgram.uniformLocation("m43"); - m_glHelper.glUniformMatrix4x3fv(location, 1, values); - - // THEN - GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); - for (int i = 0; i < 12; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - - void blitFramebuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - GLint maxSamples; - m_func->glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); - if (maxSamples < 1) - QSKIP("This test requires an implementation that supports multisampled textures"); - - // GIVEN - GLuint fbos[2]; - GLuint fboTextures[2]; - - m_func->glGenFramebuffers(2, fbos); - m_func->glGenTextures(2, fboTextures); - - m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fboTextures[0]); - m_func->glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, maxSamples, GL_RGBA8, 10, 10, true); - m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); - - m_func->glBindTexture(GL_TEXTURE_2D, fboTextures[1]); - m_func->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 10, 10, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); - m_func->glBindTexture(GL_TEXTURE_2D, 0); - - m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[1]); - m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[1], 0); - - GLenum status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); - QCOMPARE(status, GLenum(GL_FRAMEBUFFER_COMPLETE)); - - m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[0]); - m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[0], 0); - - status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); - QCOMPARE(status, GLenum(GL_FRAMEBUFFER_COMPLETE)); - - m_func->glEnable(GL_MULTISAMPLE); - m_func->glClearColor(0.2f, 0.2f, 0.2f, 0.2f); - m_func->glClear(GL_COLOR_BUFFER_BIT); - m_func->glDisable(GL_MULTISAMPLE); - - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); - - // WHEN - m_glHelper.blitFramebuffer(0,0,10,10,0,0,10,10, GL_COLOR_BUFFER_BIT, GL_NEAREST); - - m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[1]); - - GLuint result[10*10]; - m_func->glReadPixels(0,0,10,10,GL_RGBA, GL_UNSIGNED_BYTE, result); - - // THEN - GLuint v = (0.2f) * 255; - v = v | (v<<8) | (v<<16) | (v<<24); - for (GLuint value : result) { - QCOMPARE(value, v); - } - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - - m_func->glDeleteFramebuffers(2, fbos); - m_func->glDeleteTextures(2, fboTextures); - } - -#define ADD_GL_TYPE_ENTRY(Type, Expected) \ - QTest::newRow(#Type) << Type << Expected; - - void uniformTypeFromGLType_data() - { - QTest::addColumn("glType"); - QTest::addColumn("expected"); - - ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); - ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); - ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); - ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT, UniformType::UInt); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC2, UniformType::UIVec2); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC3, UniformType::UIVec3); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC4, UniformType::UIVec4); - ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x3, UniformType::Mat2x3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x4, UniformType::Mat2x4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x2, UniformType::Mat3x2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x2, UniformType::Mat4x2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x3, UniformType::Mat4x3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x4, UniformType::Mat3x4); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_RECT, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE, UniformType::Sampler); - } - - void uniformTypeFromGLType() - { - // GIVEN - QFETCH(int, glType); - QFETCH(UniformType, expected); - - // WHEN - UniformType computed = m_glHelper.uniformTypeFromGLType(glType); - - // THEN - QCOMPARE(computed, expected); - } - - void drawBuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.drawBuffer(GL_FRONT); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // THEN - GLint p; - m_func->glGetIntegerv(GL_DRAW_BUFFER, &p); - QCOMPARE(p, GL_FRONT); - } - - void readBuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.readBuffer(GL_FRONT); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_READ_BUFFER, &p); - QCOMPARE(p, GL_FRONT); - } - - void fenceSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - - // THEN - QVERIFY(sync != nullptr); - QCOMPARE(m_func->glIsSync(sync), GL_TRUE); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void clientWaitSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - QElapsedTimer t; - t.start(); - - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - - m_glHelper.clientWaitSync(sync, 1000000); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - qDebug() << t.nsecsElapsed(); - } - - void waitSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_func->glFlush(); - m_glHelper.waitSync(sync); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void wasSyncSignaled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_func->glFlush(); - m_glHelper.waitSync(sync); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // Shouldn't loop forever - while (!m_glHelper.wasSyncSignaled(sync)) - ; - } - - void deleteSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_glHelper.clientWaitSync(sync, GLuint64(-1)); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - QVERIFY(m_glHelper.wasSyncSignaled(sync) == true); - - // WHEN - m_glHelper.deleteSync(sync); - - // THEN - QCOMPARE(m_func->glIsSync(sync), GL_FALSE); - } - - void rasterMode() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 3.3 functions not supported"); - - m_func->glGetError(); - m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_POLYGON_MODE, &p); - QCOMPARE(p, GL_LINE); - } - -private: - QScopedPointer m_window; - QOpenGLContext m_glContext; - GraphicsHelperGL3_3 m_glHelper; - QOpenGLFunctions_3_3_Core *m_func = nullptr; - bool m_initializationSuccessful = false; -}; - -#endif - -int main(int argc, char *argv[]) -{ -#ifdef TEST_SHOULD_BE_PERFORMED - QGuiApplication app(argc, argv); - app.setAttribute(Qt::AA_Use96Dpi, true); - tst_GraphicsHelperGL3_3 tc; - QTEST_SET_MAIN_SOURCE_PATH - return QTest::qExec(&tc, argc, argv); -#endif - return 0; -} - -#ifdef TEST_SHOULD_BE_PERFORMED -#include "tst_graphicshelpergl3_3.moc" -#endif diff --git a/tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro b/tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro deleted file mode 100644 index b20d1afec..000000000 --- a/tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = app - -TARGET = tst_graphicshelpergl4 - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += \ - tst_graphicshelpergl4.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/graphicshelpergl4/tst_graphicshelpergl4.cpp b/tests/auto/render/graphicshelpergl4/tst_graphicshelpergl4.cpp deleted file mode 100644 index 6e5c54303..000000000 --- a/tests/auto/render/graphicshelpergl4/tst_graphicshelpergl4.cpp +++ /dev/null @@ -1,2583 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(QT_OPENGL_ES_2) && defined(QT_OPENGL_4_3) - -#define TEST_SHOULD_BE_PERFORMED 1 - -using namespace Qt3DRender; -using namespace Qt3DRender::Render; - -namespace { - -const QByteArray vertCode = QByteArrayLiteral( - "#version 430 core\n" \ - "layout(location = 1) in vec3 vertexPosition;\n" \ - "layout(location = 2) in vec2 vertexTexCoord;\n" \ - "out vec2 texCoord;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vertexTexCoord;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray vertCodeUniformBuffer = QByteArrayLiteral( - "#version 430 core\n" \ - "layout(location = 1) in vec3 vertexPosition;\n" \ - "layout(location = 2) in vec2 vertexTexCoord;\n" \ - "layout(location = 3) in int vertexColorIndex;\n" \ - "layout(location = 4) in double vertexTexCoordScale;\n" \ - "out vec2 texCoord;\n" \ - "flat out int colorIndex;\n" \ - "void main()\n" \ - "{\n" \ - " texCoord = vec2(vertexTexCoordScale * vertexTexCoord);\n" \ - " colorIndex = vertexColorIndex;\n" \ - " gl_Position = vec4(vertexPosition, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeFragOutputs = QByteArrayLiteral( - "#version 430 core\n" \ - "out vec4 color;\n" \ - "out vec2 temp;\n" \ - "void main()\n" \ - "{\n" \ - " color = vec4(1.0, 0.0, 0.0, 1.0);\n" \ - " temp = vec2(1.0, 0.3);\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( - "#version 430 core\n" \ - "out vec4 color;\n" \ - "layout(location = 1) uniform float multiplier;\n" \ - "layout(location = 2) uniform vec2 multiplierVec2;\n" \ - "layout(location = 3) uniform vec3 multiplierVec3;\n" \ - "layout(location = 4) uniform vec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ - " color = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsInt = QByteArrayLiteral( - "#version 430 core\n" \ - "out ivec4 color;\n" \ - "layout(location = 1) uniform int multiplier;\n" \ - "layout(location = 2) uniform ivec2 multiplierVec2;\n" \ - "layout(location = 3) uniform ivec3 multiplierVec3;\n" \ - "layout(location = 4) uniform ivec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ - " color = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsUInt = QByteArrayLiteral( - "#version 430 core\n" \ - "out uvec4 color;\n" \ - "layout(location = 1) uniform uint multiplier;\n" \ - "layout(location = 2) uniform uvec2 multiplierVec2;\n" \ - "layout(location = 3) uniform uvec3 multiplierVec3;\n" \ - "layout(location = 4) uniform uvec4 multiplierVec4;\n" \ - "void main()\n" \ - "{\n" \ - " uvec4 randomMult = multiplierVec4 + uvec4(multiplierVec3, 0) + uvec4(multiplierVec2, 0, 0);\n" \ - " color = uvec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ - "}\n"); - -const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( - "#version 430 core\n" \ - "out vec4 color;\n" \ - "layout(location = 1) uniform mat2 m2;\n" \ - "layout(location = 2) uniform mat2x3 m23;\n" \ - "layout(location = 3) uniform mat3x2 m32;\n" \ - "layout(location = 4) uniform mat2x4 m24;\n" \ - "layout(location = 5) uniform mat4x2 m42;\n" \ - "layout(location = 6) uniform mat3 m3;\n" \ - "layout(location = 7) uniform mat3x4 m34;\n" \ - "layout(location = 8) uniform mat4x3 m43;\n" \ - "layout(location = 9) uniform mat4 m4;\n" \ - "void main()\n" \ - "{\n" \ - " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ - " color = vec4(1, 0, 0, 1) * lengthSum;\n" \ - "}\n"); - -const QByteArray fragCodeUniformBuffer = QByteArrayLiteral( - "#version 430 core\n" \ - "out vec4 color;\n" \ - "in vec2 texCoord;\n" \ - "flat in int colorIndex;\n" \ - "layout(binding = 2, std140) uniform ColorArray\n" \ - "{\n" \ - " vec4 colors[256];\n" \ - "};\n" \ - "void main()\n" \ - "{\n" \ - " color = colors[colorIndex] + vec4(texCoord.s, texCoord.t, 0.0, 1.0);\n" \ - "}\n"); - -const QByteArray fragCodeSamplers = QByteArrayLiteral( - "#version 430 core\n" \ - "in vec2 texCoord;\n" \ - "out vec4 color;\n" \ - "layout(location = 1) uniform sampler1D s1;\n" \ - "layout(location = 2) uniform sampler2D s2;\n" \ - "layout(location = 3) uniform sampler2DArray s2a;\n" \ - "layout(location = 4) uniform sampler3D s3;\n" \ - "layout(location = 5) uniform samplerCube scube;\n" \ - "layout(location = 6) uniform sampler2DRect srect;\n" \ - "void main()\n" \ - "{\n" \ - " color = vec4(1, 0, 0, 1) *" \ - " texture(s1, texCoord.x) *" \ - " texture(s2, texCoord) *" \ - " texture(s2a, vec3(texCoord, 0.0)) *" \ - " texture(s3, vec3(texCoord, 0.0)) *" \ - " texture(scube, vec3(texCoord, 0)) *" \ - " texture(srect, texCoord);\n" \ - "}\n"); - -const QByteArray fragCodeImages = QByteArrayLiteral( - "#version 430 core\n" \ - "in vec2 texCoord;\n" \ - "out vec4 color;\n" \ - "layout(location = 1, rgba32f) readonly uniform image1D s1;\n" \ - "layout(location = 2, rg16f) readonly uniform image2D s2;\n" \ - "layout(location = 3, r16f) readonly uniform image2DArray s2a;\n" \ - "layout(location = 4, rg8) readonly uniform image3D s3;\n" \ - "layout(location = 5, rgba16_snorm) readonly uniform imageCube scube;\n" \ - "layout(location = 6, rg16) readonly uniform image2DRect srect;\n" \ - "void main()\n" \ - "{\n" \ - " ivec2 coords = ivec2(texCoord);\n"\ - " color = vec4(1, 0, 0, 1) *" \ - " imageLoad(s1, coords.x) *" \ - " imageLoad(s2, coords) *" \ - " imageLoad(s2a, ivec3(coords, 0)) *" \ - " imageLoad(s3, ivec3(coords, 0)) *" \ - " imageLoad(scube, ivec3(coords, 0)) *" \ - " imageLoad(srect, coords);\n" \ - "}\n"); - -const QByteArray computeShader = QByteArrayLiteral( - "#version 430 core\n" \ - "uniform float particleStep;\n" \ - "uniform float finalCollisionFactor;\n" \ - "layout (local_size_x = 1024) in;\n" \ - "struct ParticleData\n" \ - "{\n" \ - " vec4 position;\n" \ - " vec4 direction;\n" \ - " vec4 color;\n" \ - "};\n" \ - "layout (std140, binding = 6) coherent buffer Particles\n" \ - "{\n" \ - " ParticleData particles[];\n" \ - "} data;\n" \ - "void main(void)\n" \ - "{\n" \ - " uint globalId = gl_GlobalInvocationID.x;\n" \ - " ParticleData currentParticle = data.particles[globalId];\n" \ - " currentParticle.position = currentParticle.position + currentParticle.direction * particleStep;\n" \ - " vec4 acceleration = normalize(vec4(0.0) - currentParticle.position) * finalCollisionFactor;\n" \ - " currentParticle.direction = currentParticle.direction + acceleration * particleStep;\n" \ - " data.particles[globalId] = currentParticle;\n" \ - "}"); - -} // anonymous - -class tst_GraphicsHelperGL4 : public QObject -{ - Q_OBJECT -private Q_SLOTS: - void init() - { - m_window.reset(new QWindow); - m_window->setSurfaceType(QWindow::OpenGLSurface); - m_window->setGeometry(0, 0, 10, 10); - - QSurfaceFormat format; - format.setVersion(4, 3); - format.setProfile(QSurfaceFormat::CoreProfile); - format.setDepthBufferSize(24); - format.setSamples(4); - format.setStencilBufferSize(8); - m_window->setFormat(format); - m_glContext.setFormat(format); - - m_window->create(); - - if (!m_glContext.create()) { - qWarning() << "Failed to create OpenGL context"; - return; - } - - if (!m_glContext.makeCurrent(m_window.data())) { - qWarning() << "Failed to make OpenGL context current"; - return; - } - - if ((m_func = m_glContext.versionFunctions()) != nullptr) { - m_glHelper.initializeHelper(&m_glContext, m_func); - m_initializationSuccessful = true; - } - } - - void cleanup() - { - m_glContext.doneCurrent(); - } - - void alphaTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - // Deprecated - } - - void bindBufferBase() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint bufferId = 0; - // WHEN - m_func->glGenBuffers(1, &bufferId); - // THEN - QVERIFY(bufferId != 0); - - - // WHEN - m_func->glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferId); - m_glHelper.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, bufferId); - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundToPointBufferId = 0; - m_func->glGetIntegeri_v(GL_SHADER_STORAGE_BUFFER_BINDING, 2, &boundToPointBufferId); - QVERIFY(boundToPointBufferId == GLint(bufferId)); - - // Restore to sane state - m_func->glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); - m_func->glDeleteBuffers(1, &bufferId); - } - - void bindFragDataLocation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); - - // WHEN - QHash fragLocations; - fragLocations.insert(QStringLiteral("temp"), 2); - fragLocations.insert(QStringLiteral("color"), 1); - m_glHelper.bindFragDataLocation(shaderProgram.programId(), fragLocations); - - // THEN - QVERIFY(shaderProgram.link()); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - const GLint tempLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "temp"); - const GLint colorLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "color"); - QCOMPARE(tempLocation, 2); - QCOMPARE(colorLocation, 1); - } - - void bindFrameBufferAttachment() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - { - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color2; - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA32F); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture.create()) - qWarning() << "Texture creation failed"; - texture.allocateStorage(); - QVERIFY(texture.isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureAttachmentId = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0 + 2, - GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, - &textureAttachmentId); - QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - { - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::TargetCubeMap); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA32F); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture.create()) - qWarning() << "Texture creation failed"; - texture.allocateStorage(); - QVERIFY(texture.isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - { // Check All Faces - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - attachment.m_face = Qt3DRender::QAbstractTexture::AllFaces; - - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureIsLayered = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_LAYERED, - &textureIsLayered); - QCOMPARE(textureIsLayered, GL_TRUE); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - { // Check Specific Faces - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color0; - attachment.m_face = Qt3DRender::QAbstractTexture::CubeMapNegativeZ; - - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - error = m_func->glGetError(); - QVERIFY(error == 0); - GLint textureFace = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, - &textureFace); - QCOMPARE(textureFace, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); - GLint textureIsLayered = 0; - m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_FRAMEBUFFER_ATTACHMENT_LAYERED, - &textureIsLayered); - QCOMPARE(textureIsLayered, GL_FALSE); - - // Restore state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - } - } - - void bindFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); - - // THEN - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint boundindFBOId = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // WHEN - m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); - - // THEN - error = m_func->glGetError(); - QVERIFY(error == 0); - boundindFBOId = 0; - m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); - QVERIFY(GLuint(boundindFBOId) == fboId); - - // Cleanup - m_func->glDeleteFramebuffers(1, &fboId); - } - - void bindImageTexture() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - - // THEN - QVERIFY(texture.textureId() != 0 && texture.isCreated() && texture.isStorageAllocated()); - - // WHEN - m_glHelper.bindImageTexture(0, - texture.textureId(), - 0, - GL_FALSE, - 0, - GL_READ_WRITE, - GL_RGBA8UI); - - // THEN - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void bindShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Compute, computeShader); - QVERIFY(shaderProgram.link()); - - // WHEN - GLint index = m_func->glGetProgramResourceIndex(shaderProgram.programId(), - GL_SHADER_STORAGE_BLOCK, - "Particles"); - // THEN - GLint binding = -1; - GLenum prop = GL_BUFFER_BINDING; - m_func->glGetProgramResourceiv(shaderProgram.programId(), - GL_SHADER_STORAGE_BLOCK, - index, - 1, &prop, - 4, NULL, &binding); - QCOMPARE(binding, 6); - - // WHEN - m_glHelper.bindShaderStorageBlock(shaderProgram.programId(), index, 1); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - m_func->glGetProgramResourceiv(shaderProgram.programId(), - GL_SHADER_STORAGE_BLOCK, - index, - 1, &prop, - 4, NULL, &binding); - QCOMPARE(binding, 1); - } - - void bindUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - // WHEN - GLint index = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); - m_glHelper.bindUniformBlock(shaderProgram.programId(), index, 1); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void blendEquation() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLint equation = 0; - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_ADD); - - // WHEN - m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); - - // THEN - m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); - QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); - } - - void blendFunci() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLint destinationRgb = 0; - GLint destinationAlpha = 0; - GLint sourceRgb = 0; - GLint sourceAlpha = 0; - m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 4, &sourceRgb); - m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 4, &destinationRgb); - m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 4, &sourceAlpha); - m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 4, &destinationAlpha); - - // THEN - QCOMPARE(destinationAlpha, GL_ZERO); - QCOMPARE(destinationRgb, GL_ZERO); - QCOMPARE(sourceRgb, GL_ONE); - QCOMPARE(sourceAlpha, GL_ONE); - - // WHEN - m_glHelper.blendFunci(4, GL_SRC_COLOR, GL_ONE_MINUS_SRC_ALPHA); - - m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 4, &sourceRgb); - m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 4, &destinationRgb); - m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 4, &sourceAlpha); - m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 4, &destinationAlpha); - - // THEN - QCOMPARE(destinationAlpha, GL_ONE_MINUS_SRC_ALPHA); - QCOMPARE(destinationRgb, GL_ONE_MINUS_SRC_ALPHA); - QCOMPARE(sourceRgb, GL_SRC_COLOR); - QCOMPARE(sourceAlpha, GL_SRC_COLOR); - - // Reset default - m_glHelper.blendFunci(4, GL_ONE, GL_ZERO); - } - - void blendFuncSeparatei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLint destinationRgb = 0; - GLint destinationAlpha = 0; - GLint sourceRgb = 0; - GLint sourceAlpha = 0; - m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 2, &sourceRgb); - m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 2, &destinationRgb); - m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 2, &sourceAlpha); - m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 2, &destinationAlpha); - - // THEN - QCOMPARE(destinationAlpha, GL_ZERO); - QCOMPARE(destinationRgb, GL_ZERO); - QCOMPARE(sourceRgb, GL_ONE); - QCOMPARE(sourceAlpha, GL_ONE); - - // WHEN - m_glHelper.blendFuncSeparatei(2, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 2, &sourceRgb); - m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 2, &destinationRgb); - m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 2, &sourceAlpha); - m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 2, &destinationAlpha); - - // THEN - QCOMPARE(destinationAlpha, GL_ONE_MINUS_SRC_ALPHA); - QCOMPARE(destinationRgb, GL_ONE_MINUS_SRC_COLOR); - QCOMPARE(sourceRgb, GL_SRC_COLOR); - QCOMPARE(sourceAlpha, GL_SRC_ALPHA); - - // Reset default - m_glHelper.blendFunci(4, GL_ONE, GL_ZERO); - } - - void boundFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - // THEN - GLint boundBuffer = 0; - m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); - QCOMPARE(GLuint(boundBuffer), fboId); - - // THEN - QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); - - // Reset state - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void checkFrameBufferComplete() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - Attachment attachment; - attachment.m_point = QRenderTargetOutput::Color1; - - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - m_glHelper.bindFrameBufferAttachment(&texture, attachment); - - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - QVERIFY(m_glHelper.checkFrameBufferComplete()); - - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - } - - void clearBufferf() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - // Create 4 attachments - QOpenGLTexture *textures[4]; - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // Set Draw buffers - GLenum clearBufferEnum = GL_COLOR_ATTACHMENT3; - m_func->glDrawBuffers(1, &clearBufferEnum); - - const GLint bufferIndex = 0; // index of the element in the draw buffers - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // WHEN - const QVector4D clearValue1 = QVector4D(0.5f, 0.2f, 0.4f, 0.8f); - m_func->glClearBufferfv(GL_COLOR, bufferIndex, reinterpret_cast(&clearValue1)); - error = m_func->glGetError(); - QVERIFY(error == 0); - - // THEN - QVector colors(512 * 512); - textures[3]->bind(); - m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); - textures[3]->release(); - - for (const QVector4D c : colors) { - QVERIFY(c == clearValue1); - } - - // WHEN - const QVector4D clearValue2 = QVector4D(0.4f, 0.5f, 0.4f, 1.0f); - m_glHelper.clearBufferf(bufferIndex, clearValue2); - - // THEN - textures[3]->bind(); - m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); - textures[3]->release(); - for (const QVector4D c : colors) { - QVERIFY(c == clearValue2); - } - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void createFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // WHEN - const GLuint fboId = m_glHelper.createFrameBufferObject(); - - // THEN - QVERIFY(fboId != 0); - - // Restore - m_func->glDeleteFramebuffers(1, &fboId); - } - - void depthMask() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLboolean depthWritingEnabled = false; - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - - // THEN - QVERIFY(depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_FALSE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(!depthWritingEnabled); - - // WHEN - m_glHelper.depthMask(GL_TRUE); - - // THEN - m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); - QVERIFY(depthWritingEnabled); - } - - void depthTest() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_DEPTH_TEST); - m_func->glDepthFunc(GL_LESS); - - // WHEN - m_glHelper.depthTest(GL_LEQUAL); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - GLint depthMode = 0; - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LEQUAL); - - // WHEN - m_glHelper.depthTest(GL_LESS); - QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); - m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); - QCOMPARE(depthMode, GL_LESS); - } - - void disableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_CLIP_DISTANCE0 + 5); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - - // WHEN - m_glHelper.disableClipPlane(5); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); - } - - void disablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glEnablei(GL_BLEND, 2); - - // THEN - QVERIFY(m_func->glIsEnabledi(GL_BLEND, 2)); - - // WHEN - m_glHelper.disablei(GL_BLEND, 2); - - // THEN - QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 2)); - } - - void disablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_PRIMITIVE_RESTART); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - - // WHEN - m_glHelper.disablePrimitiveRestart(); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - } - - void drawBuffers() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); - QOpenGLTexture *textures[4]; - - // Create 4 attachments - for (int i = 0; i < 4; ++i) { - Attachment attachment; - attachment.m_point = static_cast(i); - - QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); - textures[i] = texture; - texture->setSize(512, 512); - texture->setFormat(QOpenGLTexture::RGBA32F); - texture->setMinificationFilter(QOpenGLTexture::Linear); - texture->setMagnificationFilter(QOpenGLTexture::Linear); - texture->setWrapMode(QOpenGLTexture::ClampToEdge); - if (!texture->create()) - qWarning() << "Texture creation failed"; - texture->allocateStorage(); - QVERIFY(texture->isStorageAllocated()); - GLint error = m_func->glGetError(); - QVERIFY(error == 0); - m_glHelper.bindFrameBufferAttachment(texture, attachment); - } - // THEN - GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - // WHEN - GLenum bufferEnum = GL_COLOR_ATTACHMENT4; - m_func->glDrawBuffers(1, &bufferEnum); - - // THEN - GLint enumValue = -1; - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); - - // WHEN - GLint newBufferEnum = 2; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // WHEN - newBufferEnum = 0; - m_glHelper.drawBuffers(1, &newBufferEnum); - - // THEN - m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); - QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); - - // Restore - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glDeleteFramebuffers(1, &fboId); - for (int i = 0; i < 4; ++i) - delete textures[i]; - } - - void enableClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_CLIP_DISTANCE0 + 4); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - - // WHEN - m_glHelper.enableClipPlane(4); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); - } - - void enablei() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisablei(GL_BLEND, 4); - - // THEN - QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 4)); - - // WHEN - m_glHelper.enablei(GL_BLEND, 4); - - // THEN - QVERIFY(m_func->glIsEnabledi(GL_BLEND, 4)); - } - - void enablePrimitiveRestart() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_PRIMITIVE_RESTART); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - - // WHEN - m_glHelper.enablePrimitiveRestart(883); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); - GLint restartIndex = 0; - m_func->glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX, &restartIndex); - QCOMPARE(restartIndex, 883); - - // Restore - m_func->glDisable(GL_PRIMITIVE_RESTART); - } - - void enableVertexAttribute() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - shaderProgram.bind(); - - // WHEN - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void frontFace() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glFrontFace(GL_CW); - - // THEN - GLint face = 0; - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CW); - - // WHEN - m_glHelper.frontFace(GL_CCW); - - // THEN - m_func->glGetIntegerv(GL_FRONT_FACE, &face); - QCOMPARE(face, GL_CCW); - } - - void getRenderBufferDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint renderBufferId = 0; - m_func->glGenRenderbuffers(1, &renderBufferId); - QVERIFY(renderBufferId != 0); - - // WHEN - m_func->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); - m_func->glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, 512, 512); - m_func->glBindRenderbuffer(GL_RENDERBUFFER, 0); - const QSize dimensions = m_glHelper.getRenderBufferDimensions(renderBufferId); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - - // Restore - m_func->glDeleteRenderbuffers(1, &renderBufferId); - } - - void getTextureDimensions() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLTexture texture(QOpenGLTexture::Target2D); - texture.setSize(512, 512); - texture.setFormat(QOpenGLTexture::RGBA8U); - texture.setMinificationFilter(QOpenGLTexture::Linear); - texture.setMagnificationFilter(QOpenGLTexture::Linear); - texture.create(); - texture.allocateStorage(); - - // WHEN - const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); - - // THEN - QCOMPARE(dimensions, QSize(512, 512)); - } - - void pointSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glEnable(GL_PROGRAM_POINT_SIZE); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); - GLfloat size = 0; - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 1.0f); - - // WHEN - m_glHelper.pointSize(false, 0.5f); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); - m_func->glGetFloatv(GL_POINT_SIZE, &size); - QCOMPARE(size, 0.5f); - } - - void maxClipPlaneCount() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLint maxCount = -1; - m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); - - // THEN - QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); - } - - void programUniformBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - // WHEN - const QVector activeUniformBlocks = m_glHelper.programUniformBlocks(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniformBlocks.size(), 1); - const ShaderUniformBlock uniformBlock = activeUniformBlocks.first(); - - QCOMPARE(uniformBlock.m_activeUniformsCount, 1); - QCOMPARE(uniformBlock.m_name, QStringLiteral("ColorArray")); - QCOMPARE(uniformBlock.m_binding, 2); - } - - void programAttributesAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeAttributes.size(), 2); - std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_location < b.m_location; }); - - const ShaderAttribute attribute1 = activeAttributes.at(0); - QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); - QCOMPARE(attribute1.m_size, 1); - QCOMPARE(attribute1.m_location, 1); - QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); - - const ShaderAttribute attribute2 = activeAttributes.at(1); - QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); - QCOMPARE(attribute2.m_size, 1); - QCOMPARE(attribute2.m_location, 2); - QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); - } - - void programUniformsAndLocations() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - - // THEN - QCOMPARE(activeUniforms.size(), 4); - std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_location < b.m_location; }); - - const ShaderUniform uniform1 = activeUniforms.at(0); - QCOMPARE(uniform1.m_location, 1); - QCOMPARE(uniform1.m_offset, -1); - QCOMPARE(uniform1.m_blockIndex, -1); - QCOMPARE(uniform1.m_arrayStride, -1); - QCOMPARE(uniform1.m_matrixStride, -1); - QCOMPARE(uniform1.m_size, 1); - QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); - QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); - - const ShaderUniform uniform2 = activeUniforms.at(1); - QCOMPARE(uniform2.m_location, 2); - QCOMPARE(uniform2.m_offset, -1); - QCOMPARE(uniform2.m_blockIndex, -1); - QCOMPARE(uniform2.m_arrayStride, -1); - QCOMPARE(uniform2.m_matrixStride, -1); - QCOMPARE(uniform2.m_size, 1); - QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); - QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); - - const ShaderUniform uniform3 = activeUniforms.at(2); - QCOMPARE(uniform3.m_location, 3); - QCOMPARE(uniform3.m_offset, -1); - QCOMPARE(uniform3.m_blockIndex, -1); - QCOMPARE(uniform3.m_arrayStride, -1); - QCOMPARE(uniform3.m_matrixStride, -1); - QCOMPARE(uniform3.m_size, 1); - QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); - QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); - - const ShaderUniform uniform4 = activeUniforms.at(3); - QCOMPARE(uniform4.m_location, 4); - QCOMPARE(uniform4.m_offset, -1); - QCOMPARE(uniform4.m_blockIndex, -1); - QCOMPARE(uniform4.m_arrayStride, -1); - QCOMPARE(uniform4.m_matrixStride, -1); - QCOMPARE(uniform4.m_size, 1); - QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); - QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); - } - - void programShaderStorageBlock() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Compute, computeShader); - QVERIFY(shaderProgram.link()); - - // WHEN - const QVector activeShaderStorageBlocks = m_glHelper.programShaderStorageBlocks(shaderProgram.programId()); - - // THEN - QVERIFY(activeShaderStorageBlocks.size() == 1); - ShaderStorageBlock block = activeShaderStorageBlocks.first(); - QCOMPARE(block.m_name, QStringLiteral("Particles")); - QCOMPARE(block.m_activeVariablesCount, 3); - QCOMPARE(block.m_index, 0); - QCOMPARE(block.m_binding, 6); - QCOMPARE(block.m_size, (4 + 4 + 4) * 4); - } - - void releaseFrameBufferObject() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint fboId; - m_func->glGenFramebuffers(1, &fboId); - - // THEN - QVERIFY(fboId != 0); - - // WHEN - m_glHelper.releaseFrameBufferObject(fboId); - - // THEN - QVERIFY(!m_func->glIsFramebuffer(fboId)); - } - - void setMSAAEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_MULTISAMPLE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); - - // WHEN - m_glHelper.setMSAAEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); - } - - void setAlphaCoverageEnabled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - - // WHEN - m_glHelper.setAlphaCoverageEnabled(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); - } - - void setClipPlane() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - // Deprecated in GL 4 - } - - void setSeamlessCubemap() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - } - - void setVerticesPerPatch() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(true); - - // THEN - QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - - // WHEN - m_glHelper.setSeamlessCubemap(false); - - // THEN - QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - } - - void supportsFeature() - { - for (int i = 0; i <= GraphicsHelperInterface::Fences; ++i) - QVERIFY(m_glHelper.supportsFeature(static_cast(i))); - } - - -#define ADD_UNIFORM_ENTRY(FragShader, Type, Location, ComponentSize, ExpectedRawSize) \ - QTest::newRow(#FragShader"_"#Type) << FragShader << Type << Location << ComponentSize << ExpectedRawSize; - - void uniformsByteSize_data() - { - QTest::addColumn("fragShader"); - QTest::addColumn("type"); - QTest::addColumn("location"); - QTest::addColumn("componentSize"); - QTest::addColumn("expectedByteSize"); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT, 1, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT_VEC2, 2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT_VEC3, 3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT_VEC4, 4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT, 1, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT_VEC2, 2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT_VEC3, 3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT_VEC4, 4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT, 1, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT_VEC2, 2, 1, 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT_VEC3, 3, 1, 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT_VEC4, 4, 1, 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT2, 1, 1, 4 * 2 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT2x3, 2, 1, 4 * 2 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT3x2, 3, 1, 4 * 3 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT2x4, 4, 1, 4 * 2 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT4x2, 5, 1, 4 * 4 * 2); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT3, 6, 1, 4 * 3 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT3x4, 7, 1, 4 * 3 * 4); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT4x3, 8, 1, 4 * 4 * 3); - ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT4, 9, 1, 4 * 4 * 4); - - ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_1D, 1, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_2D, 2, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_2D_ARRAY, 3, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_3D, 4, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_CUBE, 5, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_2D_RECT, 6, 1, 4); - - ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_1D, 1, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_2D, 2, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_2D_ARRAY, 3, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_3D, 4, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_CUBE, 5, 1, 4); - ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_2D_RECT, 6, 1, 4); - } - - void uniformsByteSize() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QFETCH(QByteArray, fragShader); - QFETCH(int, type); - QFETCH(int, location); - QFETCH(int, componentSize); - QFETCH(int, expectedByteSize); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); - QVERIFY(shaderProgram.link()); - - // WHEN - const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); - ShaderUniform matchingUniform; - for (const ShaderUniform &u : activeUniforms) { - if (u.m_location == location) { - matchingUniform = u; - break; - } - } - - // THEN - QCOMPARE(matchingUniform.m_location, location); - QCOMPARE(matchingUniform.m_type, GLuint(type)); - QCOMPARE(matchingUniform.m_size, componentSize); - - // WHEN - const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); - - // THEN - QCOMPARE(expectedByteSize, computedRawByteSize); - - // Restore - m_func->glUseProgram(0); - } - - void useProgram() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); - - // THEN - QVERIFY(shaderProgram.link()); - - GLint currentProg = 0; - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - - // WHEN - m_glHelper.useProgram(shaderProgram.programId()); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QCOMPARE(GLuint(currentProg), shaderProgram.programId()); - - // WHEN - m_glHelper.useProgram(0); - - // THEN - m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); - QVERIFY(currentProg == 0); - } - - void vertexAttribDivisor() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - } - - void vertexAttributePointer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLVertexArrayObject vao; - vao.create(); - QOpenGLVertexArrayObject::Binder binder(&vao); - - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); - QVERIFY(shaderProgram.link()); - - GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); - GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); - GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); - GLint texCoordScaleLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoordScale"); - - const int vertexCount = 99; - QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); - positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - positionBuffer.create(); - positionBuffer.bind(); - positionBuffer.allocate(vertexCount * sizeof(QVector3D)); - - QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); - texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - texCoordBuffer.create(); - texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); - - QOpenGLBuffer colorIndexBuffer(QOpenGLBuffer::VertexBuffer); - colorIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - colorIndexBuffer.create(); - colorIndexBuffer.allocate(vertexCount * sizeof(int)); - - QOpenGLBuffer scaleBuffer(QOpenGLBuffer::VertexBuffer); - scaleBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); - scaleBuffer.create(); - scaleBuffer.allocate(vertexCount * sizeof(double)); - - // WHEN - shaderProgram.bind(); - positionBuffer.bind(); - m_glHelper.enableVertexAttributeArray(positionLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); - - texCoordBuffer.bind(); - m_glHelper.enableVertexAttributeArray(texCoordLocation); - m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); - - colorIndexBuffer.bind(); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - m_glHelper.vertexAttributePointer(GL_INT, colorIndexLocation, 1, GL_INT, GL_TRUE, 0, 0); - - scaleBuffer.bind(); - m_glHelper.enableVertexAttributeArray(colorIndexLocation); - m_glHelper.vertexAttributePointer(GL_DOUBLE, texCoordScaleLocation, 1, GL_DOUBLE, GL_TRUE, 0, 0); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void glUniform1fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat value = 883.0f; - m_glHelper.glUniform1fv(1, 1, &value); - - // THEN - GLfloat setValue = 0.0f; - m_func->glGetUniformfv(shaderProgram.programId(), 1, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[2] = { 383.0f, 427.0f }; - m_glHelper.glUniform2fv(2, 1, values); - - // THEN - GLfloat setValues[2] = { 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 2, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; - m_glHelper.glUniform3fv(3, 1, values); - - // THEN - GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 3, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - m_glHelper.glUniform4fv(4, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 4, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(setValues[i], values[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint value = 883; - m_glHelper.glUniform1iv(1, 1, &value); - - // THEN - GLint setValue = 0; - m_func->glGetUniformiv(shaderProgram.programId(), 1, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[2] = { 383, 427 }; - m_glHelper.glUniform2iv(2, 1, values); - - // THEN - GLint setValues[2] = { 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), 2, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[3] = { 572, 1340, 1584 }; - m_glHelper.glUniform3iv(3, 1, values); - - // THEN - GLint setValues[3] = { 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), 3, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4iv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLint values[4] = { 454, 350, 883, 355 }; - m_glHelper.glUniform4iv(4, 1, values); - - // THEN - GLint setValues[4] = { 0, 0, 0, 0 }; - m_func->glGetUniformiv(shaderProgram.programId(), 4, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform1uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint value = 883U; - m_glHelper.glUniform1uiv(1, 1, &value); - - // THEN - GLuint setValue = 0U; - m_func->glGetUniformuiv(shaderProgram.programId(), 1, &setValue); - QCOMPARE(value, setValue); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform2uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[2] = { 383U, 427U }; - m_glHelper.glUniform2uiv(2, 1, values); - - // THEN - GLuint setValues[2] = { 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), 2, setValues); - for (int i = 0; i < 2; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform3uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[3] = { 572U, 1340U, 1584U }; - m_glHelper.glUniform3uiv(3, 1, values); - - // THEN - GLuint setValues[3] = { 0U, 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), 3, setValues); - for (int i = 0; i < 3; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniform4uiv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLuint values[4] = { 454U, 350U, 883U, 355U }; - m_glHelper.glUniform4uiv(4, 1, values); - - // THEN - GLuint setValues[4] = { 0U, 0U, 0U, 0U }; - m_func->glGetUniformuiv(shaderProgram.programId(), 4, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; - m_glHelper.glUniformMatrix2fv(1, 1, values); - - // THEN - GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 1, setValues); - for (int i = 0; i < 4; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; - m_glHelper.glUniformMatrix3fv(6, 1, values); - - // THEN - GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 6, setValues); - for (int i = 0; i < 9; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; - m_glHelper.glUniformMatrix4fv(9, 1, values); - - // THEN - GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 9, setValues); - for (int i = 0; i < 16; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - m_glHelper.glUniformMatrix2x3fv(2, 1, values); - - // THEN - GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 2, setValues); - for (int i = 0; i < 6; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - m_glHelper.glUniformMatrix3x2fv(3, 1, values); - - // THEN - GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 3, setValues); - for (int i = 0; i < 6; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix2x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - m_glHelper.glUniformMatrix2x4fv(4, 1, values); - - // THEN - GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 4, setValues); - for (int i = 0; i < 8; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4x2fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - m_glHelper.glUniformMatrix4x2fv(5, 1, values); - - // THEN - GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 5, setValues); - for (int i = 0; i < 8; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix3x4fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f,}; - m_glHelper.glUniformMatrix3x4fv(7, 1, values); - - // THEN - GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 7, setValues); - for (int i = 0; i < 12; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - void glUniformMatrix4x3fv() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - QOpenGLShaderProgram shaderProgram; - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); - shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); - QVERIFY(shaderProgram.link()); - - // WHEN - m_func->glUseProgram(shaderProgram.programId()); - GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; - m_glHelper.glUniformMatrix4x3fv(8, 1, values); - - // THEN - GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - m_func->glGetUniformfv(shaderProgram.programId(), 8, setValues); - for (int i = 0; i < 12; ++i) - QCOMPARE(values[i], setValues[i]); - - // Restore - m_func->glUseProgram(0); - } - - - void blitFramebuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - // GIVEN - GLuint fbos[2]; - GLuint fboTextures[2]; - - m_func->glGenFramebuffers(2, fbos); - m_func->glGenTextures(2, fboTextures); - - m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fboTextures[0]); - m_func->glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA8, 10, 10, true); - m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); - - m_func->glBindTexture(GL_TEXTURE_2D, fboTextures[1]); - m_func->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 10, 10, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); - m_func->glBindTexture(GL_TEXTURE_2D, 0); - - m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[1]); - m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[1], 0); - - GLenum status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[0]); - m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[0], 0); - - status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); - QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); - - m_func->glEnable(GL_MULTISAMPLE); - m_func->glClearColor(0.2f, 0.2f, 0.2f, 0.2f); - m_func->glClear(GL_COLOR_BUFFER_BIT); - m_func->glDisable(GL_MULTISAMPLE); - - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); - - // WHEN - m_glHelper.blitFramebuffer(0,0,10,10,0,0,10,10, GL_COLOR_BUFFER_BIT, GL_NEAREST); - - m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[1]); - - GLuint result[10*10]; - m_func->glReadPixels(0,0,10,10,GL_RGBA, GL_UNSIGNED_BYTE, result); - - // THEN - GLuint v = (0.2f) * 255; - v = v | (v<<8) | (v<<16) | (v<<24); - for (GLuint value : result) { - QCOMPARE(value, v); - } - m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); - - m_func->glDeleteFramebuffers(2, fbos); - m_func->glDeleteTextures(2, fboTextures); - } - -#define ADD_GL_TYPE_ENTRY(Type, Expected) \ - QTest::newRow(#Type) << Type << Expected; - - void uniformTypeFromGLType_data() - { - QTest::addColumn("glType"); - QTest::addColumn("expected"); - - ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); - ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); - ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); - ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); - ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT, UniformType::UInt); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC2, UniformType::UIVec2); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC3, UniformType::UIVec3); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC4, UniformType::UIVec4); - ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); - ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x3, UniformType::Mat2x3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x4, UniformType::Mat2x4); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x2, UniformType::Mat3x2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x2, UniformType::Mat4x2); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x3, UniformType::Mat4x3); - ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x4, UniformType::Mat3x4); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_RECT, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_MAP_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE_MAP_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_1D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_3D, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_BUFFER, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY, UniformType::Sampler); - ADD_GL_TYPE_ENTRY(GL_IMAGE_1D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_2D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_3D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_RECT, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_CUBE, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_BUFFER, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_1D_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_CUBE_MAP_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_MULTISAMPLE, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_MULTISAMPLE_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_1D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D, UniformType::Image); ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_3D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_RECT, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_CUBE, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_BUFFER, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_1D_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_CUBE_MAP_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_MULTISAMPLE, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_1D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_3D, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_RECT, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_CUBE, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_BUFFER, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_1D_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE, UniformType::Image); - ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY, UniformType::Image); - } - - void uniformTypeFromGLType() - { - // GIVEN - QFETCH(int, glType); - QFETCH(UniformType, expected); - - // WHEN - UniformType computed = m_glHelper.uniformTypeFromGLType(glType); - - // THEN - QCOMPARE(computed, expected); - } - - void drawBuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.drawBuffer(GL_FRONT); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // THEN - GLint p; - m_func->glGetIntegerv(GL_DRAW_BUFFER, &p); - QCOMPARE(p, GL_FRONT); - } - - void readBuffer() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - m_glHelper.readBuffer(GL_FRONT); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_READ_BUFFER, &p); - QCOMPARE(p, GL_FRONT); - } - - void fenceSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - - // THEN - QVERIFY(sync != nullptr); - QCOMPARE(m_func->glIsSync(sync), GL_TRUE); - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void clientWaitSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - QElapsedTimer t; - t.start(); - - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - - m_glHelper.clientWaitSync(sync, 1000000); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - qDebug() << t.nsecsElapsed(); - } - - void waitSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_func->glFlush(); - m_glHelper.waitSync(sync); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - } - - void wasSyncSignaled() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_func->glFlush(); - m_glHelper.waitSync(sync); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - - // Shouldn't loop forever - while (!m_glHelper.wasSyncSignaled(sync)) - ; - } - - void deleteSync() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); - - m_func->glGetError(); - - // WHEN - GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); - m_glHelper.clientWaitSync(sync, GLuint64(-1)); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - QVERIFY(m_glHelper.wasSyncSignaled(sync) == true); - - // WHEN - m_glHelper.deleteSync(sync); - - // THEN - QCOMPARE(m_func->glIsSync(sync), GL_FALSE); - } - - void rasterMode() - { - if (!m_initializationSuccessful) - QSKIP("Initialization failed, OpenGL 4.3 functions not supported"); - - m_func->glGetError(); - m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); - - // THEN - const GLint error = m_func->glGetError(); - QVERIFY(error == 0); - GLint p; - m_func->glGetIntegerv(GL_POLYGON_MODE, &p); - QCOMPARE(p, GL_LINE); - } - -private: - QScopedPointer m_window; - QOpenGLContext m_glContext; - GraphicsHelperGL4 m_glHelper; - QOpenGLFunctions_4_3_Core *m_func = nullptr; - bool m_initializationSuccessful = false; -}; - -#endif - -int main(int argc, char *argv[]) -{ -#ifdef TEST_SHOULD_BE_PERFORMED - QGuiApplication app(argc, argv); - app.setAttribute(Qt::AA_Use96Dpi, true); - tst_GraphicsHelperGL4 tc; - QTEST_SET_MAIN_SOURCE_PATH - return QTest::qExec(&tc, argc, argv); -#endif - return 0; -} - -#ifdef TEST_SHOULD_BE_PERFORMED -#include "tst_graphicshelpergl4.moc" -#endif diff --git a/tests/auto/render/layerfiltering/tst_layerfiltering.cpp b/tests/auto/render/layerfiltering/tst_layerfiltering.cpp index 255ff5ea8..1ffec30ae 100644 --- a/tests/auto/render/layerfiltering/tst_layerfiltering.cpp +++ b/tests/auto/render/layerfiltering/tst_layerfiltering.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include diff --git a/tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro b/tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro deleted file mode 100644 index ac68b8248..000000000 --- a/tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app - -TARGET = tst_materialparametergathererjob - -QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_materialparametergathererjob.cpp - -include(../commons/commons.pri) diff --git a/tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp b/tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp deleted file mode 100644 index 236faa8f0..000000000 --- a/tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp +++ /dev/null @@ -1,799 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -class TestAspect : public Qt3DRender::QRenderAspect -{ -public: - TestAspect(Qt3DCore::QNode *root) - : Qt3DRender::QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) - , m_jobManager(new Qt3DCore::QAspectJobManager()) - { - Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); - QRenderAspect::onRegistered(); - - QVector nodes; - Qt3DCore::QNodeVisitor v; - v.traverse(root, [&nodes](Qt3DCore::QNode *node) { - Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(node); - d->m_typeInfo = const_cast(Qt3DCore::QNodePrivate::findStaticMetaObject(node->metaObject())); - d->m_hasBackendNode = true; - nodes << node; - }); - - for (const auto node: nodes) - d_func()->createBackendNode({ - node->id(), - Qt3DCore::QNodePrivate::get(node)->m_typeInfo, - Qt3DCore::NodeTreeChange::Added, - node - }); - - const auto handles = nodeManagers()->techniqueManager()->activeHandles(); - for (const auto &handle: handles) { - Render::Technique *technique = nodeManagers()->techniqueManager()->data(handle); - technique->setCompatibleWithRenderer(true); - } - } - - ~TestAspect() - { - QRenderAspect::onUnregistered(); - } - - Qt3DRender::Render::NodeManagers *nodeManagers() const - { - return d_func()->m_renderer->nodeManagers(); - } - - void initializeRenderer() - { - d_func()->m_renderer->initialize(); - } - - Render::MaterialParameterGathererJobPtr materialGathererJob() const - { - Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); - job->setNodeManagers(nodeManagers()); - return job; - } - - void onRegistered() { QRenderAspect::onRegistered(); } - void onUnregistered() { QRenderAspect::onUnregistered(); } - -private: - QScopedPointer m_jobManager; -}; - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -namespace { - -class TestMaterial : public Qt3DRender::QMaterial -{ - Q_OBJECT -public: - explicit TestMaterial(Qt3DCore::QNode *parent = nullptr) - : Qt3DRender::QMaterial(parent) - , m_effect(new Qt3DRender::QEffect()) - , m_gl3Technique(new Qt3DRender::QTechnique()) - , m_gl2Technique(new Qt3DRender::QTechnique()) - , m_es2Technique(new Qt3DRender::QTechnique()) - , m_gl3Pass(new Qt3DRender::QRenderPass()) - , m_gl2Pass(new Qt3DRender::QRenderPass()) - , m_es2Pass(new Qt3DRender::QRenderPass()) - , m_gl3Program(new Qt3DRender::QShaderProgram()) - , m_gl2es2Program(new Qt3DRender::QShaderProgram()) - { - m_gl3Pass->setShaderProgram(m_gl3Program); - m_gl2Pass->setShaderProgram(m_gl2es2Program); - m_es2Pass->setShaderProgram(m_gl2es2Program); - - m_gl3Technique->addRenderPass(m_gl3Pass); - m_gl2Technique->addRenderPass(m_gl2Pass); - m_es2Technique->addRenderPass(m_es2Pass); - - m_effect->addTechnique(m_gl3Technique); - m_effect->addTechnique(m_gl2Technique); - m_effect->addTechnique(m_es2Technique); - - setEffect(m_effect); - } - - Qt3DRender::QTechnique *gl3Technique() const { return m_gl3Technique; } - Qt3DRender::QTechnique *gl2Technique() const { return m_gl2Technique; } - Qt3DRender::QTechnique *es2Technique() const { return m_es2Technique; } - - Qt3DRender::QRenderPass *gl3Pass() const { return m_gl3Pass; } - Qt3DRender::QRenderPass *gl2Pass() const { return m_gl2Pass; } - Qt3DRender::QRenderPass *es2Pass() const { return m_es2Pass; } - - Qt3DRender::QShaderProgram *gl3Shader() const { return m_gl3Program; } - Qt3DRender::QShaderProgram *gl2shader() const { return m_gl2es2Program; } - Qt3DRender::QShaderProgram *es2Shader() const { return m_gl2es2Program; } - -private: - Qt3DRender::QEffect *m_effect; - Qt3DRender::QTechnique *m_gl3Technique; - Qt3DRender::QTechnique *m_gl2Technique; - Qt3DRender::QTechnique *m_es2Technique; - Qt3DRender::QRenderPass *m_gl3Pass; - Qt3DRender::QRenderPass *m_gl2Pass; - Qt3DRender::QRenderPass *m_es2Pass; - Qt3DRender::QShaderProgram *m_gl3Program; - Qt3DRender::QShaderProgram *m_gl2es2Program; -}; - -Qt3DRender::QViewport *viewportFrameGraph() -{ - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - return viewport; -} - -Qt3DRender::QTechniqueFilter *techniqueFilterFrameGraph() -{ - Qt3DRender::QTechniqueFilter *techniqueFilter = new Qt3DRender::QTechniqueFilter(); - return techniqueFilter; -} - -Qt3DRender::QRenderPassFilter *renderPassFilter() -{ - Qt3DRender::QRenderPassFilter *passFilter = new Qt3DRender::QRenderPassFilter(); - return passFilter; -} - -Qt3DCore::QEntity *buildScene(Qt3DRender::QFrameGraphNode *frameGraph, Qt3DRender::QMaterial *material = nullptr) -{ - Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); - - // FrameGraph - Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); - renderSettings->setActiveFrameGraph(frameGraph); - root->addComponent(renderSettings); - - // Scene - for (int i = 0; i < 10; i++) { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - if (material != nullptr) - e->addComponent(material); - e->setParent(root); - } - - return root; -} - -} // anonymous - -class tst_MaterialParameterGatherer : public QObject -{ - Q_OBJECT -private Q_SLOTS: - - void checkRunNoHandlesNoTechniqueFilterNoPassFilter() - { - // GIVEN - Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph()); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 0); - - // WHEN - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); - } - - void checkRunSelectAllNoTechniqueFilterNoPassFilter() - { - // GIVEN - TestMaterial material; - Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph(), &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - } - - void checkRunDisabledMaterial() - { - // GIVEN - TestMaterial material; - material.setEnabled(false); - Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph(), &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); - } - - void checkRunSelectAllTechniqueFilterWithNoFilterNoPassFilter() - { - // GIVEN - Qt3DRender::QTechniqueFilter *frameGraphFilter = techniqueFilterFrameGraph(); - - TestMaterial material; - - Qt3DRender::QFilterKey techniqueFilterKey; - techniqueFilterKey.setName(QStringLiteral("renderingStyle")); - techniqueFilterKey.setValue(QVariant(QStringLiteral("backward"))); - - material.gl2Technique()->addFilterKey(&techniqueFilterKey); - material.gl3Technique()->addFilterKey(&techniqueFilterKey); - material.es2Technique()->addFilterKey(&techniqueFilterKey); - - Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); - QVERIFY(backendTechniqueFilter != nullptr); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - } - - void checkRunSelectAllTechniqueFilterWithIncompatibleFilterNoPassFilter() - { - // GIVEN - Qt3DRender::QTechniqueFilter *frameGraphFilter = techniqueFilterFrameGraph(); - TestMaterial material; - - Qt3DRender::QFilterKey techniqueFilterFilterKey; - techniqueFilterFilterKey.setName(QStringLiteral("renderingStyle")); - techniqueFilterFilterKey.setValue(QVariant(QStringLiteral("forward"))); - - Qt3DRender::QFilterKey techniqueFilterKey; - techniqueFilterKey.setName(QStringLiteral("renderingStyle")); - techniqueFilterKey.setValue(QVariant(QStringLiteral("backward"))); - - frameGraphFilter->addMatch(&techniqueFilterFilterKey); - - material.gl2Technique()->addFilterKey(&techniqueFilterKey); - material.gl3Technique()->addFilterKey(&techniqueFilterKey); - material.es2Technique()->addFilterKey(&techniqueFilterKey); - - Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); - QVERIFY(backendTechniqueFilter != nullptr); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); - } - - void checkRunSelectAllTechniqueFilterWithCompatibleFilterNoPassFilter() - { - // GIVEN - Qt3DRender::QTechniqueFilter *frameGraphFilter = techniqueFilterFrameGraph(); - TestMaterial material; - - Qt3DRender::QFilterKey techniqueFilterKey; - techniqueFilterKey.setName(QStringLiteral("renderingStyle")); - techniqueFilterKey.setValue(QVariant(QStringLiteral("backward"))); - - frameGraphFilter->addMatch(&techniqueFilterKey); - - material.gl2Technique()->addFilterKey(&techniqueFilterKey); - material.gl3Technique()->addFilterKey(&techniqueFilterKey); - material.es2Technique()->addFilterKey(&techniqueFilterKey); - - Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); - QVERIFY(backendTechniqueFilter != nullptr); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - } - - void checkRunSelectAllNoTechniqueFilterPassFilterWithNoFilter() - { - // GIVEN - Qt3DRender::QRenderPassFilter *frameGraphFilter = renderPassFilter(); - TestMaterial material; - - Qt3DRender::QFilterKey passFilterKey; - passFilterKey.setName(QStringLiteral("renderingStyle")); - passFilterKey.setValue(QVariant(QStringLiteral("backward"))); - - material.gl3Pass()->addFilterKey(&passFilterKey); - material.gl2Pass()->addFilterKey(&passFilterKey); - material.es2Pass()->addFilterKey(&passFilterKey); - - Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::RenderPassFilter *backendPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); - QVERIFY(backendPassFilter != nullptr); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendPassFilter); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - } - - void checkRunSelectAllNoTechniqueFilterPassFilterWithIncompatibleFilter() - { - // GIVEN - Qt3DRender::QRenderPassFilter *frameGraphFilter = renderPassFilter(); - TestMaterial material; - - Qt3DRender::QFilterKey passFilterFilterKey; - passFilterFilterKey.setName(QStringLiteral("renderingStyle")); - passFilterFilterKey.setValue(QVariant(QStringLiteral("forward"))); - - Qt3DRender::QFilterKey passFilterKey; - passFilterKey.setName(QStringLiteral("renderingStyle")); - passFilterKey.setValue(QVariant(QStringLiteral("backward"))); - - frameGraphFilter->addMatch(&passFilterFilterKey); - - material.gl3Pass()->addFilterKey(&passFilterKey); - material.gl2Pass()->addFilterKey(&passFilterKey); - material.es2Pass()->addFilterKey(&passFilterKey); - - Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - - testAspect.initializeRenderer(); - - // THEN - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::RenderPassFilter *backendPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); - QVERIFY(backendPassFilter != nullptr); - - // WHEN - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendPassFilter); - gatherer->run(); - - // THEN - QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); - } - - void checkParameterPriorityGathering() - { - { - // GIVEN - Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); - Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); - - renderPassFG->setParent(techniqueFilterFG); - - TestMaterial material; - - Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); - - // WHEN - techniqueFilterFG->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::red)))); - - auto renderPassParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); - - renderPassFG->addParameter(renderPassParameter); - material.addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::green)))); - material.effect()->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::blue)))); - - auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); - - material.gl3Technique()->addParameter(techniqueParam); - material.gl2Technique()->addParameter(techniqueParam); - material.es2Technique()->addParameter(techniqueParam); - - auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); - - material.gl3Pass()->addParameter(passParam); - material.gl2Pass()->addParameter(passParam); - material.es2Pass()->addParameter(passParam); - - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - testAspect.initializeRenderer(); - - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); - Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); - QVERIFY(backendTechniqueFilter != nullptr); - QVERIFY(backendRenderPassFilter != nullptr); - - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendRenderPassFilter); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN -> RenderPassFilter wins - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); - QCOMPARE(passParameterData.size(), 1); - - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); - - QCOMPARE(data.parameterInfo.size(), 1); - QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(renderPassParameter->id())); - } - { - // GIVEN - Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); - Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); - - renderPassFG->setParent(techniqueFilterFG); - - TestMaterial material; - - Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); - - // WHEN - auto techniqueFilterParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); - techniqueFilterFG->addParameter(techniqueFilterParameter); - - material.addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::green)))); - material.effect()->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::blue)))); - - auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); - - material.gl3Technique()->addParameter(techniqueParam); - material.gl2Technique()->addParameter(techniqueParam); - material.es2Technique()->addParameter(techniqueParam); - - auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); - - material.gl3Pass()->addParameter(passParam); - material.gl2Pass()->addParameter(passParam); - material.es2Pass()->addParameter(passParam); - - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - testAspect.initializeRenderer(); - - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); - Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); - QVERIFY(backendTechniqueFilter != nullptr); - QVERIFY(backendRenderPassFilter != nullptr); - - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendRenderPassFilter); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN -> TechniqueFilter wins - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); - QCOMPARE(passParameterData.size(), 1); - - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); - - QCOMPARE(data.parameterInfo.size(), 1); - QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(techniqueFilterParameter->id())); - } - { - // GIVEN - Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); - Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); - - renderPassFG->setParent(techniqueFilterFG); - - TestMaterial material; - - Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); - - // WHEN - auto materialParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); - - material.addParameter(materialParameter); - material.effect()->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::blue)))); - - auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); - - material.gl3Technique()->addParameter(techniqueParam); - material.gl2Technique()->addParameter(techniqueParam); - material.es2Technique()->addParameter(techniqueParam); - - auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); - - material.gl3Pass()->addParameter(passParam); - material.gl2Pass()->addParameter(passParam); - material.es2Pass()->addParameter(passParam); - - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - testAspect.initializeRenderer(); - - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); - Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); - QVERIFY(backendTechniqueFilter != nullptr); - QVERIFY(backendRenderPassFilter != nullptr); - - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendRenderPassFilter); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN -> TechniqueFilter wins - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); - QCOMPARE(passParameterData.size(), 1); - - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); - - QCOMPARE(data.parameterInfo.size(), 1); - QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(materialParameter->id())); - } - { - // GIVEN - Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); - Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); - - renderPassFG->setParent(techniqueFilterFG); - - TestMaterial material; - - Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); - - // WHEN - auto effectParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); - - material.effect()->addParameter(effectParameter); - - auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); - - material.gl3Technique()->addParameter(techniqueParam); - material.gl2Technique()->addParameter(techniqueParam); - material.es2Technique()->addParameter(techniqueParam); - - auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); - - material.gl3Pass()->addParameter(passParam); - material.gl2Pass()->addParameter(passParam); - material.es2Pass()->addParameter(passParam); - - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - testAspect.initializeRenderer(); - - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); - Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); - QVERIFY(backendTechniqueFilter != nullptr); - QVERIFY(backendRenderPassFilter != nullptr); - - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendRenderPassFilter); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN -> TechniqueFilter wins - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); - QCOMPARE(passParameterData.size(), 1); - - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); - - QCOMPARE(data.parameterInfo.size(), 1); - QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(effectParameter->id())); - } - { - // GIVEN - Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); - Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); - - renderPassFG->setParent(techniqueFilterFG); - - TestMaterial material; - - Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); - - // WHEN - auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); - - material.gl3Technique()->addParameter(techniqueParam); - material.gl2Technique()->addParameter(techniqueParam); - material.es2Technique()->addParameter(techniqueParam); - - auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); - - material.gl3Pass()->addParameter(passParam); - material.gl2Pass()->addParameter(passParam); - material.es2Pass()->addParameter(passParam); - - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - testAspect.initializeRenderer(); - - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); - Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); - QVERIFY(backendTechniqueFilter != nullptr); - QVERIFY(backendRenderPassFilter != nullptr); - - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendRenderPassFilter); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN -> TechniqueFilter wins - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); - QCOMPARE(passParameterData.size(), 1); - - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); - - QCOMPARE(data.parameterInfo.size(), 1); - QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(techniqueParam->id())); - } - { - // GIVEN - Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); - Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); - - renderPassFG->setParent(techniqueFilterFG); - - TestMaterial material; - - Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); - - // WHEN - auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); - - material.gl3Pass()->addParameter(passParam); - material.gl2Pass()->addParameter(passParam); - material.es2Pass()->addParameter(passParam); - - Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); - testAspect.initializeRenderer(); - - QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); - Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); - Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); - QVERIFY(backendTechniqueFilter != nullptr); - QVERIFY(backendRenderPassFilter != nullptr); - - gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); - gatherer->setRenderPassFilter(backendRenderPassFilter); - gatherer->setTechniqueFilter(backendTechniqueFilter); - gatherer->run(); - - // THEN -> TechniqueFilter wins - QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); - QCOMPARE(passParameterData.size(), 1); - - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); - - QCOMPARE(data.parameterInfo.size(), 1); - QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(passParam->id())); - } - } -}; - -QTEST_MAIN(tst_MaterialParameterGatherer) - -#include "tst_materialparametergathererjob.moc" diff --git a/tests/auto/render/opengl/computecommand/computecommand.pro b/tests/auto/render/opengl/computecommand/computecommand.pro new file mode 100644 index 000000000..38515059a --- /dev/null +++ b/tests/auto/render/opengl/computecommand/computecommand.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_computecommand + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_computecommand.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/computecommand/tst_computecommand.cpp b/tests/auto/render/opengl/computecommand/tst_computecommand.cpp new file mode 100644 index 000000000..80cbfb090 --- /dev/null +++ b/tests/auto/render/opengl/computecommand/tst_computecommand.cpp @@ -0,0 +1,143 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "qbackendnodetester.h" +#include "testrenderer.h" +#include "testpostmanarbiter.h" + + +// tst_Renderer is a friend class of Renderer +class tst_Renderer : public Qt3DRender::Render::Renderer +{ +public: + tst_Renderer() + : Qt3DRender::Render::Renderer(Qt3DRender::QRenderAspect::Synchronous) + {} + + ~tst_Renderer() { + shutdown(); + } +}; + + +class tst_ComputeCommand : public Qt3DCore::QBackendNodeTester +{ + Q_OBJECT + +private Q_SLOTS: + + void checkDisablesFrontend() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManager; + tst_Renderer renderer; + TestArbiter arbiter; + + Qt3DCore::QAspectManager manager; + Qt3DCore::QScene scene; + + Qt3DCore::QEntity rootEntity; + Qt3DCore::QNodePrivate::get(&rootEntity)->setScene(&scene); + + Qt3DRender::QComputeCommand computeCommand; + Qt3DRender::Render::ComputeCommand *backendComputeCommand = nullptr; + + renderer.setNodeManagers(&nodeManager); + + // WHEN + computeCommand.setParent(&rootEntity); + // RootEntity is the entry point to retrieve the scene instance for lookups + manager.setRootEntity(&rootEntity, {}); + + // THEN + QVERIFY(scene.lookupNode(computeCommand.id()) != nullptr); + + // WHEN + auto handle = nodeManager.computeJobManager()->getOrAcquireHandle(computeCommand.id()); + backendComputeCommand = nodeManager.computeJobManager()->data(handle); + + // WHEN + computeCommand.setWorkGroupX(256); + computeCommand.setWorkGroupY(512); + computeCommand.setWorkGroupZ(128); + computeCommand.setRunType(Qt3DRender::QComputeCommand::Manual); + computeCommand.trigger(1); + + Qt3DCore::QBackendNodePrivate::get(backendComputeCommand)->setArbiter(&arbiter); + backendComputeCommand->setRenderer(&renderer); + simulateInitializationSync(&computeCommand, backendComputeCommand); + + // THEN + QCOMPARE(backendComputeCommand->frameCount(),1); + QCOMPARE(backendComputeCommand->isEnabled(), true); + QCOMPARE(computeCommand.isEnabled(), true); + QCOMPARE(backendComputeCommand->hasReachedFrameCount(), false); + + // WHEN + backendComputeCommand->updateFrameCount(); + + // THEN + QCOMPARE(backendComputeCommand->frameCount(), 0); + QCOMPARE(backendComputeCommand->hasReachedFrameCount(), true); + + + // Still enabled as we have yet to notify the fronted + QCOMPARE(backendComputeCommand->isEnabled(), true); + QCOMPARE(computeCommand.isEnabled(), true); + + // WHEN + renderer.jobsDone(&manager); // so Renderer::sendDisablesToFrontend gets called + + // THEN + QCOMPARE(computeCommand.isEnabled(), false); + QCOMPARE(backendComputeCommand->hasReachedFrameCount(), false); + + // WHEN + backendComputeCommand->syncFromFrontEnd(&computeCommand, false); + + // THEN + QCOMPARE(backendComputeCommand->frameCount(), 0); + QCOMPARE(backendComputeCommand->isEnabled(), false); + } +}; + +QTEST_MAIN(tst_ComputeCommand) + +#include "tst_computecommand.moc" diff --git a/tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST b/tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST new file mode 100644 index 000000000..7cbc7c4c0 --- /dev/null +++ b/tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST @@ -0,0 +1,6 @@ +#[checkRunRendererRunning] +windows-7 +windows-7sp1 +#QTBUG-64271 +# Offscreen platform does not support OpenGL context creation +b2qt diff --git a/tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro b/tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro new file mode 100644 index 000000000..5d533839c --- /dev/null +++ b/tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_filtercompatibletechniquejob + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_filtercompatibletechniquejob.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp b/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp new file mode 100644 index 000000000..8b9390340 --- /dev/null +++ b/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp @@ -0,0 +1,263 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class TestAspect : public Qt3DRender::QRenderAspect +{ +public: + TestAspect(Qt3DCore::QNode *root) + : Qt3DRender::QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) + , m_jobManager(new Qt3DCore::QAspectJobManager()) + , m_window(new QWindow()) + , m_contextCreationSuccessful(false) + { + m_window->setSurfaceType(QWindow::OpenGLSurface); + m_window->setGeometry(0, 0, 10, 10); + m_window->create(); + + if (!m_glContext.create()) { + qWarning() << "Failed to create OpenGL context"; + return; + } + + if (!m_glContext.makeCurrent(m_window.data())) { + qWarning() << "Failed to make OpenGL context current"; + return; + } + + m_contextCreationSuccessful = true; + + Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); + QRenderAspect::onRegistered(); + + QVector nodes; + Qt3DCore::QNodeVisitor v; + v.traverse(root, [&nodes](Qt3DCore::QNode *node) { + Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(node); + d->m_typeInfo = const_cast(Qt3DCore::QNodePrivate::findStaticMetaObject(node->metaObject())); + d->m_hasBackendNode = true; + nodes << node; + }); + + for (const auto node: nodes) + d_func()->createBackendNode({ + node->id(), + Qt3DCore::QNodePrivate::get(node)->m_typeInfo, + Qt3DCore::NodeTreeChange::Added, + node + }); + } + + ~TestAspect() + { + if (m_contextCreationSuccessful) + QRenderAspect::onUnregistered(); + } + + Qt3DRender::Render::NodeManagers *nodeManagers() const + { + return d_func()->m_renderer + ? d_func()->m_renderer->nodeManagers() : nullptr; + } + + bool contextCreationSuccessful() const + { + return m_contextCreationSuccessful; + } + + void initializeRenderer() + { + renderer()->setOpenGLContext(&m_glContext); + d_func()->m_renderer->initialize(); + renderer()->submissionContext()->beginDrawing(m_window.data()); + } + + Render::Renderer *renderer() const + { + return static_cast(d_func()->m_renderer); + } + + void onRegistered() { QRenderAspect::onRegistered(); } + void onUnregistered() { QRenderAspect::onUnregistered(); } + +private: + QScopedPointer m_jobManager; + QScopedPointer m_window; + QOpenGLContext m_glContext; + bool m_contextCreationSuccessful; +}; + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +namespace { + +Qt3DCore::QEntity *buildTestScene() +{ + Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); + + // FrameGraph + Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); + renderSettings->setActiveFrameGraph(new Qt3DRender::QViewport()); + root->addComponent(renderSettings); + + // Scene + Qt3DRender::QTechnique *gl2Technique = new Qt3DRender::QTechnique(root); + gl2Technique->graphicsApiFilter()->setApi(Qt3DRender::QGraphicsApiFilter::OpenGL); + gl2Technique->graphicsApiFilter()->setMajorVersion(2); + gl2Technique->graphicsApiFilter()->setMinorVersion(0); + gl2Technique->graphicsApiFilter()->setProfile(Qt3DRender::QGraphicsApiFilter::NoProfile); + + Qt3DRender::QTechnique *gl3Technique = new Qt3DRender::QTechnique(root); + gl3Technique->graphicsApiFilter()->setApi(Qt3DRender::QGraphicsApiFilter::OpenGL); + gl3Technique->graphicsApiFilter()->setMajorVersion(3); + gl3Technique->graphicsApiFilter()->setMinorVersion(2); + gl3Technique->graphicsApiFilter()->setProfile(Qt3DRender::QGraphicsApiFilter::CoreProfile); + + Qt3DRender::QTechnique *es2Technique = new Qt3DRender::QTechnique(root); + es2Technique->graphicsApiFilter()->setApi(Qt3DRender::QGraphicsApiFilter::OpenGLES); + es2Technique->graphicsApiFilter()->setMajorVersion(2); + es2Technique->graphicsApiFilter()->setMinorVersion(0); + es2Technique->graphicsApiFilter()->setProfile(Qt3DRender::QGraphicsApiFilter::NoProfile); + + return root; +} + +} // anonymous + +class tst_FilterCompatibleTechniqueJob : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + + void initTestCase() + { + QSurfaceFormat format; +#ifdef QT_OPENGL_ES_2 + format.setRenderableType(QSurfaceFormat::OpenGLES); +#else + if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL) { + format.setVersion(4, 3); + format.setProfile(QSurfaceFormat::CoreProfile); + } +#endif + format.setDepthBufferSize(24); + format.setSamples(4); + format.setStencilBufferSize(8); + QSurfaceFormat::setDefaultFormat(format); + } + + void checkInitialState() + { + // GIVEN + Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; + + // THEN + QVERIFY(backendFilterCompatibleTechniqueJob.manager() == nullptr); + QVERIFY(backendFilterCompatibleTechniqueJob.renderer() == nullptr); + + // WHEN + Qt3DRender::Render::TechniqueManager techniqueManager; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + backendFilterCompatibleTechniqueJob.setManager(&techniqueManager); + backendFilterCompatibleTechniqueJob.setRenderer(&renderer); + + // THEN + QCOMPARE(backendFilterCompatibleTechniqueJob.manager(), &techniqueManager); + QCOMPARE(backendFilterCompatibleTechniqueJob.renderer(), &renderer); + + renderer.shutdown(); + } + + void checkRunRendererRunning() + { + // GIVEN + Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; + Qt3DRender::TestAspect testAspect(buildTestScene()); + + const bool unableToCreateContext = !testAspect.contextCreationSuccessful(); + + if (unableToCreateContext) + QSKIP("Initialization failed, unable to create GL context"); + + // WHEN + Qt3DRender::Render::NodeManagers *nodeManagers = testAspect.nodeManagers(); + QVERIFY(nodeManagers); + Qt3DRender::Render::TechniqueManager *techniqueManager = nodeManagers->techniqueManager(); + QVERIFY(techniqueManager); + backendFilterCompatibleTechniqueJob.setManager(techniqueManager); + backendFilterCompatibleTechniqueJob.setRenderer(testAspect.renderer()); + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.renderer()->isRunning(), true); + QCOMPARE(testAspect.renderer()->submissionContext()->isInitialized(), true); + const QVector handles = testAspect.nodeManagers()->techniqueManager()->activeHandles(); + QCOMPARE(handles.size(), 3); + + // WHEN + backendFilterCompatibleTechniqueJob.run(); + + // THEN -> empty if job ran properly + const QVector dirtyTechniquesId = testAspect.nodeManagers()->techniqueManager()->takeDirtyTechniques(); + QCOMPARE(dirtyTechniquesId.size(), 0); + + // Check at least one technique is valid + bool foundValid = false; + for (const auto handle: handles) { + Qt3DRender::Render::Technique *technique = testAspect.nodeManagers()->techniqueManager()->data(handle); + foundValid |= technique->isCompatibleWithRenderer(); + } + QCOMPARE(foundValid, true); + } +}; + +QTEST_MAIN(tst_FilterCompatibleTechniqueJob) + +#include "tst_filtercompatibletechniquejob.moc" diff --git a/tests/auto/render/opengl/glshadermanager/glshadermanager.pro b/tests/auto/render/opengl/glshadermanager/glshadermanager.pro new file mode 100644 index 000000000..dc96ab3bb --- /dev/null +++ b/tests/auto/render/opengl/glshadermanager/glshadermanager.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_glshadermanager + +QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_glshadermanager.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp b/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp new file mode 100644 index 000000000..83420af3b --- /dev/null +++ b/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp @@ -0,0 +1,199 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include "qbackendnodetester.h" +#include "testrenderer.h" + +class tst_GLShaderManager : public Qt3DCore::QBackendNodeTester +{ + Q_OBJECT + +private Q_SLOTS: + void adopt(); + void lookupResource(); + void abandon(); + void insertAfterRemoval(); +}; + +void tst_GLShaderManager::adopt() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader1; + Qt3DRender::QShaderProgram frontendShader2; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode1; + Qt3DRender::Render::Shader backendShaderNode2; + + backendShaderNode1.setRenderer(&renderer); + backendShaderNode2.setRenderer(&renderer); + simulateInitialization(&frontendShader1, &backendShaderNode1); + simulateInitialization(&frontendShader2, &backendShaderNode2); + + // THEN + QVERIFY(cache.lookupResource(backendShaderNode1.peerId()) == nullptr); + QVERIFY(cache.lookupResource(backendShaderNode2.peerId()) == nullptr); + QVERIFY(backendShaderNode1.peerId() != backendShaderNode2.peerId()); + + // WHEN + Qt3DRender::Render::GLShader *glShader1 = cache.createOrAdoptExisting(&backendShaderNode1); + + // THEN + QVERIFY(glShader1 != nullptr); + QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); + QCOMPARE(shaderNodeIds.size(), 1); + QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); + + // WHEN + Qt3DRender::Render::GLShader *glShader2 = cache.createOrAdoptExisting(&backendShaderNode2); + + // THEN + QCOMPARE(glShader1, glShader2); + + shaderNodeIds = cache.shaderIdsForProgram(glShader2); + QCOMPARE(shaderNodeIds.size(), 2); + QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); + QCOMPARE(shaderNodeIds.last(), backendShaderNode2.peerId()); +} + +void tst_GLShaderManager::lookupResource() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader1; + Qt3DRender::QShaderProgram frontendShader2; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode1; + Qt3DRender::Render::Shader backendShaderNode2; + + backendShaderNode1.setRenderer(&renderer); + backendShaderNode2.setRenderer(&renderer); + simulateInitialization(&frontendShader1, &backendShaderNode1); + simulateInitialization(&frontendShader2, &backendShaderNode2); + + // WHEN + cache.createOrAdoptExisting(&backendShaderNode1); + cache.createOrAdoptExisting(&backendShaderNode2); + + // THEN + Qt3DRender::Render::GLShader *glShader1 = cache.lookupResource(backendShaderNode1.peerId()); + Qt3DRender::Render::GLShader *glShader2 = cache.lookupResource(backendShaderNode2.peerId()); + QVERIFY(glShader1 != nullptr); + QCOMPARE(glShader1, glShader2); + const QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); + QCOMPARE(shaderNodeIds.size(), 2); + QVERIFY(shaderNodeIds.contains(frontendShader1.id())); + QVERIFY(shaderNodeIds.contains(frontendShader2.id())); +} + +void tst_GLShaderManager::abandon() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader1; + Qt3DRender::QShaderProgram frontendShader2; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode1; + Qt3DRender::Render::Shader backendShaderNode2; + + backendShaderNode1.setRenderer(&renderer); + backendShaderNode2.setRenderer(&renderer); + simulateInitialization(&frontendShader1, &backendShaderNode1); + simulateInitialization(&frontendShader2, &backendShaderNode2); + cache.createOrAdoptExisting(&backendShaderNode1); + cache.createOrAdoptExisting(&backendShaderNode2); + + // WHEN + Qt3DRender::Render::GLShader *glShader = cache.lookupResource(backendShaderNode1.peerId()); + cache.abandon(glShader, &backendShaderNode1); + + // THEN + QVector shaderNodeIds = cache.shaderIdsForProgram(glShader); + QVERIFY(cache.takeAbandonned().isEmpty()); + QCOMPARE(shaderNodeIds.size(), 1); + QCOMPARE(shaderNodeIds.first(), backendShaderNode2.peerId()); + + // WHEN + cache.abandon(glShader, &backendShaderNode2); + + // THEN + shaderNodeIds = cache.shaderIdsForProgram(glShader); + QCOMPARE(shaderNodeIds.size(), 0); + const QVector releasedShaders = cache.takeAbandonned(); + QCOMPARE(releasedShaders.size(), 1); + QCOMPARE(releasedShaders.first(), glShader); +} + +void tst_GLShaderManager::insertAfterRemoval() +{ + // GIVEN + Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::QShaderProgram frontendShader; + TestRenderer renderer; + Qt3DRender::Render::Shader backendShaderNode; + + + backendShaderNode.setRenderer(&renderer); + simulateInitialization(&frontendShader, &backendShaderNode); + + // WHEN + Qt3DRender::Render::GLShader *apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); + const Qt3DRender::Render::GLShader *originalApiShader = apiShader1; + + // THEN + auto apiShader2 = cache.lookupResource(frontendShader.id()); + QVERIFY(apiShader1 != nullptr); + QVERIFY(apiShader2 != nullptr); + QVERIFY(apiShader1 == originalApiShader); + QVERIFY(apiShader1 == apiShader2); + + // WHEN + cache.abandon(apiShader1, &backendShaderNode); + + // THEN + Qt3DRender::Render::GLShader *apiShaderEmpty = cache.lookupResource(frontendShader.id()); + QVERIFY(apiShaderEmpty == nullptr); + + // WHEN + apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); + cache.purge(); + apiShader2 = cache.lookupResource(frontendShader.id()); + + // THEN + QVERIFY(apiShader1 != nullptr); + QVERIFY(apiShader2 != nullptr); + QVERIFY(apiShader1 == apiShader2); + QVERIFY(apiShader2 == originalApiShader); +} + +QTEST_APPLESS_MAIN(tst_GLShaderManager) + +#include "tst_glshadermanager.moc" diff --git a/tests/auto/render/opengl/graphicshelpergl2/graphicshelpergl2.pro b/tests/auto/render/opengl/graphicshelpergl2/graphicshelpergl2.pro new file mode 100644 index 000000000..eb8ba7f04 --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl2/graphicshelpergl2.pro @@ -0,0 +1,16 @@ +TEMPLATE = app + +TARGET = tst_graphicshelpergl2 + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib openglextensions + +CONFIG += testcase + +SOURCES += \ + tst_graphicshelpergl2.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp b/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp new file mode 100644 index 000000000..0a43a3040 --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp @@ -0,0 +1,1605 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef QT_OPENGL_ES_2 + +#define TEST_SHOULD_BE_PERFORMED 1 + +QT_BEGIN_NAMESPACE + +using namespace Qt3DRender; +using namespace Qt3DRender::Render; + +namespace { + +const QByteArray vertCode = QByteArrayLiteral( + "#version 120\n" \ + "attribute vec3 vertexPosition;\n" \ + "attribute vec2 vertexTexCoord;\n" \ + "varying vec2 texCoord;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vertexTexCoord;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( + "#version 120\n" \ + "uniform float multiplier;\n" \ + "uniform vec2 multiplierVec2;\n" \ + "uniform vec3 multiplierVec3;\n" \ + "uniform vec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ + " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsInt = QByteArrayLiteral( + "#version 120\n" \ + "uniform int multiplier;\n" \ + "uniform ivec2 multiplierVec2;\n" \ + "uniform ivec3 multiplierVec3;\n" \ + "uniform ivec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ + " gl_FragColor = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( + "#version 120\n" \ + "uniform mat2 m2;\n" \ + "uniform mat2x3 m23;\n" \ + "uniform mat3x2 m32;\n" \ + "uniform mat2x4 m24;\n" \ + "uniform mat4x2 m42;\n" \ + "uniform mat3 m3;\n" \ + "uniform mat3x4 m34;\n" \ + "uniform mat4x3 m43;\n" \ + "uniform mat4 m4;\n" \ + "void main()\n" \ + "{\n" \ + " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ + " gl_FragColor = vec4(1, 0, 0, 1) * lengthSum;\n" \ + "}\n"); + + +const QByteArray fragCodeSamplers = QByteArrayLiteral( + "#version 120\n" \ + "varying vec2 texCoord;\n" \ + "uniform sampler1D s1;\n" \ + "uniform sampler2D s2;\n" \ + "uniform sampler3D s3;\n" \ + "uniform samplerCube scube;\n" \ + "void main()\n" \ + "{\n" \ + " gl_FragColor = vec4(1, 0, 0, 1) *" \ + " texture1D(s1, texCoord.x) *" \ + " texture2D(s2, texCoord) *" \ + " texture3D(s3, vec3(texCoord, 0.0)) *" \ + " textureCube(scube, vec3(texCoord, 0));\n" \ + "}\n"); + +} // anonymous + +class tst_GraphicsHelperGL2 : public QObject +{ + Q_OBJECT +private Q_SLOTS: + + void init() + { + m_window.reset(new QWindow); + m_window->setSurfaceType(QWindow::OpenGLSurface); + m_window->setGeometry(0, 0, 10, 10); + m_window->create(); + + QSurfaceFormat format; + format.setVersion(2, 0); + format.setProfile(QSurfaceFormat::NoProfile); + format.setDepthBufferSize(24); + format.setSamples(4); + format.setStencilBufferSize(8); + m_window->setFormat(format); + m_glContext.setFormat(format); + + if (!m_glContext.create()) { + qWarning() << "Failed to create OpenGL context"; + return; + } + + if (!m_glContext.makeCurrent(m_window.data())) { + qWarning() << "Failed to make OpenGL context current"; + return; + } + + if ((m_func = m_glContext.versionFunctions()) != nullptr) { + if (m_glContext.hasExtension(QByteArrayLiteral("GL_ARB_framebuffer_object"))) { + m_fboFuncs = new QOpenGLExtension_ARB_framebuffer_object(); + m_fboFuncs->initializeOpenGLFunctions(); + } + m_glHelper.initializeHelper(&m_glContext, m_func); + m_initializationSuccessful = true; + } + } + + void cleanup() + { + m_glContext.doneCurrent(); + } + + void alphaTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Deprecated + } + + void bindBufferBase() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // Not supported by GL2 + } + + void bindFragDataLocation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void bindFrameBufferAttachment() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + + // GIVEN + GLuint fboId; + m_fboFuncs->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA32F); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture.create()) + qWarning() << "Texture creation failed"; + texture.allocateStorage(); + QVERIFY(texture.isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_fboFuncs->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureAttachmentId = 0; + m_fboFuncs->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, + &textureAttachmentId); + QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); + + // Restore state + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_fboFuncs->glDeleteFramebuffers(1, &fboId); + } + + void bindFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + + // GIVEN + GLuint fboId; + m_fboFuncs->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); + + // THEN + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundindFBOId = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // Cleanup + m_fboFuncs->glDeleteFramebuffers(1, &fboId); + } + + void bindShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void bindUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void blendEquation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + GLint equation = 0; + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_ADD); + + // WHEN + m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); + + // THEN + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); + } + + void blendFunci() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void blendFuncSeparatei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void boundFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + + // GIVEN + GLuint fboId; + m_fboFuncs->glGenFramebuffers(1, &fboId); + + // WHEN + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + // THEN + GLint boundBuffer = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); + QCOMPARE(GLuint(boundBuffer), fboId); + + // THEN + QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); + + // Reset state + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_fboFuncs->glDeleteFramebuffers(1, &fboId); + } + + void checkFrameBufferComplete() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + + // GIVEN + GLuint fboId; + m_fboFuncs->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_fboFuncs->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + QVERIFY(m_glHelper.checkFrameBufferComplete()); + + // Restore + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_fboFuncs->glDeleteFramebuffers(1, &fboId); + } + + void clearBufferf() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void createFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + + // WHEN + const GLuint fboId = m_glHelper.createFrameBufferObject(); + + // THEN + QVERIFY(fboId != 0); + + // Restore + m_fboFuncs->glDeleteFramebuffers(1, &fboId); + } + + void depthMask() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + GLboolean depthWritingEnabled = false; + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + + // THEN + QVERIFY(depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_FALSE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(!depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_TRUE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(depthWritingEnabled); + } + + void depthTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + m_func->glDisable(GL_DEPTH_TEST); + m_func->glDepthFunc(GL_LESS); + + // WHEN + m_glHelper.depthTest(GL_LEQUAL); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + GLint depthMode = 0; + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LEQUAL); + + // WHEN + m_glHelper.depthTest(GL_LESS); + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LESS); + } + + void disableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + m_func->glEnable(GL_CLIP_DISTANCE0 + 5); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + + // WHEN + m_glHelper.disableClipPlane(5); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + } + + void disablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void disablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void drawBuffers() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + + // GIVEN + GLuint fboId; + m_fboFuncs->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + QOpenGLTexture *textures[4]; + + // Create 4 attachments + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + // THEN + GLenum status = m_fboFuncs->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // WHEN + GLenum bufferEnum = GL_COLOR_ATTACHMENT4; + m_func->glDrawBuffers(1, &bufferEnum); + + // THEN + GLint enumValue = -1; + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); + + // WHEN + GLint newBufferEnum = 2; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // WHEN + newBufferEnum = 0; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // Restore + m_fboFuncs->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_fboFuncs->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void enableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + m_func->glDisable(GL_CLIP_DISTANCE0 + 4); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + + // WHEN + m_glHelper.enableClipPlane(4); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + } + + void enablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void enablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void enableVertexAttribute() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); + QVERIFY(shaderProgram.link()); + shaderProgram.bind(); + + // WHEN + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void frontFace() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + m_func->glFrontFace(GL_CW); + + // THEN + GLint face = 0; + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CW); + + // WHEN + m_glHelper.frontFace(GL_CCW); + + // THEN + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CCW); + } + + void getRenderBufferDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void getTextureDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + + // WHEN + const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + } + + void pointSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // WHEN + m_glHelper.pointSize(false, 0.5f); + // THEN + GLfloat size = 0.0f; + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 0.5f); + } + + void maxClipPlaneCount() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + GLint maxCount = -1; + m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); + + // THEN + QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); + } + + void programUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // Not supported by GL2 + } + + void programAttributesAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeAttributes.size(), 2); + std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_name < b.m_name; }); + + const ShaderAttribute attribute1 = activeAttributes.at(0); + QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); + QCOMPARE(attribute1.m_size, 1); + QCOMPARE(attribute1.m_location, shaderProgram.attributeLocation("vertexPosition")); + QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); + + const ShaderAttribute attribute2 = activeAttributes.at(1); + QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); + QCOMPARE(attribute2.m_size, 1); + QCOMPARE(attribute2.m_location, shaderProgram.attributeLocation("vertexTexCoord")); + QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); + } + + void programUniformsAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniforms.size(), 4); + std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_name < b.m_name; }); + + const ShaderUniform uniform1 = activeUniforms.at(0); + QCOMPARE(uniform1.m_location, shaderProgram.uniformLocation("multiplier")); + QCOMPARE(uniform1.m_offset, -1); + QCOMPARE(uniform1.m_blockIndex, -1); + QCOMPARE(uniform1.m_arrayStride, -1); + QCOMPARE(uniform1.m_matrixStride, -1); + QCOMPARE(uniform1.m_size, 1); + QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); + QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); + + const ShaderUniform uniform2 = activeUniforms.at(1); + QCOMPARE(uniform2.m_location, shaderProgram.uniformLocation("multiplierVec2")); + QCOMPARE(uniform2.m_offset, -1); + QCOMPARE(uniform2.m_blockIndex, -1); + QCOMPARE(uniform2.m_arrayStride, -1); + QCOMPARE(uniform2.m_matrixStride, -1); + QCOMPARE(uniform2.m_size, 1); + QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); + QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); + + const ShaderUniform uniform3 = activeUniforms.at(2); + QCOMPARE(uniform3.m_location, shaderProgram.uniformLocation("multiplierVec3")); + QCOMPARE(uniform3.m_offset, -1); + QCOMPARE(uniform3.m_blockIndex, -1); + QCOMPARE(uniform3.m_arrayStride, -1); + QCOMPARE(uniform3.m_matrixStride, -1); + QCOMPARE(uniform3.m_size, 1); + QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); + QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); + + const ShaderUniform uniform4 = activeUniforms.at(3); + QCOMPARE(uniform4.m_location, shaderProgram.uniformLocation("multiplierVec4")); + QCOMPARE(uniform4.m_offset, -1); + QCOMPARE(uniform4.m_blockIndex, -1); + QCOMPARE(uniform4.m_arrayStride, -1); + QCOMPARE(uniform4.m_matrixStride, -1); + QCOMPARE(uniform4.m_size, 1); + QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); + QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); + } + + void programShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void releaseFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + if (!m_fboFuncs) + QSKIP("FBO not supported by OpenGL 2.0"); + // GIVEN + GLuint fboId; + m_fboFuncs->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.releaseFrameBufferObject(fboId); + + // THEN + QVERIFY(!m_fboFuncs->glIsFramebuffer(fboId)); + } + + void setMSAAEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + m_func->glDisable(GL_MULTISAMPLE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + } + + void setAlphaCoverageEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + } + + void setClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // Deprecated in 3.3 core + } + + void setSeamlessCubemap() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported in GL2 + } + + void setVerticesPerPatch() + { + // Not supported in GL2 + } + +#define SUPPORTS_FEATURE(Feature, IsSupported) \ + QVERIFY(m_glHelper.supportsFeature(Feature) == IsSupported); + + void supportsFeature() + { + SUPPORTS_FEATURE(GraphicsHelperInterface::MRT, (m_fboFuncs != nullptr)); + SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::BindableFragmentOutputs, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::PrimitiveRestart, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::RenderBufferDimensionRetrieval, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::TextureDimensionRetrieval, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::ShaderStorageObject, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::Compute, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::DrawBuffersBlend, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::Tessellation, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::BlitFramebuffer, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::IndirectDrawing, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::MapBuffer, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::Fences, false); + } + + +#define ADD_UNIFORM_ENTRY(FragShader, Name, Type, ComponentSize, ExpectedRawSize) \ + QTest::newRow(#FragShader"_"#Type) << FragShader << QStringLiteral(Name) << Type << ComponentSize << ExpectedRawSize; + + void uniformsByteSize_data() + { + QTest::addColumn("fragShader"); + QTest::addColumn("name"); + QTest::addColumn("type"); + QTest::addColumn("componentSize"); + QTest::addColumn("expectedByteSize"); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplier", GL_FLOAT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec2", GL_FLOAT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec3",GL_FLOAT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec4", GL_FLOAT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplier", GL_INT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec2", GL_INT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec3", GL_INT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec4", GL_INT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m2", GL_FLOAT_MAT2, 1, 4 * 2 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m23", GL_FLOAT_MAT2x3, 1, 4 * 2 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m32", GL_FLOAT_MAT3x2, 1, 4 * 3 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m24", GL_FLOAT_MAT2x4, 1, 4 * 2 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m42", GL_FLOAT_MAT4x2, 1, 4 * 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m3", GL_FLOAT_MAT3, 1, 4 * 3 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m34", GL_FLOAT_MAT3x4, 1, 4 * 3 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m43", GL_FLOAT_MAT4x3, 1, 4 * 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m4", GL_FLOAT_MAT4, 1, 4 * 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s1", GL_SAMPLER_1D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2", GL_SAMPLER_2D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s3", GL_SAMPLER_3D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "scube", GL_SAMPLER_CUBE, 1, 4); + } + + void uniformsByteSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QFETCH(QByteArray, fragShader); + QFETCH(QString, name); + QFETCH(int, type); + QFETCH(int, componentSize); + QFETCH(int, expectedByteSize); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); + QVERIFY(shaderProgram.link()); + + GLint location = shaderProgram.uniformLocation(name); + // WHEN + const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + ShaderUniform matchingUniform; + for (const ShaderUniform &u : activeUniforms) { + if (u.m_location == location) { + matchingUniform = u; + break; + } + } + + // THEN + QCOMPARE(matchingUniform.m_location, location); + QCOMPARE(matchingUniform.m_type, GLuint(type)); + QCOMPARE(matchingUniform.m_size, componentSize); + + // WHEN + const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); + + // THEN + QCOMPARE(expectedByteSize, computedRawByteSize); + + // Restore + m_func->glUseProgram(0); + } + + void useProgram() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + + // THEN + QVERIFY(shaderProgram.link()); + + GLint currentProg = 0; + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + + // WHEN + m_glHelper.useProgram(shaderProgram.programId()); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QCOMPARE(GLuint(currentProg), shaderProgram.programId()); + + // WHEN + m_glHelper.useProgram(0); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + } + + void vertexAttribDivisor() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not available in 3.2 + } + + void vertexAttributePointer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); + QVERIFY(shaderProgram.link()); + + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + + const int vertexCount = 99; + QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); + positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + positionBuffer.create(); + positionBuffer.bind(); + positionBuffer.allocate(vertexCount * sizeof(QVector3D)); + + QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); + texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + texCoordBuffer.create(); + texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); + + // WHEN + shaderProgram.bind(); + positionBuffer.bind(); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); + + texCoordBuffer.bind(); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void glUniform1fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat value = 883.0f; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1fv(location, 1, &value); + + // THEN + GLfloat setValue = 0.0f; + m_func->glGetUniformfv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[2] = { 383.0f, 427.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2fv(location, 1, values); + + // THEN + GLfloat setValues[2] = { 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3fv(location, 1, values); + + // THEN + GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4fv(location, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint value = 883; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1iv(location, 1, &value); + + // THEN + GLint setValue = 0; + m_func->glGetUniformiv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[2] = { 383, 427 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2iv(location, 1, values); + + // THEN + GLint setValues[2] = { 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[3] = { 572, 1340, 1584 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3iv(location, 1, values); + + // THEN + GLint setValues[3] = { 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[4] = { 454, 350, 883, 355 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4iv(location, 1, values); + + // THEN + GLint setValues[4] = { 0, 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniform2uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniform3uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniform4uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniformMatrix2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + const GLint location = shaderProgram.uniformLocation("m2"); + m_glHelper.glUniformMatrix2fv(location, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; + const GLint location = shaderProgram.uniformLocation("m3"); + m_glHelper.glUniformMatrix3fv(location, 1, values); + + // THEN + GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 9; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; + const GLint location = shaderProgram.uniformLocation("m4"); + m_glHelper.glUniformMatrix4fv(location, 1, values); + + // THEN + GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 16; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniformMatrix3x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniformMatrix2x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniformMatrix4x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniformMatrix3x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void glUniformMatrix4x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void blitFramebuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + +#define ADD_GL_TYPE_ENTRY(Type, Expected) \ + QTest::newRow(#Type) << Type << Expected; + + void uniformTypeFromGLType_data() + { + QTest::addColumn("glType"); + QTest::addColumn("expected"); + + ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); + ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); + ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); + ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); + ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); + } + + void uniformTypeFromGLType() + { + // GIVEN + QFETCH(int, glType); + QFETCH(UniformType, expected); + + // WHEN + UniformType computed = m_glHelper.uniformTypeFromGLType(glType); + + // THEN + QCOMPARE(computed, expected); + } + + void drawBuffer() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void readBuffer() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void fenceSync() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void clientWaitSync() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void waitSync() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void wasSyncSignaled() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void deleteSync() + { + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + // Not supported by GL2 + } + + void rasterMode() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 2.0 functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_POLYGON_MODE, &p); + QCOMPARE(p, GL_LINE); + } + +private: + QScopedPointer m_window; + QOpenGLContext m_glContext; + GraphicsHelperGL2 m_glHelper; + QOpenGLFunctions_2_0 *m_func = nullptr; + QOpenGLExtension_ARB_framebuffer_object *m_fboFuncs = nullptr; + bool m_initializationSuccessful = false; +}; + +QT_END_NAMESPACE + +#endif + +int main(int argc, char *argv[]) +{ +#ifdef TEST_SHOULD_BE_PERFORMED + QGuiApplication app(argc, argv); + app.setAttribute(Qt::AA_Use96Dpi, true); + tst_GraphicsHelperGL2 tc; + QTEST_SET_MAIN_SOURCE_PATH + return QTest::qExec(&tc, argc, argv); +#endif + return 0; +} + +#ifdef TEST_SHOULD_BE_PERFORMED +#include "tst_graphicshelpergl2.moc" +#endif diff --git a/tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro b/tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro new file mode 100644 index 000000000..a613f1279 --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro @@ -0,0 +1,16 @@ +TEMPLATE = app + +TARGET = tst_graphicshelpergl3_2 + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += \ + tst_graphicshelpergl3_2.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp b/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp new file mode 100644 index 000000000..a4a59d7c4 --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp @@ -0,0 +1,2294 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(QT_OPENGL_ES_2) && defined(QT_OPENGL_3_2) + +#define TEST_SHOULD_BE_PERFORMED 1 + +using namespace Qt3DRender; +using namespace Qt3DRender::Render; + +namespace { + +const QByteArray vertCode = QByteArrayLiteral( + "#version 150 core\n" \ + "in vec3 vertexPosition;\n" \ + "in vec2 vertexTexCoord;\n" \ + "out vec2 texCoord;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vertexTexCoord;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray vertCodeUniformBuffer = QByteArrayLiteral( + "#version 150 core\n" \ + "in vec3 vertexPosition;\n" \ + "in vec2 vertexTexCoord;\n" \ + "in int vertexColorIndex;\n" \ + "out vec2 texCoord;\n" \ + "flat out int colorIndex;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vertexTexCoord;\n" \ + " colorIndex = vertexColorIndex;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeFragOutputs = QByteArrayLiteral( + "#version 150 core\n" \ + "out vec4 color;\n" \ + "out vec2 temp;\n" \ + "void main()\n" \ + "{\n" \ + " color = vec4(1.0, 0.0, 0.0, 1.0);\n" \ + " temp = vec2(1.0, 0.3);\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( + "#version 150 core\n" \ + "out vec4 color;\n" \ + "uniform float multiplier;\n" \ + "uniform vec2 multiplierVec2;\n" \ + "uniform vec3 multiplierVec3;\n" \ + "uniform vec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ + " color = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsInt = QByteArrayLiteral( + "#version 150 core\n" \ + "out vec4 color;\n" \ + "uniform int multiplier;\n" \ + "uniform ivec2 multiplierVec2;\n" \ + "uniform ivec3 multiplierVec3;\n" \ + "uniform ivec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ + " color = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsUInt = QByteArrayLiteral( + "#version 150 core\n" \ + "out vec4 color;\n" \ + "uniform uint multiplier;\n" \ + "uniform uvec2 multiplierVec2;\n" \ + "uniform uvec3 multiplierVec3;\n" \ + "uniform uvec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " uvec4 randomMult = multiplierVec4 + uvec4(multiplierVec3, 0) + uvec4(multiplierVec2, 0, 0);\n" \ + " color = uvec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( + "#version 150 core\n" \ + "out vec4 color;\n" \ + "uniform mat2 m2;\n" \ + "uniform mat2x3 m23;\n" \ + "uniform mat3x2 m32;\n" \ + "uniform mat2x4 m24;\n" \ + "uniform mat4x2 m42;\n" \ + "uniform mat3 m3;\n" \ + "uniform mat3x4 m34;\n" \ + "uniform mat4x3 m43;\n" \ + "uniform mat4 m4;\n" \ + "void main()\n" \ + "{\n" \ + " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ + " color = vec4(1, 0, 0, 1) * lengthSum;\n" \ + "}\n"); + +const QByteArray fragCodeUniformBuffer = QByteArrayLiteral( + "#version 150 core\n" \ + "out vec4 color;\n" \ + "in vec2 texCoord;\n" \ + "flat in int colorIndex;\n" \ + "uniform ColorArray\n" \ + "{\n" \ + " vec4 colors[256];\n" \ + "};\n" \ + "void main()\n" \ + "{\n" \ + " color = colors[colorIndex] + vec4(texCoord.s, texCoord.t, 0.0, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeSamplers = QByteArrayLiteral( + "#version 150 core\n" \ + "in vec2 texCoord;\n" \ + "out vec4 color;\n" \ + "uniform sampler1D s1;\n" \ + "uniform sampler2D s2;\n" \ + "uniform sampler2DArray s2a;\n" \ + "uniform sampler3D s3;\n" \ + "uniform samplerCube scube;\n" \ + "uniform sampler2DRect srect;\n" \ + "void main()\n" \ + "{\n" \ + " color = vec4(1, 0, 0, 1) *" \ + " texture(s1, texCoord.x) *" \ + " texture(s2, texCoord) *" \ + " texture(s2a, vec3(texCoord, 0.0)) *" \ + " texture(s3, vec3(texCoord, 0.0)) *" \ + " texture(scube, vec3(texCoord, 0)) *" \ + " texture(srect, texCoord);\n" \ + "}\n"); + +} // anonymous + +class tst_GraphicsHelperGL3_2 : public QObject +{ + Q_OBJECT +private Q_SLOTS: + + void init() + { + m_window.reset(new QWindow); + m_window->setSurfaceType(QWindow::OpenGLSurface); + m_window->setGeometry(0, 0, 10, 10); + m_window->create(); + + QSurfaceFormat format; + format.setVersion(3, 2); + format.setProfile(QSurfaceFormat::CoreProfile); + format.setDepthBufferSize(24); + format.setSamples(4); + format.setStencilBufferSize(8); + m_window->setFormat(format); + m_glContext.setFormat(format); + + if (!m_glContext.create()) { + qWarning() << "Failed to create OpenGL context"; + return; + } + + if (!m_glContext.makeCurrent(m_window.data())) { + qWarning() << "Failed to make OpenGL context current"; + return; + } + + if ((m_func = m_glContext.versionFunctions()) != nullptr) { + m_glHelper.initializeHelper(&m_glContext, m_func); + m_initializationSuccessful = true; + } + } + + void cleanup() + { + m_glContext.doneCurrent(); + } + + void alphaTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + // Deprecated + } + + void bindBufferBase() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint bufferId = 0; + // WHEN + m_func->glGenBuffers(1, &bufferId); + // THEN + QVERIFY(bufferId != 0); + + + // WHEN + m_func->glBindBuffer(GL_UNIFORM_BUFFER, bufferId); + m_glHelper.bindBufferBase(GL_UNIFORM_BUFFER, 2, bufferId); + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundToPointBufferId = 0; + m_func->glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, 2, &boundToPointBufferId); + QVERIFY(boundToPointBufferId == GLint(bufferId)); + + // Restore to sane state + m_func->glBindBuffer(GL_UNIFORM_BUFFER, 0); + m_func->glDeleteBuffers(1, &bufferId); + } + + void bindFragDataLocation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); + + // WHEN + QHash fragLocations; + fragLocations.insert(QStringLiteral("temp"), 2); + fragLocations.insert(QStringLiteral("color"), 1); + m_glHelper.bindFragDataLocation(shaderProgram.programId(), fragLocations); + + // THEN + QVERIFY(shaderProgram.link()); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + const GLint tempLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "temp"); + const GLint colorLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "color"); + QCOMPARE(tempLocation, 2); + QCOMPARE(colorLocation, 1); + } + + void bindFrameBufferAttachment() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA32F); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture.create()) + qWarning() << "Texture creation failed"; + texture.allocateStorage(); + QVERIFY(texture.isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureAttachmentId = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, + &textureAttachmentId); + QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void bindFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); + + // THEN + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundindFBOId = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // Cleanup + m_func->glDeleteFramebuffers(1, &fboId); + } + + void bindShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + // Not supported in OpenGL 3.2 + } + + void bindUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + // WHEN + GLint index = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); + m_glHelper.bindUniformBlock(shaderProgram.programId(), index, 1); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void blendEquation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLint equation = 0; + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_ADD); + + // WHEN + m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); + + // THEN + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); + } + + void blendFunci() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + // Not supported by OpenGL 3.2 + } + + void blendFuncSeparatei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // Not supported by OpenGL 3.2 + } + + void boundFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + // THEN + GLint boundBuffer = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); + QCOMPARE(GLuint(boundBuffer), fboId); + + // THEN + QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); + + // Reset state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void checkFrameBufferComplete() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + QVERIFY(m_glHelper.checkFrameBufferComplete()); + + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void clearBufferf() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + // Create 4 attachments + QOpenGLTexture *textures[4]; + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // Set Draw buffers + GLenum clearBufferEnum = GL_COLOR_ATTACHMENT3; + m_func->glDrawBuffers(1, &clearBufferEnum); + + const GLint bufferIndex = 0; // index of the element in the draw buffers + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // WHEN + const QVector4D clearValue1 = QVector4D(0.5f, 0.2f, 0.4f, 0.8f); + m_func->glClearBufferfv(GL_COLOR, bufferIndex, reinterpret_cast(&clearValue1)); + error = m_func->glGetError(); + QVERIFY(error == 0); + + // THEN + QVector colors(512 * 512); + textures[3]->bind(); + m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); + textures[3]->release(); + for (const QVector4D c : colors) { + QVERIFY(c == clearValue1); + } + + // WHEN + const QVector4D clearValue2 = QVector4D(0.4f, 0.5f, 0.4f, 1.0f); + m_glHelper.clearBufferf(bufferIndex, clearValue2); + + // THEN + textures[3]->bind(); + m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); + textures[3]->release(); + for (const QVector4D c : colors) { + QVERIFY(c == clearValue2); + } + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void createFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // WHEN + const GLuint fboId = m_glHelper.createFrameBufferObject(); + + // THEN + QVERIFY(fboId != 0); + + // Restore + m_func->glDeleteFramebuffers(1, &fboId); + } + + void depthMask() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLboolean depthWritingEnabled = false; + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + + // THEN + QVERIFY(depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_FALSE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(!depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_TRUE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(depthWritingEnabled); + } + + void depthTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_DEPTH_TEST); + m_func->glDepthFunc(GL_LESS); + + // WHEN + m_glHelper.depthTest(GL_LEQUAL); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + GLint depthMode = 0; + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LEQUAL); + + // WHEN + m_glHelper.depthTest(GL_LESS); + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LESS); + } + + void disableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_CLIP_DISTANCE0 + 5); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + + // WHEN + m_glHelper.disableClipPlane(5); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + } + + void disablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glEnablei(GL_BLEND, 2); + + // THEN + QVERIFY(m_func->glIsEnabledi(GL_BLEND, 2)); + + // WHEN + m_glHelper.disablei(GL_BLEND, 2); + + // THEN + QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 2)); + } + + void disablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_PRIMITIVE_RESTART); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + + // WHEN + m_glHelper.disablePrimitiveRestart(); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + } + + void drawBuffers() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + QOpenGLTexture *textures[4]; + + // Create 4 attachments + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // WHEN + GLenum bufferEnum = GL_COLOR_ATTACHMENT4; + m_func->glDrawBuffers(1, &bufferEnum); + + // THEN + GLint enumValue = -1; + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); + + // WHEN + GLint newBufferEnum = 2; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // WHEN + newBufferEnum = 0; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void enableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_CLIP_DISTANCE0 + 4); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + + // WHEN + m_glHelper.enableClipPlane(4); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + } + + void enablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisablei(GL_BLEND, 4); + + // THEN + QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 4)); + + // WHEN + m_glHelper.enablei(GL_BLEND, 4); + + // THEN + QVERIFY(m_func->glIsEnabledi(GL_BLEND, 4)); + } + + void enablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_PRIMITIVE_RESTART); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + + // WHEN + m_glHelper.enablePrimitiveRestart(883); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + GLint restartIndex = 0; + m_func->glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX, &restartIndex); + QCOMPARE(restartIndex, 883); + + // Restore + m_func->glDisable(GL_PRIMITIVE_RESTART); + } + + void enableVertexAttribute() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + shaderProgram.bind(); + + // WHEN + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void frontFace() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glFrontFace(GL_CW); + + // THEN + GLint face = 0; + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CW); + + // WHEN + m_glHelper.frontFace(GL_CCW); + + // THEN + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CCW); + } + + void getRenderBufferDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint renderBufferId = 0; + m_func->glGenRenderbuffers(1, &renderBufferId); + QVERIFY(renderBufferId != 0); + + // WHEN + m_func->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_func->glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, 512, 512); + m_func->glBindRenderbuffer(GL_RENDERBUFFER, 0); + const QSize dimensions = m_glHelper.getRenderBufferDimensions(renderBufferId); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + + // Restore + m_func->glDeleteRenderbuffers(1, &renderBufferId); + } + + void getTextureDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + + // WHEN + const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + } + + void pointSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_PROGRAM_POINT_SIZE); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); + GLfloat size = 0; + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 1.0f); + + // WHEN + m_glHelper.pointSize(false, 0.5f); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 0.5f); + } + + void maxClipPlaneCount() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLint maxCount = -1; + m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); + + // THEN + QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); + } + + void programUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + // WHEN + const QVector activeUniformBlocks = m_glHelper.programUniformBlocks(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniformBlocks.size(), 1); + const ShaderUniformBlock uniformBlock = activeUniformBlocks.first(); + + QCOMPARE(uniformBlock.m_activeUniformsCount, 1); + QCOMPARE(uniformBlock.m_name, QStringLiteral("ColorArray")); + + GLint blockIndex = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); + GLint blockBinding = -1; + m_func->glGetActiveUniformBlockiv(shaderProgram.programId(), blockIndex, GL_UNIFORM_BLOCK_BINDING, &blockBinding); + QCOMPARE(blockIndex, uniformBlock.m_index); + QCOMPARE(blockBinding, uniformBlock.m_binding); + } + + void programAttributesAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeAttributes.size(), 2); + std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_name < b.m_name; }); + + const ShaderAttribute attribute1 = activeAttributes.at(0); + QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); + QCOMPARE(attribute1.m_size, 1); + QCOMPARE(attribute1.m_location, shaderProgram.attributeLocation("vertexPosition")); + QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); + + const ShaderAttribute attribute2 = activeAttributes.at(1); + QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); + QCOMPARE(attribute2.m_size, 1); + QCOMPARE(attribute2.m_location, shaderProgram.attributeLocation("vertexTexCoord")); + QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); + } + + void programUniformsAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniforms.size(), 4); + std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_name < b.m_name; }); + + const ShaderUniform uniform1 = activeUniforms.at(0); + QCOMPARE(uniform1.m_location, shaderProgram.uniformLocation("multiplier")); + QCOMPARE(uniform1.m_offset, -1); + QCOMPARE(uniform1.m_blockIndex, -1); + QCOMPARE(uniform1.m_arrayStride, -1); + QCOMPARE(uniform1.m_matrixStride, -1); + QCOMPARE(uniform1.m_size, 1); + QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); + QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); + + const ShaderUniform uniform2 = activeUniforms.at(1); + QCOMPARE(uniform2.m_location, shaderProgram.uniformLocation("multiplierVec2")); + QCOMPARE(uniform2.m_offset, -1); + QCOMPARE(uniform2.m_blockIndex, -1); + QCOMPARE(uniform2.m_arrayStride, -1); + QCOMPARE(uniform2.m_matrixStride, -1); + QCOMPARE(uniform2.m_size, 1); + QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); + QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); + + const ShaderUniform uniform3 = activeUniforms.at(2); + QCOMPARE(uniform3.m_location, shaderProgram.uniformLocation("multiplierVec3")); + QCOMPARE(uniform3.m_offset, -1); + QCOMPARE(uniform3.m_blockIndex, -1); + QCOMPARE(uniform3.m_arrayStride, -1); + QCOMPARE(uniform3.m_matrixStride, -1); + QCOMPARE(uniform3.m_size, 1); + QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); + QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); + + const ShaderUniform uniform4 = activeUniforms.at(3); + QCOMPARE(uniform4.m_location, shaderProgram.uniformLocation("multiplierVec4")); + QCOMPARE(uniform4.m_offset, -1); + QCOMPARE(uniform4.m_blockIndex, -1); + QCOMPARE(uniform4.m_arrayStride, -1); + QCOMPARE(uniform4.m_matrixStride, -1); + QCOMPARE(uniform4.m_size, 1); + QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); + QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); + } + + void programShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // Not supported in 3.2 + } + + void releaseFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.releaseFrameBufferObject(fboId); + + // THEN + QVERIFY(!m_func->glIsFramebuffer(fboId)); + } + + void setMSAAEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_MULTISAMPLE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + } + + void setAlphaCoverageEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + } + + void setClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // Deprecated in 3.3 core + } + + void setSeamlessCubemap() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + } + + void setVerticesPerPatch() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + } + +#define SUPPORTS_FEATURE(Feature, IsSupported) \ + QVERIFY(m_glHelper.supportsFeature(Feature) == IsSupported); + + void supportsFeature() + { + SUPPORTS_FEATURE(GraphicsHelperInterface::MRT, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::BindableFragmentOutputs, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::PrimitiveRestart, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::RenderBufferDimensionRetrieval, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::TextureDimensionRetrieval, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::ShaderStorageObject, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::Compute, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::DrawBuffersBlend, false); + // Tesselation could be true or false depending on extensions so not tested + SUPPORTS_FEATURE(GraphicsHelperInterface::BlitFramebuffer, true); + } + + +#define ADD_UNIFORM_ENTRY(FragShader, Name, Type, ComponentSize, ExpectedRawSize) \ + QTest::newRow(#FragShader"_"#Type) << FragShader << QStringLiteral(Name) << Type << ComponentSize << ExpectedRawSize; + + void uniformsByteSize_data() + { + QTest::addColumn("fragShader"); + QTest::addColumn("name"); + QTest::addColumn("type"); + QTest::addColumn("componentSize"); + QTest::addColumn("expectedByteSize"); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplier", GL_FLOAT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec2", GL_FLOAT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec3",GL_FLOAT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec4", GL_FLOAT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplier", GL_INT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec2", GL_INT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec3", GL_INT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec4", GL_INT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplier", GL_UNSIGNED_INT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec2", GL_UNSIGNED_INT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec3", GL_UNSIGNED_INT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec4", GL_UNSIGNED_INT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m2", GL_FLOAT_MAT2, 1, 4 * 2 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m23", GL_FLOAT_MAT2x3, 1, 4 * 2 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m32", GL_FLOAT_MAT3x2, 1, 4 * 3 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m24", GL_FLOAT_MAT2x4, 1, 4 * 2 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m42", GL_FLOAT_MAT4x2, 1, 4 * 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m3", GL_FLOAT_MAT3, 1, 4 * 3 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m34", GL_FLOAT_MAT3x4, 1, 4 * 3 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m43", GL_FLOAT_MAT4x3, 1, 4 * 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m4", GL_FLOAT_MAT4, 1, 4 * 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s1", GL_SAMPLER_1D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2", GL_SAMPLER_2D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2a", GL_SAMPLER_2D_ARRAY, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s3", GL_SAMPLER_3D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "scube", GL_SAMPLER_CUBE, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "srect", GL_SAMPLER_2D_RECT, 1, 4); + } + + void uniformsByteSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QFETCH(QByteArray, fragShader); + QFETCH(QString, name); + QFETCH(int, type); + QFETCH(int, componentSize); + QFETCH(int, expectedByteSize); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); + QVERIFY(shaderProgram.link()); + + GLint location = shaderProgram.uniformLocation(name); + // WHEN + const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + ShaderUniform matchingUniform; + for (const ShaderUniform &u : activeUniforms) { + if (u.m_location == location) { + matchingUniform = u; + break; + } + } + + + // THEN + QCOMPARE(matchingUniform.m_location, location); + QCOMPARE(matchingUniform.m_type, GLuint(type)); + QCOMPARE(matchingUniform.m_size, componentSize); + + // WHEN + const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); + + // THEN + QCOMPARE(expectedByteSize, computedRawByteSize); + + // Restore + m_func->glUseProgram(0); + } + + void useProgram() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); + + // THEN + QVERIFY(shaderProgram.link()); + + GLint currentProg = 0; + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + + // WHEN + m_glHelper.useProgram(shaderProgram.programId()); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QCOMPARE(GLuint(currentProg), shaderProgram.programId()); + + // WHEN + m_glHelper.useProgram(0); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + } + + void vertexAttribDivisor() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + // Not available in 3.2 + } + + void vertexAttributePointer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); + + const int vertexCount = 99; + QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); + positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + positionBuffer.create(); + positionBuffer.bind(); + positionBuffer.allocate(vertexCount * sizeof(QVector3D)); + + QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); + texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + texCoordBuffer.create(); + texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); + + QOpenGLBuffer colorIndexBuffer(QOpenGLBuffer::VertexBuffer); + colorIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + colorIndexBuffer.create(); + colorIndexBuffer.allocate(vertexCount * sizeof(int)); + + // WHEN + shaderProgram.bind(); + positionBuffer.bind(); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); + + texCoordBuffer.bind(); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); + + colorIndexBuffer.bind(); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + m_glHelper.vertexAttributePointer(GL_INT, colorIndexLocation, 1, GL_INT, GL_TRUE, 0, 0); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void glUniform1fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat value = 883.0f; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1fv(location, 1, &value); + + // THEN + GLfloat setValue = 0.0f; + m_func->glGetUniformfv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[2] = { 383.0f, 427.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2fv(location, 1, values); + + // THEN + GLfloat setValues[2] = { 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3fv(location, 1, values); + + // THEN + GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4fv(location, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint value = 883; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1iv(location, 1, &value); + + // THEN + GLint setValue = 0; + m_func->glGetUniformiv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[2] = { 383, 427 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2iv(location, 1, values); + + // THEN + GLint setValues[2] = { 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[3] = { 572, 1340, 1584 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3iv(location, 1, values); + + // THEN + GLint setValues[3] = { 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[4] = { 454, 350, 883, 355 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4iv(location, 1, values); + + // THEN + GLint setValues[4] = { 0, 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint value = 883U; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1uiv(location, 1, &value); + + // THEN + GLuint setValue = 0U; + m_func->glGetUniformuiv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[2] = { 383U, 427U }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2uiv(location, 1, values); + + // THEN + GLuint setValues[2] = { 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[3] = { 572U, 1340U, 1584U }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3uiv(location, 1, values); + + // THEN + GLuint setValues[3] = { 0U, 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[4] = { 454U, 350U, 883U, 355U }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4uiv(location, 1, values); + + // THEN + GLuint setValues[4] = { 0U, 0U, 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + const GLint location = shaderProgram.uniformLocation("m2"); + m_glHelper.glUniformMatrix2fv(location, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; + const GLint location = shaderProgram.uniformLocation("m3"); + m_glHelper.glUniformMatrix3fv(location, 1, values); + + // THEN + GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 9; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; + const GLint location = shaderProgram.uniformLocation("m4"); + m_glHelper.glUniformMatrix4fv(location, 1, values); + + // THEN + GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 16; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m23"); + m_glHelper.glUniformMatrix2x3fv(location, 1, values); + + // THEN + GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 6; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m32"); + m_glHelper.glUniformMatrix3x2fv(location, 1, values); + + // THEN + GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 6; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m24"); + m_glHelper.glUniformMatrix2x4fv(location, 1, values); + + // THEN + GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 8; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m42"); + m_glHelper.glUniformMatrix4x2fv(location, 1, values); + + // THEN + GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 8; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f}; + const GLint location = shaderProgram.uniformLocation("m34"); + m_glHelper.glUniformMatrix3x4fv(location, 1, values); + + // THEN + GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 12; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m43"); + m_glHelper.glUniformMatrix4x3fv(location, 1, values); + + // THEN + GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 12; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void blitFramebuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + GLint maxSamples; + m_func->glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); + if (maxSamples < 1) + QSKIP("This test requires an implementation that supports multisampled textures"); + + // GIVEN + GLuint fbos[2]; + GLuint fboTextures[2]; + + m_func->glGenFramebuffers(2, fbos); + m_func->glGenTextures(2, fboTextures); + + m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fboTextures[0]); + m_func->glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, maxSamples, GL_RGBA8, 10, 10, true); + m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); + + m_func->glBindTexture(GL_TEXTURE_2D, fboTextures[1]); + m_func->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 10, 10, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + m_func->glBindTexture(GL_TEXTURE_2D, 0); + + m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[1]); + m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[1], 0); + + GLenum status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[0]); + m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[0], 0); + + status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + m_func->glEnable(GL_MULTISAMPLE); + m_func->glClearColor(0.2f, 0.2f, 0.2f, 0.2f); + m_func->glClear(GL_COLOR_BUFFER_BIT); + m_func->glDisable(GL_MULTISAMPLE); + + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); + + // WHEN + m_glHelper.blitFramebuffer(0,0,10,10,0,0,10,10, GL_COLOR_BUFFER_BIT, GL_NEAREST); + + m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[1]); + + GLuint result[10*10]; + m_func->glReadPixels(0,0,10,10,GL_RGBA, GL_UNSIGNED_BYTE, result); + + // THEN + GLuint v = (0.2f) * 255; + v = v | (v<<8) | (v<<16) | (v<<24); + for (GLuint value : result) { + QCOMPARE(value, v); + } + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + + m_func->glDeleteFramebuffers(2, fbos); + m_func->glDeleteTextures(2, fboTextures); + } + +#define ADD_GL_TYPE_ENTRY(Type, Expected) \ + QTest::newRow(#Type) << Type << Expected; + + void uniformTypeFromGLType_data() + { + QTest::addColumn("glType"); + QTest::addColumn("expected"); + + ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); + ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); + ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); + ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT, UniformType::UInt); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC2, UniformType::UIVec2); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC3, UniformType::UIVec3); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC4, UniformType::UIVec4); + ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x3, UniformType::Mat2x3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x4, UniformType::Mat2x4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x2, UniformType::Mat3x2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x2, UniformType::Mat4x2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x3, UniformType::Mat4x3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x4, UniformType::Mat3x4); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_RECT, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE, UniformType::Sampler); + } + + void uniformTypeFromGLType() + { + // GIVEN + QFETCH(int, glType); + QFETCH(UniformType, expected); + + // WHEN + UniformType computed = m_glHelper.uniformTypeFromGLType(glType); + + // THEN + QCOMPARE(computed, expected); + } + + void drawBuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.drawBuffer(GL_FRONT); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // THEN + GLint p; + m_func->glGetIntegerv(GL_DRAW_BUFFER, &p); + QCOMPARE(p, GL_FRONT); + } + + void readBuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.readBuffer(GL_FRONT); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_READ_BUFFER, &p); + QCOMPARE(p, GL_FRONT); + } + + void fenceSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + + // THEN + QVERIFY(sync != nullptr); + QCOMPARE(m_func->glIsSync(sync), GL_TRUE); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void clientWaitSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + QElapsedTimer t; + t.start(); + + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + + m_glHelper.clientWaitSync(sync, 1000000); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + qDebug() << t.nsecsElapsed(); + } + + void waitSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_func->glFlush(); + m_glHelper.waitSync(sync); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void wasSyncSignaled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_func->glFlush(); + m_glHelper.waitSync(sync); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // Shouldn't loop forever + while (!m_glHelper.wasSyncSignaled(sync)) + ; + } + + void deleteSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_glHelper.clientWaitSync(sync, GLuint64(-1)); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + QVERIFY(m_glHelper.wasSyncSignaled(sync) == true); + + // WHEN + m_glHelper.deleteSync(sync); + + // THEN + QCOMPARE(m_func->glIsSync(sync), GL_FALSE); + } + + void rasterMode() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.2 functions not supported"); + + m_func->glGetError(); + + m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_POLYGON_MODE, &p); + QCOMPARE(p, GL_LINE); + } + +private: + QScopedPointer m_window; + QOpenGLContext m_glContext; + GraphicsHelperGL3_2 m_glHelper; + QOpenGLFunctions_3_2_Core *m_func = nullptr; + bool m_initializationSuccessful = false; +}; + +#endif + +int main(int argc, char *argv[]) +{ +#ifdef TEST_SHOULD_BE_PERFORMED + QGuiApplication app(argc, argv); + app.setAttribute(Qt::AA_Use96Dpi, true); + tst_GraphicsHelperGL3_2 tc; + QTEST_SET_MAIN_SOURCE_PATH + return QTest::qExec(&tc, argc, argv); +#endif + return 0; +} + +#ifdef TEST_SHOULD_BE_PERFORMED +#include "tst_graphicshelpergl3_2.moc" +#endif diff --git a/tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro b/tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro new file mode 100644 index 000000000..5ef0b6806 --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro @@ -0,0 +1,16 @@ +TEMPLATE = app + +TARGET = tst_graphicshelpergl3_3 + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += \ + tst_graphicshelpergl3_3.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp b/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp new file mode 100644 index 000000000..3e4a052ba --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp @@ -0,0 +1,2393 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(QT_OPENGL_ES_2) && defined(QT_OPENGL_3_2) + +#define TEST_SHOULD_BE_PERFORMED 1 + +using namespace Qt3DRender; +using namespace Qt3DRender::Render; + +namespace { + +const QByteArray vertCode = QByteArrayLiteral( + "#version 330 core\n" \ + "in vec3 vertexPosition;\n" \ + "in vec2 vertexTexCoord;\n" \ + "out vec2 texCoord;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vertexTexCoord;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray vertCodeUniformBuffer = QByteArrayLiteral( + "#version 330 core\n" \ + "in vec3 vertexPosition;\n" \ + "in vec2 vertexTexCoord;\n" \ + "in int vertexColorIndex;\n" \ + "out vec2 texCoord;\n" \ + "flat out int colorIndex;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vertexTexCoord;\n" \ + " colorIndex = vertexColorIndex;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeFragOutputs = QByteArrayLiteral( + "#version 330 core\n" \ + "out vec4 color;\n" \ + "out vec2 temp;\n" \ + "void main()\n" \ + "{\n" \ + " color = vec4(1.0, 0.0, 0.0, 1.0);\n" \ + " temp = vec2(1.0, 0.3);\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( + "#version 330 core\n" \ + "out vec4 color;\n" \ + "uniform float multiplier;\n" \ + "uniform vec2 multiplierVec2;\n" \ + "uniform vec3 multiplierVec3;\n" \ + "uniform vec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ + " color = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsInt = QByteArrayLiteral( + "#version 330 core\n" \ + "out ivec4 color;\n" \ + "uniform int multiplier;\n" \ + "uniform ivec2 multiplierVec2;\n" \ + "uniform ivec3 multiplierVec3;\n" \ + "uniform ivec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ + " color = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsUInt = QByteArrayLiteral( + "#version 330 core\n" \ + "out uvec4 color;\n" \ + "uniform uint multiplier;\n" \ + "uniform uvec2 multiplierVec2;\n" \ + "uniform uvec3 multiplierVec3;\n" \ + "uniform uvec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " uvec4 randomMult = multiplierVec4 + uvec4(multiplierVec3, 0) + uvec4(multiplierVec2, 0, 0);\n" \ + " color = uvec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( + "#version 330 core\n" \ + "out vec4 color;\n" \ + "uniform mat2 m2;\n" \ + "uniform mat2x3 m23;\n" \ + "uniform mat3x2 m32;\n" \ + "uniform mat2x4 m24;\n" \ + "uniform mat4x2 m42;\n" \ + "uniform mat3 m3;\n" \ + "uniform mat3x4 m34;\n" \ + "uniform mat4x3 m43;\n" \ + "uniform mat4 m4;\n" \ + "void main()\n" \ + "{\n" \ + " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ + " color = vec4(1, 0, 0, 1) * lengthSum;\n" \ + "}\n"); + +const QByteArray fragCodeUniformBuffer = QByteArrayLiteral( + "#version 330 core\n" \ + "out vec4 color;\n" \ + "in vec2 texCoord;\n" \ + "flat in int colorIndex;\n" \ + "uniform ColorArray\n" \ + "{\n" \ + " vec4 colors[256];\n" \ + "};\n" \ + "void main()\n" \ + "{\n" \ + " color = colors[colorIndex] + vec4(texCoord.s, texCoord.t, 0.0, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeSamplers = QByteArrayLiteral( + "#version 330 core\n" \ + "in vec2 texCoord;\n" \ + "out vec4 color;\n" \ + "uniform sampler1D s1;\n" \ + "uniform sampler2D s2;\n" \ + "uniform sampler2DArray s2a;\n" \ + "uniform sampler3D s3;\n" \ + "uniform samplerCube scube;\n" \ + "uniform sampler2DRect srect;\n" \ + "void main()\n" \ + "{\n" \ + " color = vec4(1, 0, 0, 1) *" \ + " texture(s1, texCoord.x) *" \ + " texture(s2, texCoord) *" \ + " texture(s2a, vec3(texCoord, 0.0)) *" \ + " texture(s3, vec3(texCoord, 0.0)) *" \ + " texture(scube, vec3(texCoord, 0)) *" \ + " texture(srect, texCoord);\n" \ + "}\n"); + +} // anonymous + +class tst_GraphicsHelperGL3_3 : public QObject +{ + Q_OBJECT +private Q_SLOTS: + + void init() + { + m_window.reset(new QWindow); + m_window->setSurfaceType(QWindow::OpenGLSurface); + m_window->setGeometry(0, 0, 10, 10); + + QSurfaceFormat format; + format.setVersion(3, 3); + format.setProfile(QSurfaceFormat::CoreProfile); + format.setDepthBufferSize(24); + format.setSamples(4); + format.setStencilBufferSize(8); + m_window->setFormat(format); + m_glContext.setFormat(format); + + m_window->create(); + + if (!m_glContext.create()) { + qWarning() << "Failed to create OpenGL context"; + return; + } + + if (!m_glContext.makeCurrent(m_window.data())) { + qWarning() << "Failed to maed OpenGL context current"; + return; + } + + if ((m_func = m_glContext.versionFunctions()) != nullptr) { + m_glHelper.initializeHelper(&m_glContext, m_func); + m_initializationSuccessful = true; + } + } + + void cleanup() + { + m_glContext.doneCurrent(); + } + + void alphaTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + // Deprecated + } + + void bindBufferBase() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLuint bufferId = 0; + // WHEN + m_func->glGenBuffers(1, &bufferId); + // THEN + QVERIFY(bufferId != 0); + + + // WHEN + m_func->glBindBuffer(GL_UNIFORM_BUFFER, bufferId); + m_glHelper.bindBufferBase(GL_UNIFORM_BUFFER, 2, bufferId); + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundToPointBufferId = 0; + m_func->glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, 2, &boundToPointBufferId); + QVERIFY(boundToPointBufferId == GLint(bufferId)); + + // Restore to sane state + m_func->glBindBuffer(GL_UNIFORM_BUFFER, 0); + m_func->glDeleteBuffers(1, &bufferId); + } + + void bindFragDataLocation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); + + // WHEN + QHash fragLocations; + fragLocations.insert(QStringLiteral("temp"), 2); + fragLocations.insert(QStringLiteral("color"), 1); + m_glHelper.bindFragDataLocation(shaderProgram.programId(), fragLocations); + + // THEN + QVERIFY(shaderProgram.link()); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + const GLint tempLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "temp"); + const GLint colorLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "color"); + QCOMPARE(tempLocation, 2); + QCOMPARE(colorLocation, 1); + } + + void bindFrameBufferAttachment() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + { + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + + GLint maxAttachmentsCount = 0; + m_func->glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxAttachmentsCount); + + // THEN + QVERIFY(fboId != 0); + QVERIFY(maxAttachmentsCount >= 3); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture.create()) + qWarning() << "Texture creation failed"; + texture.allocateStorage(); + QVERIFY(texture.isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QCOMPARE(int(status), GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureAttachmentId = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, + &textureAttachmentId); + QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + { + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::TargetCubeMap); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA32F); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture.create()) + qWarning() << "Texture creation failed"; + texture.allocateStorage(); + QVERIFY(texture.isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + { // Check All Faces + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + attachment.m_face = Qt3DRender::QAbstractTexture::AllFaces; + + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureIsLayered = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_LAYERED, + &textureIsLayered); + QCOMPARE(textureIsLayered, GL_TRUE); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + { // Check Specific Faces + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + attachment.m_face = Qt3DRender::QAbstractTexture::CubeMapNegativeZ; + + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureFace = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, + &textureFace); + QCOMPARE(textureFace, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); + GLint textureIsLayered = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_LAYERED, + &textureIsLayered); + QCOMPARE(textureIsLayered, GL_FALSE); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + } + } + + void bindFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); + + // THEN + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundindFBOId = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // Cleanup + m_func->glDeleteFramebuffers(1, &fboId); + } + + void bindShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + // Not supported in OpenGL 3.3 + } + + void bindUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + // WHEN + GLint index = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); + m_glHelper.bindUniformBlock(shaderProgram.programId(), index, 1); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void blendEquation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLint equation = 0; + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_ADD); + + // WHEN + m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); + + // THEN + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); + } + + void blendFunci() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + // Not supported by OpenGL 3.3 + } + + void blendFuncSeparatei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // Not supported by OpenGL 3.3 + } + + void boundFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + // THEN + GLint boundBuffer = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); + QCOMPARE(GLuint(boundBuffer), fboId); + + // THEN + QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); + + // Reset state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void checkFrameBufferComplete() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + QVERIFY(m_glHelper.checkFrameBufferComplete()); + + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void clearBufferf() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + // Create 4 attachments + QOpenGLTexture *textures[4]; + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // Set Draw buffers + GLenum clearBufferEnum = GL_COLOR_ATTACHMENT3; + m_func->glDrawBuffers(1, &clearBufferEnum); + + const GLint bufferIndex = 0; // index of the element in the draw buffers + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // WHEN + const QVector4D clearValue1 = QVector4D(0.5f, 0.2f, 0.4f, 0.8f); + m_func->glClearBufferfv(GL_COLOR, bufferIndex, reinterpret_cast(&clearValue1)); + error = m_func->glGetError(); + QVERIFY(error == 0); + + // THEN + QVector colors(512 * 512); + textures[3]->bind(); + m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); + textures[3]->release(); + + for (const QVector4D c : colors) { + QVERIFY(c == clearValue1); + } + + // WHEN + const QVector4D clearValue2 = QVector4D(0.4f, 0.5f, 0.4f, 1.0f); + m_glHelper.clearBufferf(bufferIndex, clearValue2); + + // THEN + textures[3]->bind(); + m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); + textures[3]->release(); + for (const QVector4D c : colors) { + QVERIFY(c == clearValue2); + } + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void createFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // WHEN + const GLuint fboId = m_glHelper.createFrameBufferObject(); + + // THEN + QVERIFY(fboId != 0); + + // Restore + m_func->glDeleteFramebuffers(1, &fboId); + } + + void depthMask() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLboolean depthWritingEnabled = false; + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + + // THEN + QVERIFY(depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_FALSE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(!depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_TRUE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(depthWritingEnabled); + } + + void depthTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_DEPTH_TEST); + m_func->glDepthFunc(GL_LESS); + + // WHEN + m_glHelper.depthTest(GL_LEQUAL); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + GLint depthMode = 0; + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LEQUAL); + + // WHEN + m_glHelper.depthTest(GL_LESS); + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LESS); + } + + void disableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_CLIP_DISTANCE0 + 5); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + + // WHEN + m_glHelper.disableClipPlane(5); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + } + + void disablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glEnablei(GL_BLEND, 2); + + // THEN + QVERIFY(m_func->glIsEnabledi(GL_BLEND, 2)); + + // WHEN + m_glHelper.disablei(GL_BLEND, 2); + + // THEN + QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 2)); + } + + void disablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_PRIMITIVE_RESTART); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + + // WHEN + m_glHelper.disablePrimitiveRestart(); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + } + + void drawBuffers() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + QOpenGLTexture *textures[4]; + + // Create 4 attachments + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // WHEN + GLenum bufferEnum = GL_COLOR_ATTACHMENT4; + m_func->glDrawBuffers(1, &bufferEnum); + + // THEN + GLint enumValue = -1; + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); + + // WHEN + GLint newBufferEnum = 2; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // WHEN + newBufferEnum = 0; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void enableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_CLIP_DISTANCE0 + 4); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + + // WHEN + m_glHelper.enableClipPlane(4); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + } + + void enablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisablei(GL_BLEND, 4); + + // THEN + QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 4)); + + // WHEN + m_glHelper.enablei(GL_BLEND, 4); + + // THEN + QVERIFY(m_func->glIsEnabledi(GL_BLEND, 4)); + } + + void enablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_PRIMITIVE_RESTART); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + + // WHEN + m_glHelper.enablePrimitiveRestart(883); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + GLint restartIndex = 0; + m_func->glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX, &restartIndex); + QCOMPARE(restartIndex, 883); + + // Restore + m_func->glDisable(GL_PRIMITIVE_RESTART); + } + + void enableVertexAttribute() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + shaderProgram.bind(); + + // WHEN + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void frontFace() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glFrontFace(GL_CW); + + // THEN + GLint face = 0; + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CW); + + // WHEN + m_glHelper.frontFace(GL_CCW); + + // THEN + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CCW); + } + + void getRenderBufferDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLuint renderBufferId = 0; + m_func->glGenRenderbuffers(1, &renderBufferId); + QVERIFY(renderBufferId != 0); + + // WHEN + m_func->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_func->glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, 512, 512); + m_func->glBindRenderbuffer(GL_RENDERBUFFER, 0); + const QSize dimensions = m_glHelper.getRenderBufferDimensions(renderBufferId); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + + // Restore + m_func->glDeleteRenderbuffers(1, &renderBufferId); + } + + void getTextureDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + + // WHEN + const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + } + + void pointSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_PROGRAM_POINT_SIZE); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); + GLfloat size = 0; + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 1.0f); + + // WHEN + m_glHelper.pointSize(false, 0.5f); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 0.5f); + } + + void maxClipPlaneCount() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLint maxCount = -1; + m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); + + // THEN + QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); + } + + void programUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + // WHEN + const QVector activeUniformBlocks = m_glHelper.programUniformBlocks(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniformBlocks.size(), 1); + const ShaderUniformBlock uniformBlock = activeUniformBlocks.first(); + + QCOMPARE(uniformBlock.m_activeUniformsCount, 1); + QCOMPARE(uniformBlock.m_name, QStringLiteral("ColorArray")); + + GLint blockIndex = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); + GLint blockBinding = -1; + m_func->glGetActiveUniformBlockiv(shaderProgram.programId(), blockIndex, GL_UNIFORM_BLOCK_BINDING, &blockBinding); + QCOMPARE(blockIndex, uniformBlock.m_index); + QCOMPARE(blockBinding, uniformBlock.m_binding); + } + + void programAttributesAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeAttributes.size(), 2); + std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_name < b.m_name; }); + + const ShaderAttribute attribute1 = activeAttributes.at(0); + QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); + QCOMPARE(attribute1.m_size, 1); + QCOMPARE(attribute1.m_location, shaderProgram.attributeLocation("vertexPosition")); + QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); + + const ShaderAttribute attribute2 = activeAttributes.at(1); + QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); + QCOMPARE(attribute2.m_size, 1); + QCOMPARE(attribute2.m_location, shaderProgram.attributeLocation("vertexTexCoord")); + QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); + } + + void programUniformsAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniforms.size(), 4); + std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_name < b.m_name; }); + + const ShaderUniform uniform1 = activeUniforms.at(0); + QCOMPARE(uniform1.m_location, shaderProgram.uniformLocation("multiplier")); + QCOMPARE(uniform1.m_offset, -1); + QCOMPARE(uniform1.m_blockIndex, -1); + QCOMPARE(uniform1.m_arrayStride, -1); + QCOMPARE(uniform1.m_matrixStride, -1); + QCOMPARE(uniform1.m_size, 1); + QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); + QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); + + const ShaderUniform uniform2 = activeUniforms.at(1); + QCOMPARE(uniform2.m_location, shaderProgram.uniformLocation("multiplierVec2")); + QCOMPARE(uniform2.m_offset, -1); + QCOMPARE(uniform2.m_blockIndex, -1); + QCOMPARE(uniform2.m_arrayStride, -1); + QCOMPARE(uniform2.m_matrixStride, -1); + QCOMPARE(uniform2.m_size, 1); + QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); + QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); + + const ShaderUniform uniform3 = activeUniforms.at(2); + QCOMPARE(uniform3.m_location, shaderProgram.uniformLocation("multiplierVec3")); + QCOMPARE(uniform3.m_offset, -1); + QCOMPARE(uniform3.m_blockIndex, -1); + QCOMPARE(uniform3.m_arrayStride, -1); + QCOMPARE(uniform3.m_matrixStride, -1); + QCOMPARE(uniform3.m_size, 1); + QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); + QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); + + const ShaderUniform uniform4 = activeUniforms.at(3); + QCOMPARE(uniform4.m_location, shaderProgram.uniformLocation("multiplierVec4")); + QCOMPARE(uniform4.m_offset, -1); + QCOMPARE(uniform4.m_blockIndex, -1); + QCOMPARE(uniform4.m_arrayStride, -1); + QCOMPARE(uniform4.m_matrixStride, -1); + QCOMPARE(uniform4.m_size, 1); + QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); + QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); + } + + void programShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // Not supported in 3.3 + } + + void releaseFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.releaseFrameBufferObject(fboId); + + // THEN + QVERIFY(!m_func->glIsFramebuffer(fboId)); + } + + void setMSAAEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_MULTISAMPLE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + } + + void setAlphaCoverageEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + } + + void setClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // Deprecated in 3.3 core + } + + void setSeamlessCubemap() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + } + + void setVerticesPerPatch() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + } + +#define SUPPORTS_FEATURE(Feature, IsSupported) \ + QVERIFY(m_glHelper.supportsFeature(Feature) == IsSupported); + + void supportsFeature() + { + SUPPORTS_FEATURE(GraphicsHelperInterface::MRT, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::BindableFragmentOutputs, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::PrimitiveRestart, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::RenderBufferDimensionRetrieval, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::TextureDimensionRetrieval, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::UniformBufferObject, true); + SUPPORTS_FEATURE(GraphicsHelperInterface::ShaderStorageObject, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::Compute, false); + SUPPORTS_FEATURE(GraphicsHelperInterface::DrawBuffersBlend, false); + // Tesselation could be true or false depending on extensions so not tested + SUPPORTS_FEATURE(GraphicsHelperInterface::BlitFramebuffer, true); + } + + +#define ADD_UNIFORM_ENTRY(FragShader, Name, Type, ComponentSize, ExpectedRawSize) \ + QTest::newRow(#FragShader"_"#Type) << FragShader << QStringLiteral(Name) << Type << ComponentSize << ExpectedRawSize; + + void uniformsByteSize_data() + { + QTest::addColumn("fragShader"); + QTest::addColumn("name"); + QTest::addColumn("type"); + QTest::addColumn("componentSize"); + QTest::addColumn("expectedByteSize"); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplier", GL_FLOAT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec2", GL_FLOAT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec3",GL_FLOAT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, "multiplierVec4", GL_FLOAT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplier", GL_INT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec2", GL_INT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec3", GL_INT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, "multiplierVec4", GL_INT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplier", GL_UNSIGNED_INT, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec2", GL_UNSIGNED_INT_VEC2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec3", GL_UNSIGNED_INT_VEC3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, "multiplierVec4", GL_UNSIGNED_INT_VEC4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m2", GL_FLOAT_MAT2, 1, 4 * 2 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m23", GL_FLOAT_MAT2x3, 1, 4 * 2 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m32", GL_FLOAT_MAT3x2, 1, 4 * 3 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m24", GL_FLOAT_MAT2x4, 1, 4 * 2 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m42", GL_FLOAT_MAT4x2, 1, 4 * 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m3", GL_FLOAT_MAT3, 1, 4 * 3 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m34", GL_FLOAT_MAT3x4, 1, 4 * 3 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m43", GL_FLOAT_MAT4x3, 1, 4 * 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, "m4", GL_FLOAT_MAT4, 1, 4 * 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s1", GL_SAMPLER_1D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2", GL_SAMPLER_2D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s2a", GL_SAMPLER_2D_ARRAY, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "s3", GL_SAMPLER_3D, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "scube", GL_SAMPLER_CUBE, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, "srect", GL_SAMPLER_2D_RECT, 1, 4); + } + + void uniformsByteSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QFETCH(QByteArray, fragShader); + QFETCH(QString, name); + QFETCH(int, type); + QFETCH(int, componentSize); + QFETCH(int, expectedByteSize); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); + QVERIFY(shaderProgram.link()); + + GLint location = shaderProgram.uniformLocation(name); + // WHEN + const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + ShaderUniform matchingUniform; + for (const ShaderUniform &u : activeUniforms) { + if (u.m_location == location) { + matchingUniform = u; + break; + } + } + + + // THEN + QCOMPARE(matchingUniform.m_location, location); + QCOMPARE(matchingUniform.m_type, GLuint(type)); + QCOMPARE(matchingUniform.m_size, componentSize); + + // WHEN + const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); + + // THEN + QCOMPARE(expectedByteSize, computedRawByteSize); + + // Restore + m_func->glUseProgram(0); + } + + + void useProgram() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); + + // THEN + QVERIFY(shaderProgram.link()); + + GLint currentProg = 0; + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + + // WHEN + m_glHelper.useProgram(shaderProgram.programId()); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QCOMPARE(GLuint(currentProg), shaderProgram.programId()); + + // WHEN + m_glHelper.useProgram(0); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + } + + void vertexAttribDivisor() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + } + + void vertexAttributePointer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); + + const int vertexCount = 99; + QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); + positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + positionBuffer.create(); + positionBuffer.bind(); + positionBuffer.allocate(vertexCount * sizeof(QVector3D)); + + QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); + texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + texCoordBuffer.create(); + texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); + + QOpenGLBuffer colorIndexBuffer(QOpenGLBuffer::VertexBuffer); + colorIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + colorIndexBuffer.create(); + colorIndexBuffer.allocate(vertexCount * sizeof(int)); + + // WHEN + shaderProgram.bind(); + positionBuffer.bind(); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); + + texCoordBuffer.bind(); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); + + colorIndexBuffer.bind(); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + m_glHelper.vertexAttributePointer(GL_INT, colorIndexLocation, 1, GL_INT, GL_TRUE, 0, 0); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void glUniform1fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat value = 883.0f; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1fv(location, 1, &value); + + // THEN + GLfloat setValue = 0.0f; + m_func->glGetUniformfv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[2] = { 383.0f, 427.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2fv(location, 1, values); + + // THEN + GLfloat setValues[2] = { 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3fv(location, 1, values); + + // THEN + GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4fv(location, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint value = 883; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1iv(location, 1, &value); + + // THEN + GLint setValue = 0; + m_func->glGetUniformiv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[2] = { 383, 427 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2iv(location, 1, values); + + // THEN + GLint setValues[2] = { 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[3] = { 572, 1340, 1584 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3iv(location, 1, values); + + // THEN + GLint setValues[3] = { 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[4] = { 454, 350, 883, 355 }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4iv(location, 1, values); + + // THEN + GLint setValues[4] = { 0, 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint value = 883U; + const GLint location = shaderProgram.uniformLocation("multiplier"); + m_glHelper.glUniform1uiv(location, 1, &value); + + // THEN + GLuint setValue = 0U; + m_func->glGetUniformuiv(shaderProgram.programId(), location, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[2] = { 383U, 427U }; + const GLint location = shaderProgram.uniformLocation("multiplierVec2"); + m_glHelper.glUniform2uiv(location, 1, values); + + // THEN + GLuint setValues[2] = { 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[3] = { 572U, 1340U, 1584U }; + const GLint location = shaderProgram.uniformLocation("multiplierVec3"); + m_glHelper.glUniform3uiv(location, 1, values); + + // THEN + GLuint setValues[3] = { 0U, 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[4] = { 454U, 350U, 883U, 355U }; + const GLint location = shaderProgram.uniformLocation("multiplierVec4"); + m_glHelper.glUniform4uiv(location, 1, values); + + // THEN + GLuint setValues[4] = { 0U, 0U, 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + const GLint location = shaderProgram.uniformLocation("m2"); + m_glHelper.glUniformMatrix2fv(location, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; + const GLint location = shaderProgram.uniformLocation("m3"); + m_glHelper.glUniformMatrix3fv(location, 1, values); + + // THEN + GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 9; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; + const GLint location = shaderProgram.uniformLocation("m4"); + m_glHelper.glUniformMatrix4fv(location, 1, values); + + // THEN + GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 16; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m23"); + m_glHelper.glUniformMatrix2x3fv(location, 1, values); + + // THEN + GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 6; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m32"); + m_glHelper.glUniformMatrix3x2fv(location, 1, values); + + // THEN + GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 6; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m24"); + m_glHelper.glUniformMatrix2x4fv(location, 1, values); + + // THEN + GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 8; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m42"); + m_glHelper.glUniformMatrix4x2fv(location, 1, values); + + // THEN + GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 8; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f}; + const GLint location = shaderProgram.uniformLocation("m34"); + m_glHelper.glUniformMatrix3x4fv(location, 1, values); + + // THEN + GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 12; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + const GLint location = shaderProgram.uniformLocation("m43"); + m_glHelper.glUniformMatrix4x3fv(location, 1, values); + + // THEN + GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), location, setValues); + for (int i = 0; i < 12; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + + void blitFramebuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + GLint maxSamples; + m_func->glGetIntegerv(GL_MAX_SAMPLES, &maxSamples); + if (maxSamples < 1) + QSKIP("This test requires an implementation that supports multisampled textures"); + + // GIVEN + GLuint fbos[2]; + GLuint fboTextures[2]; + + m_func->glGenFramebuffers(2, fbos); + m_func->glGenTextures(2, fboTextures); + + m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fboTextures[0]); + m_func->glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, maxSamples, GL_RGBA8, 10, 10, true); + m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); + + m_func->glBindTexture(GL_TEXTURE_2D, fboTextures[1]); + m_func->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 10, 10, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + m_func->glBindTexture(GL_TEXTURE_2D, 0); + + m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[1]); + m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[1], 0); + + GLenum status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); + QCOMPARE(status, GLenum(GL_FRAMEBUFFER_COMPLETE)); + + m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[0]); + m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[0], 0); + + status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); + QCOMPARE(status, GLenum(GL_FRAMEBUFFER_COMPLETE)); + + m_func->glEnable(GL_MULTISAMPLE); + m_func->glClearColor(0.2f, 0.2f, 0.2f, 0.2f); + m_func->glClear(GL_COLOR_BUFFER_BIT); + m_func->glDisable(GL_MULTISAMPLE); + + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); + + // WHEN + m_glHelper.blitFramebuffer(0,0,10,10,0,0,10,10, GL_COLOR_BUFFER_BIT, GL_NEAREST); + + m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[1]); + + GLuint result[10*10]; + m_func->glReadPixels(0,0,10,10,GL_RGBA, GL_UNSIGNED_BYTE, result); + + // THEN + GLuint v = (0.2f) * 255; + v = v | (v<<8) | (v<<16) | (v<<24); + for (GLuint value : result) { + QCOMPARE(value, v); + } + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + + m_func->glDeleteFramebuffers(2, fbos); + m_func->glDeleteTextures(2, fboTextures); + } + +#define ADD_GL_TYPE_ENTRY(Type, Expected) \ + QTest::newRow(#Type) << Type << Expected; + + void uniformTypeFromGLType_data() + { + QTest::addColumn("glType"); + QTest::addColumn("expected"); + + ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); + ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); + ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); + ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT, UniformType::UInt); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC2, UniformType::UIVec2); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC3, UniformType::UIVec3); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC4, UniformType::UIVec4); + ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x3, UniformType::Mat2x3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x4, UniformType::Mat2x4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x2, UniformType::Mat3x2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x2, UniformType::Mat4x2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x3, UniformType::Mat4x3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x4, UniformType::Mat3x4); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_RECT, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE, UniformType::Sampler); + } + + void uniformTypeFromGLType() + { + // GIVEN + QFETCH(int, glType); + QFETCH(UniformType, expected); + + // WHEN + UniformType computed = m_glHelper.uniformTypeFromGLType(glType); + + // THEN + QCOMPARE(computed, expected); + } + + void drawBuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.drawBuffer(GL_FRONT); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // THEN + GLint p; + m_func->glGetIntegerv(GL_DRAW_BUFFER, &p); + QCOMPARE(p, GL_FRONT); + } + + void readBuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.readBuffer(GL_FRONT); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_READ_BUFFER, &p); + QCOMPARE(p, GL_FRONT); + } + + void fenceSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + + // THEN + QVERIFY(sync != nullptr); + QCOMPARE(m_func->glIsSync(sync), GL_TRUE); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void clientWaitSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + QElapsedTimer t; + t.start(); + + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + + m_glHelper.clientWaitSync(sync, 1000000); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + qDebug() << t.nsecsElapsed(); + } + + void waitSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_func->glFlush(); + m_glHelper.waitSync(sync); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void wasSyncSignaled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_func->glFlush(); + m_glHelper.waitSync(sync); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // Shouldn't loop forever + while (!m_glHelper.wasSyncSignaled(sync)) + ; + } + + void deleteSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_glHelper.clientWaitSync(sync, GLuint64(-1)); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + QVERIFY(m_glHelper.wasSyncSignaled(sync) == true); + + // WHEN + m_glHelper.deleteSync(sync); + + // THEN + QCOMPARE(m_func->glIsSync(sync), GL_FALSE); + } + + void rasterMode() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 3.3 functions not supported"); + + m_func->glGetError(); + m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_POLYGON_MODE, &p); + QCOMPARE(p, GL_LINE); + } + +private: + QScopedPointer m_window; + QOpenGLContext m_glContext; + GraphicsHelperGL3_3 m_glHelper; + QOpenGLFunctions_3_3_Core *m_func = nullptr; + bool m_initializationSuccessful = false; +}; + +#endif + +int main(int argc, char *argv[]) +{ +#ifdef TEST_SHOULD_BE_PERFORMED + QGuiApplication app(argc, argv); + app.setAttribute(Qt::AA_Use96Dpi, true); + tst_GraphicsHelperGL3_3 tc; + QTEST_SET_MAIN_SOURCE_PATH + return QTest::qExec(&tc, argc, argv); +#endif + return 0; +} + +#ifdef TEST_SHOULD_BE_PERFORMED +#include "tst_graphicshelpergl3_3.moc" +#endif diff --git a/tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro b/tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro new file mode 100644 index 000000000..5ea881208 --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro @@ -0,0 +1,16 @@ +TEMPLATE = app + +TARGET = tst_graphicshelpergl4 + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += \ + tst_graphicshelpergl4.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp b/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp new file mode 100644 index 000000000..31024e1db --- /dev/null +++ b/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp @@ -0,0 +1,2583 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(QT_OPENGL_ES_2) && defined(QT_OPENGL_4_3) + +#define TEST_SHOULD_BE_PERFORMED 1 + +using namespace Qt3DRender; +using namespace Qt3DRender::Render; + +namespace { + +const QByteArray vertCode = QByteArrayLiteral( + "#version 430 core\n" \ + "layout(location = 1) in vec3 vertexPosition;\n" \ + "layout(location = 2) in vec2 vertexTexCoord;\n" \ + "out vec2 texCoord;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vertexTexCoord;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray vertCodeUniformBuffer = QByteArrayLiteral( + "#version 430 core\n" \ + "layout(location = 1) in vec3 vertexPosition;\n" \ + "layout(location = 2) in vec2 vertexTexCoord;\n" \ + "layout(location = 3) in int vertexColorIndex;\n" \ + "layout(location = 4) in double vertexTexCoordScale;\n" \ + "out vec2 texCoord;\n" \ + "flat out int colorIndex;\n" \ + "void main()\n" \ + "{\n" \ + " texCoord = vec2(vertexTexCoordScale * vertexTexCoord);\n" \ + " colorIndex = vertexColorIndex;\n" \ + " gl_Position = vec4(vertexPosition, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeFragOutputs = QByteArrayLiteral( + "#version 430 core\n" \ + "out vec4 color;\n" \ + "out vec2 temp;\n" \ + "void main()\n" \ + "{\n" \ + " color = vec4(1.0, 0.0, 0.0, 1.0);\n" \ + " temp = vec2(1.0, 0.3);\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloat = QByteArrayLiteral( + "#version 430 core\n" \ + "out vec4 color;\n" \ + "layout(location = 1) uniform float multiplier;\n" \ + "layout(location = 2) uniform vec2 multiplierVec2;\n" \ + "layout(location = 3) uniform vec3 multiplierVec3;\n" \ + "layout(location = 4) uniform vec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " vec4 randomMult = multiplierVec4 + vec4(multiplierVec3, 0.0) + vec4(multiplierVec2, 0.0, 0.0);\n" \ + " color = vec4(1.0, 0.0, 0.0, 1.0) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsInt = QByteArrayLiteral( + "#version 430 core\n" \ + "out ivec4 color;\n" \ + "layout(location = 1) uniform int multiplier;\n" \ + "layout(location = 2) uniform ivec2 multiplierVec2;\n" \ + "layout(location = 3) uniform ivec3 multiplierVec3;\n" \ + "layout(location = 4) uniform ivec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " ivec4 randomMult = multiplierVec4 + ivec4(multiplierVec3, 0) + ivec4(multiplierVec2, 0, 0);\n" \ + " color = ivec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsUInt = QByteArrayLiteral( + "#version 430 core\n" \ + "out uvec4 color;\n" \ + "layout(location = 1) uniform uint multiplier;\n" \ + "layout(location = 2) uniform uvec2 multiplierVec2;\n" \ + "layout(location = 3) uniform uvec3 multiplierVec3;\n" \ + "layout(location = 4) uniform uvec4 multiplierVec4;\n" \ + "void main()\n" \ + "{\n" \ + " uvec4 randomMult = multiplierVec4 + uvec4(multiplierVec3, 0) + uvec4(multiplierVec2, 0, 0);\n" \ + " color = uvec4(1, 0, 0, 1) * randomMult * multiplier;\n" \ + "}\n"); + +const QByteArray fragCodeUniformsFloatMatrices = QByteArrayLiteral( + "#version 430 core\n" \ + "out vec4 color;\n" \ + "layout(location = 1) uniform mat2 m2;\n" \ + "layout(location = 2) uniform mat2x3 m23;\n" \ + "layout(location = 3) uniform mat3x2 m32;\n" \ + "layout(location = 4) uniform mat2x4 m24;\n" \ + "layout(location = 5) uniform mat4x2 m42;\n" \ + "layout(location = 6) uniform mat3 m3;\n" \ + "layout(location = 7) uniform mat3x4 m34;\n" \ + "layout(location = 8) uniform mat4x3 m43;\n" \ + "layout(location = 9) uniform mat4 m4;\n" \ + "void main()\n" \ + "{\n" \ + " float lengthSum = m2[0][0] + m23[0][0] + m32[0][0] + m24[0][0] + m42[0][0] + m3[0][0] + m34[0][0] + m43[0][0] + m4[0][0];\n" \ + " color = vec4(1, 0, 0, 1) * lengthSum;\n" \ + "}\n"); + +const QByteArray fragCodeUniformBuffer = QByteArrayLiteral( + "#version 430 core\n" \ + "out vec4 color;\n" \ + "in vec2 texCoord;\n" \ + "flat in int colorIndex;\n" \ + "layout(binding = 2, std140) uniform ColorArray\n" \ + "{\n" \ + " vec4 colors[256];\n" \ + "};\n" \ + "void main()\n" \ + "{\n" \ + " color = colors[colorIndex] + vec4(texCoord.s, texCoord.t, 0.0, 1.0);\n" \ + "}\n"); + +const QByteArray fragCodeSamplers = QByteArrayLiteral( + "#version 430 core\n" \ + "in vec2 texCoord;\n" \ + "out vec4 color;\n" \ + "layout(location = 1) uniform sampler1D s1;\n" \ + "layout(location = 2) uniform sampler2D s2;\n" \ + "layout(location = 3) uniform sampler2DArray s2a;\n" \ + "layout(location = 4) uniform sampler3D s3;\n" \ + "layout(location = 5) uniform samplerCube scube;\n" \ + "layout(location = 6) uniform sampler2DRect srect;\n" \ + "void main()\n" \ + "{\n" \ + " color = vec4(1, 0, 0, 1) *" \ + " texture(s1, texCoord.x) *" \ + " texture(s2, texCoord) *" \ + " texture(s2a, vec3(texCoord, 0.0)) *" \ + " texture(s3, vec3(texCoord, 0.0)) *" \ + " texture(scube, vec3(texCoord, 0)) *" \ + " texture(srect, texCoord);\n" \ + "}\n"); + +const QByteArray fragCodeImages = QByteArrayLiteral( + "#version 430 core\n" \ + "in vec2 texCoord;\n" \ + "out vec4 color;\n" \ + "layout(location = 1, rgba32f) readonly uniform image1D s1;\n" \ + "layout(location = 2, rg16f) readonly uniform image2D s2;\n" \ + "layout(location = 3, r16f) readonly uniform image2DArray s2a;\n" \ + "layout(location = 4, rg8) readonly uniform image3D s3;\n" \ + "layout(location = 5, rgba16_snorm) readonly uniform imageCube scube;\n" \ + "layout(location = 6, rg16) readonly uniform image2DRect srect;\n" \ + "void main()\n" \ + "{\n" \ + " ivec2 coords = ivec2(texCoord);\n"\ + " color = vec4(1, 0, 0, 1) *" \ + " imageLoad(s1, coords.x) *" \ + " imageLoad(s2, coords) *" \ + " imageLoad(s2a, ivec3(coords, 0)) *" \ + " imageLoad(s3, ivec3(coords, 0)) *" \ + " imageLoad(scube, ivec3(coords, 0)) *" \ + " imageLoad(srect, coords);\n" \ + "}\n"); + +const QByteArray computeShader = QByteArrayLiteral( + "#version 430 core\n" \ + "uniform float particleStep;\n" \ + "uniform float finalCollisionFactor;\n" \ + "layout (local_size_x = 1024) in;\n" \ + "struct ParticleData\n" \ + "{\n" \ + " vec4 position;\n" \ + " vec4 direction;\n" \ + " vec4 color;\n" \ + "};\n" \ + "layout (std140, binding = 6) coherent buffer Particles\n" \ + "{\n" \ + " ParticleData particles[];\n" \ + "} data;\n" \ + "void main(void)\n" \ + "{\n" \ + " uint globalId = gl_GlobalInvocationID.x;\n" \ + " ParticleData currentParticle = data.particles[globalId];\n" \ + " currentParticle.position = currentParticle.position + currentParticle.direction * particleStep;\n" \ + " vec4 acceleration = normalize(vec4(0.0) - currentParticle.position) * finalCollisionFactor;\n" \ + " currentParticle.direction = currentParticle.direction + acceleration * particleStep;\n" \ + " data.particles[globalId] = currentParticle;\n" \ + "}"); + +} // anonymous + +class tst_GraphicsHelperGL4 : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void init() + { + m_window.reset(new QWindow); + m_window->setSurfaceType(QWindow::OpenGLSurface); + m_window->setGeometry(0, 0, 10, 10); + + QSurfaceFormat format; + format.setVersion(4, 3); + format.setProfile(QSurfaceFormat::CoreProfile); + format.setDepthBufferSize(24); + format.setSamples(4); + format.setStencilBufferSize(8); + m_window->setFormat(format); + m_glContext.setFormat(format); + + m_window->create(); + + if (!m_glContext.create()) { + qWarning() << "Failed to create OpenGL context"; + return; + } + + if (!m_glContext.makeCurrent(m_window.data())) { + qWarning() << "Failed to make OpenGL context current"; + return; + } + + if ((m_func = m_glContext.versionFunctions()) != nullptr) { + m_glHelper.initializeHelper(&m_glContext, m_func); + m_initializationSuccessful = true; + } + } + + void cleanup() + { + m_glContext.doneCurrent(); + } + + void alphaTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + // Deprecated + } + + void bindBufferBase() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint bufferId = 0; + // WHEN + m_func->glGenBuffers(1, &bufferId); + // THEN + QVERIFY(bufferId != 0); + + + // WHEN + m_func->glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferId); + m_glHelper.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, bufferId); + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundToPointBufferId = 0; + m_func->glGetIntegeri_v(GL_SHADER_STORAGE_BUFFER_BINDING, 2, &boundToPointBufferId); + QVERIFY(boundToPointBufferId == GLint(bufferId)); + + // Restore to sane state + m_func->glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); + m_func->glDeleteBuffers(1, &bufferId); + } + + void bindFragDataLocation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); + + // WHEN + QHash fragLocations; + fragLocations.insert(QStringLiteral("temp"), 2); + fragLocations.insert(QStringLiteral("color"), 1); + m_glHelper.bindFragDataLocation(shaderProgram.programId(), fragLocations); + + // THEN + QVERIFY(shaderProgram.link()); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + const GLint tempLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "temp"); + const GLint colorLocation = m_func->glGetFragDataLocation(shaderProgram.programId(), "color"); + QCOMPARE(tempLocation, 2); + QCOMPARE(colorLocation, 1); + } + + void bindFrameBufferAttachment() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + { + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color2; + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA32F); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture.create()) + qWarning() << "Texture creation failed"; + texture.allocateStorage(); + QVERIFY(texture.isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureAttachmentId = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0 + 2, + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, + &textureAttachmentId); + QCOMPARE(GLuint(textureAttachmentId), texture.textureId()); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + { + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::TargetCubeMap); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA32F); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture.create()) + qWarning() << "Texture creation failed"; + texture.allocateStorage(); + QVERIFY(texture.isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + { // Check All Faces + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + attachment.m_face = Qt3DRender::QAbstractTexture::AllFaces; + + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureIsLayered = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_LAYERED, + &textureIsLayered); + QCOMPARE(textureIsLayered, GL_TRUE); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + { // Check Specific Faces + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color0; + attachment.m_face = Qt3DRender::QAbstractTexture::CubeMapNegativeZ; + + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + error = m_func->glGetError(); + QVERIFY(error == 0); + GLint textureFace = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, + &textureFace); + QCOMPARE(textureFace, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); + GLint textureIsLayered = 0; + m_func->glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_FRAMEBUFFER_ATTACHMENT_LAYERED, + &textureIsLayered); + QCOMPARE(textureIsLayered, GL_FALSE); + + // Restore state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + } + } + + void bindFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBODraw); + + // THEN + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint boundindFBOId = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBORead); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // WHEN + m_glHelper.bindFrameBufferObject(fboId, GraphicsHelperInterface::FBOReadAndDraw); + + // THEN + error = m_func->glGetError(); + QVERIFY(error == 0); + boundindFBOId = 0; + m_func->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &boundindFBOId); + QVERIFY(GLuint(boundindFBOId) == fboId); + + // Cleanup + m_func->glDeleteFramebuffers(1, &fboId); + } + + void bindImageTexture() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + + // THEN + QVERIFY(texture.textureId() != 0 && texture.isCreated() && texture.isStorageAllocated()); + + // WHEN + m_glHelper.bindImageTexture(0, + texture.textureId(), + 0, + GL_FALSE, + 0, + GL_READ_WRITE, + GL_RGBA8UI); + + // THEN + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void bindShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Compute, computeShader); + QVERIFY(shaderProgram.link()); + + // WHEN + GLint index = m_func->glGetProgramResourceIndex(shaderProgram.programId(), + GL_SHADER_STORAGE_BLOCK, + "Particles"); + // THEN + GLint binding = -1; + GLenum prop = GL_BUFFER_BINDING; + m_func->glGetProgramResourceiv(shaderProgram.programId(), + GL_SHADER_STORAGE_BLOCK, + index, + 1, &prop, + 4, NULL, &binding); + QCOMPARE(binding, 6); + + // WHEN + m_glHelper.bindShaderStorageBlock(shaderProgram.programId(), index, 1); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + m_func->glGetProgramResourceiv(shaderProgram.programId(), + GL_SHADER_STORAGE_BLOCK, + index, + 1, &prop, + 4, NULL, &binding); + QCOMPARE(binding, 1); + } + + void bindUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + // WHEN + GLint index = m_func->glGetUniformBlockIndex(shaderProgram.programId(), "ColorArray"); + m_glHelper.bindUniformBlock(shaderProgram.programId(), index, 1); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void blendEquation() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLint equation = 0; + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_ADD); + + // WHEN + m_glHelper.blendEquation(GL_FUNC_REVERSE_SUBTRACT); + + // THEN + m_func->glGetIntegerv(GL_BLEND_EQUATION_RGB, &equation); + QCOMPARE(equation, GL_FUNC_REVERSE_SUBTRACT); + } + + void blendFunci() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLint destinationRgb = 0; + GLint destinationAlpha = 0; + GLint sourceRgb = 0; + GLint sourceAlpha = 0; + m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 4, &sourceRgb); + m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 4, &destinationRgb); + m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 4, &sourceAlpha); + m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 4, &destinationAlpha); + + // THEN + QCOMPARE(destinationAlpha, GL_ZERO); + QCOMPARE(destinationRgb, GL_ZERO); + QCOMPARE(sourceRgb, GL_ONE); + QCOMPARE(sourceAlpha, GL_ONE); + + // WHEN + m_glHelper.blendFunci(4, GL_SRC_COLOR, GL_ONE_MINUS_SRC_ALPHA); + + m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 4, &sourceRgb); + m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 4, &destinationRgb); + m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 4, &sourceAlpha); + m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 4, &destinationAlpha); + + // THEN + QCOMPARE(destinationAlpha, GL_ONE_MINUS_SRC_ALPHA); + QCOMPARE(destinationRgb, GL_ONE_MINUS_SRC_ALPHA); + QCOMPARE(sourceRgb, GL_SRC_COLOR); + QCOMPARE(sourceAlpha, GL_SRC_COLOR); + + // Reset default + m_glHelper.blendFunci(4, GL_ONE, GL_ZERO); + } + + void blendFuncSeparatei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLint destinationRgb = 0; + GLint destinationAlpha = 0; + GLint sourceRgb = 0; + GLint sourceAlpha = 0; + m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 2, &sourceRgb); + m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 2, &destinationRgb); + m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 2, &sourceAlpha); + m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 2, &destinationAlpha); + + // THEN + QCOMPARE(destinationAlpha, GL_ZERO); + QCOMPARE(destinationRgb, GL_ZERO); + QCOMPARE(sourceRgb, GL_ONE); + QCOMPARE(sourceAlpha, GL_ONE); + + // WHEN + m_glHelper.blendFuncSeparatei(2, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + m_func->glGetIntegeri_v(GL_BLEND_SRC_RGB, 2, &sourceRgb); + m_func->glGetIntegeri_v(GL_BLEND_DST_RGB, 2, &destinationRgb); + m_func->glGetIntegeri_v(GL_BLEND_SRC_ALPHA, 2, &sourceAlpha); + m_func->glGetIntegeri_v(GL_BLEND_DST_ALPHA, 2, &destinationAlpha); + + // THEN + QCOMPARE(destinationAlpha, GL_ONE_MINUS_SRC_ALPHA); + QCOMPARE(destinationRgb, GL_ONE_MINUS_SRC_COLOR); + QCOMPARE(sourceRgb, GL_SRC_COLOR); + QCOMPARE(sourceAlpha, GL_SRC_ALPHA); + + // Reset default + m_glHelper.blendFunci(4, GL_ONE, GL_ZERO); + } + + void boundFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + // THEN + GLint boundBuffer = 0; + m_func->glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundBuffer); + QCOMPARE(GLuint(boundBuffer), fboId); + + // THEN + QCOMPARE(m_glHelper.boundFrameBufferObject(), fboId); + + // Reset state + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void checkFrameBufferComplete() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + Attachment attachment; + attachment.m_point = QRenderTargetOutput::Color1; + + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + m_glHelper.bindFrameBufferAttachment(&texture, attachment); + + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + QVERIFY(m_glHelper.checkFrameBufferComplete()); + + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + } + + void clearBufferf() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + // Create 4 attachments + QOpenGLTexture *textures[4]; + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // Set Draw buffers + GLenum clearBufferEnum = GL_COLOR_ATTACHMENT3; + m_func->glDrawBuffers(1, &clearBufferEnum); + + const GLint bufferIndex = 0; // index of the element in the draw buffers + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // WHEN + const QVector4D clearValue1 = QVector4D(0.5f, 0.2f, 0.4f, 0.8f); + m_func->glClearBufferfv(GL_COLOR, bufferIndex, reinterpret_cast(&clearValue1)); + error = m_func->glGetError(); + QVERIFY(error == 0); + + // THEN + QVector colors(512 * 512); + textures[3]->bind(); + m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); + textures[3]->release(); + + for (const QVector4D c : colors) { + QVERIFY(c == clearValue1); + } + + // WHEN + const QVector4D clearValue2 = QVector4D(0.4f, 0.5f, 0.4f, 1.0f); + m_glHelper.clearBufferf(bufferIndex, clearValue2); + + // THEN + textures[3]->bind(); + m_func->glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, colors.data()); + textures[3]->release(); + for (const QVector4D c : colors) { + QVERIFY(c == clearValue2); + } + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void createFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // WHEN + const GLuint fboId = m_glHelper.createFrameBufferObject(); + + // THEN + QVERIFY(fboId != 0); + + // Restore + m_func->glDeleteFramebuffers(1, &fboId); + } + + void depthMask() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLboolean depthWritingEnabled = false; + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + + // THEN + QVERIFY(depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_FALSE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(!depthWritingEnabled); + + // WHEN + m_glHelper.depthMask(GL_TRUE); + + // THEN + m_func->glGetBooleanv(GL_DEPTH_WRITEMASK, &depthWritingEnabled); + QVERIFY(depthWritingEnabled); + } + + void depthTest() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_DEPTH_TEST); + m_func->glDepthFunc(GL_LESS); + + // WHEN + m_glHelper.depthTest(GL_LEQUAL); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + GLint depthMode = 0; + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LEQUAL); + + // WHEN + m_glHelper.depthTest(GL_LESS); + QVERIFY(m_func->glIsEnabled(GL_DEPTH_TEST)); + m_func->glGetIntegerv(GL_DEPTH_FUNC, &depthMode); + QCOMPARE(depthMode, GL_LESS); + } + + void disableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_CLIP_DISTANCE0 + 5); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + + // WHEN + m_glHelper.disableClipPlane(5); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 5)); + } + + void disablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glEnablei(GL_BLEND, 2); + + // THEN + QVERIFY(m_func->glIsEnabledi(GL_BLEND, 2)); + + // WHEN + m_glHelper.disablei(GL_BLEND, 2); + + // THEN + QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 2)); + } + + void disablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_PRIMITIVE_RESTART); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + + // WHEN + m_glHelper.disablePrimitiveRestart(); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + } + + void drawBuffers() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fboId); + QOpenGLTexture *textures[4]; + + // Create 4 attachments + for (int i = 0; i < 4; ++i) { + Attachment attachment; + attachment.m_point = static_cast(i); + + QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D); + textures[i] = texture; + texture->setSize(512, 512); + texture->setFormat(QOpenGLTexture::RGBA32F); + texture->setMinificationFilter(QOpenGLTexture::Linear); + texture->setMagnificationFilter(QOpenGLTexture::Linear); + texture->setWrapMode(QOpenGLTexture::ClampToEdge); + if (!texture->create()) + qWarning() << "Texture creation failed"; + texture->allocateStorage(); + QVERIFY(texture->isStorageAllocated()); + GLint error = m_func->glGetError(); + QVERIFY(error == 0); + m_glHelper.bindFrameBufferAttachment(texture, attachment); + } + // THEN + GLenum status = m_func->glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + // WHEN + GLenum bufferEnum = GL_COLOR_ATTACHMENT4; + m_func->glDrawBuffers(1, &bufferEnum); + + // THEN + GLint enumValue = -1; + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT4); + + // WHEN + GLint newBufferEnum = 2; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // WHEN + newBufferEnum = 0; + m_glHelper.drawBuffers(1, &newBufferEnum); + + // THEN + m_func->glGetIntegerv(GL_DRAW_BUFFER0, &enumValue); + QCOMPARE(enumValue, GL_COLOR_ATTACHMENT0 + newBufferEnum); + + // Restore + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glDeleteFramebuffers(1, &fboId); + for (int i = 0; i < 4; ++i) + delete textures[i]; + } + + void enableClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_CLIP_DISTANCE0 + 4); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + + // WHEN + m_glHelper.enableClipPlane(4); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_CLIP_DISTANCE0 + 4)); + } + + void enablei() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisablei(GL_BLEND, 4); + + // THEN + QVERIFY(!m_func->glIsEnabledi(GL_BLEND, 4)); + + // WHEN + m_glHelper.enablei(GL_BLEND, 4); + + // THEN + QVERIFY(m_func->glIsEnabledi(GL_BLEND, 4)); + } + + void enablePrimitiveRestart() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_PRIMITIVE_RESTART); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + + // WHEN + m_glHelper.enablePrimitiveRestart(883); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PRIMITIVE_RESTART)); + GLint restartIndex = 0; + m_func->glGetIntegerv(GL_PRIMITIVE_RESTART_INDEX, &restartIndex); + QCOMPARE(restartIndex, 883); + + // Restore + m_func->glDisable(GL_PRIMITIVE_RESTART); + } + + void enableVertexAttribute() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + shaderProgram.bind(); + + // WHEN + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void frontFace() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glFrontFace(GL_CW); + + // THEN + GLint face = 0; + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CW); + + // WHEN + m_glHelper.frontFace(GL_CCW); + + // THEN + m_func->glGetIntegerv(GL_FRONT_FACE, &face); + QCOMPARE(face, GL_CCW); + } + + void getRenderBufferDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint renderBufferId = 0; + m_func->glGenRenderbuffers(1, &renderBufferId); + QVERIFY(renderBufferId != 0); + + // WHEN + m_func->glBindRenderbuffer(GL_RENDERBUFFER, renderBufferId); + m_func->glRenderbufferStorage(GL_RENDERBUFFER, GL_SRGB8_ALPHA8, 512, 512); + m_func->glBindRenderbuffer(GL_RENDERBUFFER, 0); + const QSize dimensions = m_glHelper.getRenderBufferDimensions(renderBufferId); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + + // Restore + m_func->glDeleteRenderbuffers(1, &renderBufferId); + } + + void getTextureDimensions() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLTexture texture(QOpenGLTexture::Target2D); + texture.setSize(512, 512); + texture.setFormat(QOpenGLTexture::RGBA8U); + texture.setMinificationFilter(QOpenGLTexture::Linear); + texture.setMagnificationFilter(QOpenGLTexture::Linear); + texture.create(); + texture.allocateStorage(); + + // WHEN + const QSize dimensions = m_glHelper.getTextureDimensions(texture.textureId(), GL_TEXTURE_2D); + + // THEN + QCOMPARE(dimensions, QSize(512, 512)); + } + + void pointSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glEnable(GL_PROGRAM_POINT_SIZE); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); + GLfloat size = 0; + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 1.0f); + + // WHEN + m_glHelper.pointSize(false, 0.5f); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_PROGRAM_POINT_SIZE)); + m_func->glGetFloatv(GL_POINT_SIZE, &size); + QCOMPARE(size, 0.5f); + } + + void maxClipPlaneCount() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLint maxCount = -1; + m_func->glGetIntegerv(GL_MAX_CLIP_PLANES, &maxCount); + + // THEN + QCOMPARE(maxCount, m_glHelper.maxClipPlaneCount()); + } + + void programUniformBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + // WHEN + const QVector activeUniformBlocks = m_glHelper.programUniformBlocks(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniformBlocks.size(), 1); + const ShaderUniformBlock uniformBlock = activeUniformBlocks.first(); + + QCOMPARE(uniformBlock.m_activeUniformsCount, 1); + QCOMPARE(uniformBlock.m_name, QStringLiteral("ColorArray")); + QCOMPARE(uniformBlock.m_binding, 2); + } + + void programAttributesAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeSamplers); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeAttributes = m_glHelper.programAttributesAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeAttributes.size(), 2); + std::sort(activeAttributes.begin(), activeAttributes.end(), [] (const ShaderAttribute &a, const ShaderAttribute &b) { return a.m_location < b.m_location; }); + + const ShaderAttribute attribute1 = activeAttributes.at(0); + QCOMPARE(attribute1.m_name, QStringLiteral("vertexPosition")); + QCOMPARE(attribute1.m_size, 1); + QCOMPARE(attribute1.m_location, 1); + QCOMPARE(attribute1.m_type, GLenum(GL_FLOAT_VEC3)); + + const ShaderAttribute attribute2 = activeAttributes.at(1); + QCOMPARE(attribute2.m_name, QStringLiteral("vertexTexCoord")); + QCOMPARE(attribute2.m_size, 1); + QCOMPARE(attribute2.m_location, 2); + QCOMPARE(attribute2.m_type, GLenum(GL_FLOAT_VEC2)); + } + + void programUniformsAndLocations() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + + // THEN + QCOMPARE(activeUniforms.size(), 4); + std::sort(activeUniforms.begin(), activeUniforms.end(), [] (const ShaderUniform &a, const ShaderUniform &b) { return a.m_location < b.m_location; }); + + const ShaderUniform uniform1 = activeUniforms.at(0); + QCOMPARE(uniform1.m_location, 1); + QCOMPARE(uniform1.m_offset, -1); + QCOMPARE(uniform1.m_blockIndex, -1); + QCOMPARE(uniform1.m_arrayStride, -1); + QCOMPARE(uniform1.m_matrixStride, -1); + QCOMPARE(uniform1.m_size, 1); + QCOMPARE(uniform1.m_type, GLenum(GL_FLOAT)); + QCOMPARE(uniform1.m_name, QStringLiteral("multiplier")); + + const ShaderUniform uniform2 = activeUniforms.at(1); + QCOMPARE(uniform2.m_location, 2); + QCOMPARE(uniform2.m_offset, -1); + QCOMPARE(uniform2.m_blockIndex, -1); + QCOMPARE(uniform2.m_arrayStride, -1); + QCOMPARE(uniform2.m_matrixStride, -1); + QCOMPARE(uniform2.m_size, 1); + QCOMPARE(uniform2.m_type, GLenum(GL_FLOAT_VEC2)); + QCOMPARE(uniform2.m_name, QStringLiteral("multiplierVec2")); + + const ShaderUniform uniform3 = activeUniforms.at(2); + QCOMPARE(uniform3.m_location, 3); + QCOMPARE(uniform3.m_offset, -1); + QCOMPARE(uniform3.m_blockIndex, -1); + QCOMPARE(uniform3.m_arrayStride, -1); + QCOMPARE(uniform3.m_matrixStride, -1); + QCOMPARE(uniform3.m_size, 1); + QCOMPARE(uniform3.m_type, GLenum(GL_FLOAT_VEC3)); + QCOMPARE(uniform3.m_name, QStringLiteral("multiplierVec3")); + + const ShaderUniform uniform4 = activeUniforms.at(3); + QCOMPARE(uniform4.m_location, 4); + QCOMPARE(uniform4.m_offset, -1); + QCOMPARE(uniform4.m_blockIndex, -1); + QCOMPARE(uniform4.m_arrayStride, -1); + QCOMPARE(uniform4.m_matrixStride, -1); + QCOMPARE(uniform4.m_size, 1); + QCOMPARE(uniform4.m_type, GLenum(GL_FLOAT_VEC4)); + QCOMPARE(uniform4.m_name, QStringLiteral("multiplierVec4")); + } + + void programShaderStorageBlock() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Compute, computeShader); + QVERIFY(shaderProgram.link()); + + // WHEN + const QVector activeShaderStorageBlocks = m_glHelper.programShaderStorageBlocks(shaderProgram.programId()); + + // THEN + QVERIFY(activeShaderStorageBlocks.size() == 1); + ShaderStorageBlock block = activeShaderStorageBlocks.first(); + QCOMPARE(block.m_name, QStringLiteral("Particles")); + QCOMPARE(block.m_activeVariablesCount, 3); + QCOMPARE(block.m_index, 0); + QCOMPARE(block.m_binding, 6); + QCOMPARE(block.m_size, (4 + 4 + 4) * 4); + } + + void releaseFrameBufferObject() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint fboId; + m_func->glGenFramebuffers(1, &fboId); + + // THEN + QVERIFY(fboId != 0); + + // WHEN + m_glHelper.releaseFrameBufferObject(fboId); + + // THEN + QVERIFY(!m_func->glIsFramebuffer(fboId)); + } + + void setMSAAEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_MULTISAMPLE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_MULTISAMPLE)); + + // WHEN + m_glHelper.setMSAAEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_MULTISAMPLE)); + } + + void setAlphaCoverageEnabled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + + // WHEN + m_glHelper.setAlphaCoverageEnabled(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE)); + } + + void setClipPlane() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + // Deprecated in GL 4 + } + + void setSeamlessCubemap() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + } + + void setVerticesPerPatch() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + m_func->glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(true); + + // THEN + QVERIFY(m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + + // WHEN + m_glHelper.setSeamlessCubemap(false); + + // THEN + QVERIFY(!m_func->glIsEnabled(GL_TEXTURE_CUBE_MAP_SEAMLESS)); + } + + void supportsFeature() + { + for (int i = 0; i <= GraphicsHelperInterface::Fences; ++i) + QVERIFY(m_glHelper.supportsFeature(static_cast(i))); + } + + +#define ADD_UNIFORM_ENTRY(FragShader, Type, Location, ComponentSize, ExpectedRawSize) \ + QTest::newRow(#FragShader"_"#Type) << FragShader << Type << Location << ComponentSize << ExpectedRawSize; + + void uniformsByteSize_data() + { + QTest::addColumn("fragShader"); + QTest::addColumn("type"); + QTest::addColumn("location"); + QTest::addColumn("componentSize"); + QTest::addColumn("expectedByteSize"); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT, 1, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT_VEC2, 2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT_VEC3, 3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloat, GL_FLOAT_VEC4, 4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT, 1, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT_VEC2, 2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT_VEC3, 3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsInt, GL_INT_VEC4, 4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT, 1, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT_VEC2, 2, 1, 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT_VEC3, 3, 1, 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsUInt, GL_UNSIGNED_INT_VEC4, 4, 1, 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT2, 1, 1, 4 * 2 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT2x3, 2, 1, 4 * 2 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT3x2, 3, 1, 4 * 3 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT2x4, 4, 1, 4 * 2 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT4x2, 5, 1, 4 * 4 * 2); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT3, 6, 1, 4 * 3 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT3x4, 7, 1, 4 * 3 * 4); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT4x3, 8, 1, 4 * 4 * 3); + ADD_UNIFORM_ENTRY(fragCodeUniformsFloatMatrices, GL_FLOAT_MAT4, 9, 1, 4 * 4 * 4); + + ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_1D, 1, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_2D, 2, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_2D_ARRAY, 3, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_3D, 4, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_CUBE, 5, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeSamplers, GL_SAMPLER_2D_RECT, 6, 1, 4); + + ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_1D, 1, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_2D, 2, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_2D_ARRAY, 3, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_3D, 4, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_CUBE, 5, 1, 4); + ADD_UNIFORM_ENTRY(fragCodeImages, GL_IMAGE_2D_RECT, 6, 1, 4); + } + + void uniformsByteSize() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QFETCH(QByteArray, fragShader); + QFETCH(int, type); + QFETCH(int, location); + QFETCH(int, componentSize); + QFETCH(int, expectedByteSize); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragShader); + QVERIFY(shaderProgram.link()); + + // WHEN + const QVector activeUniforms = m_glHelper.programUniformsAndLocations(shaderProgram.programId()); + ShaderUniform matchingUniform; + for (const ShaderUniform &u : activeUniforms) { + if (u.m_location == location) { + matchingUniform = u; + break; + } + } + + // THEN + QCOMPARE(matchingUniform.m_location, location); + QCOMPARE(matchingUniform.m_type, GLuint(type)); + QCOMPARE(matchingUniform.m_size, componentSize); + + // WHEN + const int computedRawByteSize = m_glHelper.uniformByteSize(matchingUniform); + + // THEN + QCOMPARE(expectedByteSize, computedRawByteSize); + + // Restore + m_func->glUseProgram(0); + } + + void useProgram() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeFragOutputs); + + // THEN + QVERIFY(shaderProgram.link()); + + GLint currentProg = 0; + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + + // WHEN + m_glHelper.useProgram(shaderProgram.programId()); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QCOMPARE(GLuint(currentProg), shaderProgram.programId()); + + // WHEN + m_glHelper.useProgram(0); + + // THEN + m_func->glGetIntegerv(GL_CURRENT_PROGRAM, ¤tProg); + QVERIFY(currentProg == 0); + } + + void vertexAttribDivisor() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + } + + void vertexAttributePointer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLVertexArrayObject vao; + vao.create(); + QOpenGLVertexArrayObject::Binder binder(&vao); + + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCodeUniformBuffer); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformBuffer); + QVERIFY(shaderProgram.link()); + + GLint positionLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexPosition"); + GLint texCoordLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoord"); + GLint colorIndexLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexColorIndex"); + GLint texCoordScaleLocation = m_func->glGetAttribLocation(shaderProgram.programId(), "vertexTexCoordScale"); + + const int vertexCount = 99; + QOpenGLBuffer positionBuffer(QOpenGLBuffer::VertexBuffer); + positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + positionBuffer.create(); + positionBuffer.bind(); + positionBuffer.allocate(vertexCount * sizeof(QVector3D)); + + QOpenGLBuffer texCoordBuffer(QOpenGLBuffer::VertexBuffer); + texCoordBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + texCoordBuffer.create(); + texCoordBuffer.allocate(vertexCount * sizeof(QVector2D)); + + QOpenGLBuffer colorIndexBuffer(QOpenGLBuffer::VertexBuffer); + colorIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + colorIndexBuffer.create(); + colorIndexBuffer.allocate(vertexCount * sizeof(int)); + + QOpenGLBuffer scaleBuffer(QOpenGLBuffer::VertexBuffer); + scaleBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); + scaleBuffer.create(); + scaleBuffer.allocate(vertexCount * sizeof(double)); + + // WHEN + shaderProgram.bind(); + positionBuffer.bind(); + m_glHelper.enableVertexAttributeArray(positionLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC3, positionLocation, 3, GL_FLOAT, GL_TRUE, 0, 0); + + texCoordBuffer.bind(); + m_glHelper.enableVertexAttributeArray(texCoordLocation); + m_glHelper.vertexAttributePointer(GL_FLOAT_VEC2, texCoordLocation, 2, GL_FLOAT, GL_TRUE, 0, 0); + + colorIndexBuffer.bind(); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + m_glHelper.vertexAttributePointer(GL_INT, colorIndexLocation, 1, GL_INT, GL_TRUE, 0, 0); + + scaleBuffer.bind(); + m_glHelper.enableVertexAttributeArray(colorIndexLocation); + m_glHelper.vertexAttributePointer(GL_DOUBLE, texCoordScaleLocation, 1, GL_DOUBLE, GL_TRUE, 0, 0); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void glUniform1fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat value = 883.0f; + m_glHelper.glUniform1fv(1, 1, &value); + + // THEN + GLfloat setValue = 0.0f; + m_func->glGetUniformfv(shaderProgram.programId(), 1, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[2] = { 383.0f, 427.0f }; + m_glHelper.glUniform2fv(2, 1, values); + + // THEN + GLfloat setValues[2] = { 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 2, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[3] = { 572.0f, 1340.0f, 1584.0f }; + m_glHelper.glUniform3fv(3, 1, values); + + // THEN + GLfloat setValues[3] = { 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 3, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloat); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + m_glHelper.glUniform4fv(4, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 4, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(setValues[i], values[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint value = 883; + m_glHelper.glUniform1iv(1, 1, &value); + + // THEN + GLint setValue = 0; + m_func->glGetUniformiv(shaderProgram.programId(), 1, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[2] = { 383, 427 }; + m_glHelper.glUniform2iv(2, 1, values); + + // THEN + GLint setValues[2] = { 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), 2, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[3] = { 572, 1340, 1584 }; + m_glHelper.glUniform3iv(3, 1, values); + + // THEN + GLint setValues[3] = { 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), 3, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4iv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLint values[4] = { 454, 350, 883, 355 }; + m_glHelper.glUniform4iv(4, 1, values); + + // THEN + GLint setValues[4] = { 0, 0, 0, 0 }; + m_func->glGetUniformiv(shaderProgram.programId(), 4, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform1uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint value = 883U; + m_glHelper.glUniform1uiv(1, 1, &value); + + // THEN + GLuint setValue = 0U; + m_func->glGetUniformuiv(shaderProgram.programId(), 1, &setValue); + QCOMPARE(value, setValue); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform2uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[2] = { 383U, 427U }; + m_glHelper.glUniform2uiv(2, 1, values); + + // THEN + GLuint setValues[2] = { 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), 2, setValues); + for (int i = 0; i < 2; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform3uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[3] = { 572U, 1340U, 1584U }; + m_glHelper.glUniform3uiv(3, 1, values); + + // THEN + GLuint setValues[3] = { 0U, 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), 3, setValues); + for (int i = 0; i < 3; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniform4uiv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsUInt); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLuint values[4] = { 454U, 350U, 883U, 355U }; + m_glHelper.glUniform4uiv(4, 1, values); + + // THEN + GLuint setValues[4] = { 0U, 0U, 0U, 0U }; + m_func->glGetUniformuiv(shaderProgram.programId(), 4, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[4] = { 454.0f, 350.0f, 883.0f, 355.0f }; + m_glHelper.glUniformMatrix2fv(1, 1, values); + + // THEN + GLfloat setValues[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 1, setValues); + for (int i = 0; i < 4; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[9] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f }; + m_glHelper.glUniformMatrix3fv(6, 1, values); + + // THEN + GLfloat setValues[9] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 6, setValues); + for (int i = 0; i < 9; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[16] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f, 1200.0f, 427.0f, 396.0f, 1603.0f, 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 327.0f }; + m_glHelper.glUniformMatrix4fv(9, 1, values); + + // THEN + GLfloat setValues[16] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 9, setValues); + for (int i = 0; i < 16; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + m_glHelper.glUniformMatrix2x3fv(2, 1, values); + + // THEN + GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 2, setValues); + for (int i = 0; i < 6; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[6] = { 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + m_glHelper.glUniformMatrix3x2fv(3, 1, values); + + // THEN + GLfloat setValues[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 3, setValues); + for (int i = 0; i < 6; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix2x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + m_glHelper.glUniformMatrix2x4fv(4, 1, values); + + // THEN + GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 4, setValues); + for (int i = 0; i < 8; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4x2fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[8] = { 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + m_glHelper.glUniformMatrix4x2fv(5, 1, values); + + // THEN + GLfloat setValues[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 5, setValues); + for (int i = 0; i < 8; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix3x4fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 5.3f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f,}; + m_glHelper.glUniformMatrix3x4fv(7, 1, values); + + // THEN + GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 7, setValues); + for (int i = 0; i < 12; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + void glUniformMatrix4x3fv() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + QOpenGLShaderProgram shaderProgram; + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex, vertCode); + shaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment, fragCodeUniformsFloatMatrices); + QVERIFY(shaderProgram.link()); + + // WHEN + m_func->glUseProgram(shaderProgram.programId()); + GLfloat values[12] = { 55.0f, 5.7f, 383.0f, 6.2f, 383.0f, 427.0f, 454.0f, 350.0f, 883.0f, 355.0f, 1340.0f, 1584.0f}; + m_glHelper.glUniformMatrix4x3fv(8, 1, values); + + // THEN + GLfloat setValues[12] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; + m_func->glGetUniformfv(shaderProgram.programId(), 8, setValues); + for (int i = 0; i < 12; ++i) + QCOMPARE(values[i], setValues[i]); + + // Restore + m_func->glUseProgram(0); + } + + + void blitFramebuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + // GIVEN + GLuint fbos[2]; + GLuint fboTextures[2]; + + m_func->glGenFramebuffers(2, fbos); + m_func->glGenTextures(2, fboTextures); + + m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fboTextures[0]); + m_func->glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA8, 10, 10, true); + m_func->glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); + + m_func->glBindTexture(GL_TEXTURE_2D, fboTextures[1]); + m_func->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 10, 10, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + m_func->glBindTexture(GL_TEXTURE_2D, 0); + + m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[1]); + m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[1], 0); + + GLenum status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + m_func->glBindFramebuffer(GL_FRAMEBUFFER, fbos[0]); + m_func->glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, fboTextures[0], 0); + + status = m_func->glCheckFramebufferStatus(GL_FRAMEBUFFER); + QVERIFY(status == GL_FRAMEBUFFER_COMPLETE); + + m_func->glEnable(GL_MULTISAMPLE); + m_func->glClearColor(0.2f, 0.2f, 0.2f, 0.2f); + m_func->glClear(GL_COLOR_BUFFER_BIT); + m_func->glDisable(GL_MULTISAMPLE); + + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); + + // WHEN + m_glHelper.blitFramebuffer(0,0,10,10,0,0,10,10, GL_COLOR_BUFFER_BIT, GL_NEAREST); + + m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[1]); + + GLuint result[10*10]; + m_func->glReadPixels(0,0,10,10,GL_RGBA, GL_UNSIGNED_BYTE, result); + + // THEN + GLuint v = (0.2f) * 255; + v = v | (v<<8) | (v<<16) | (v<<24); + for (GLuint value : result) { + QCOMPARE(value, v); + } + m_func->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_func->glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + + m_func->glDeleteFramebuffers(2, fbos); + m_func->glDeleteTextures(2, fboTextures); + } + +#define ADD_GL_TYPE_ENTRY(Type, Expected) \ + QTest::newRow(#Type) << Type << Expected; + + void uniformTypeFromGLType_data() + { + QTest::addColumn("glType"); + QTest::addColumn("expected"); + + ADD_GL_TYPE_ENTRY(GL_FLOAT, UniformType::Float); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC2, UniformType::Vec2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_VEC3, UniformType::Vec3); + ADD_GL_TYPE_ENTRY(GL_INT, UniformType::Int); + ADD_GL_TYPE_ENTRY(GL_INT_VEC2, UniformType::IVec2); + ADD_GL_TYPE_ENTRY(GL_INT_VEC3, UniformType::IVec3); + ADD_GL_TYPE_ENTRY(GL_INT_VEC4, UniformType::IVec4); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT, UniformType::UInt); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC2, UniformType::UIVec2); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC3, UniformType::UIVec3); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_VEC4, UniformType::UIVec4); + ADD_GL_TYPE_ENTRY(GL_BOOL, UniformType::Bool); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC2, UniformType::BVec2); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC3, UniformType::BVec3); + ADD_GL_TYPE_ENTRY(GL_BOOL_VEC4, UniformType::BVec4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2, UniformType::Mat2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3, UniformType::Mat3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4, UniformType::Mat4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x3, UniformType::Mat2x3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT2x4, UniformType::Mat2x4); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x2, UniformType::Mat3x2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x2, UniformType::Mat4x2); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT4x3, UniformType::Mat4x3); + ADD_GL_TYPE_ENTRY(GL_FLOAT_MAT3x4, UniformType::Mat3x4); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_1D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_RECT, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_2D_ARRAY_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_MAP_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_INT_SAMPLER_CUBE_MAP_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_1D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_3D, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_BUFFER, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY, UniformType::Sampler); + ADD_GL_TYPE_ENTRY(GL_IMAGE_1D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_2D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_3D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_RECT, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_CUBE, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_BUFFER, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_1D_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_CUBE_MAP_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_MULTISAMPLE, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_IMAGE_2D_MULTISAMPLE_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_1D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D, UniformType::Image); ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_3D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_RECT, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_CUBE, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_BUFFER, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_1D_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_CUBE_MAP_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_MULTISAMPLE, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_1D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_3D, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_RECT, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_CUBE, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_BUFFER, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_1D_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE, UniformType::Image); + ADD_GL_TYPE_ENTRY(GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY, UniformType::Image); + } + + void uniformTypeFromGLType() + { + // GIVEN + QFETCH(int, glType); + QFETCH(UniformType, expected); + + // WHEN + UniformType computed = m_glHelper.uniformTypeFromGLType(glType); + + // THEN + QCOMPARE(computed, expected); + } + + void drawBuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.drawBuffer(GL_FRONT); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // THEN + GLint p; + m_func->glGetIntegerv(GL_DRAW_BUFFER, &p); + QCOMPARE(p, GL_FRONT); + } + + void readBuffer() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + m_glHelper.readBuffer(GL_FRONT); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_READ_BUFFER, &p); + QCOMPARE(p, GL_FRONT); + } + + void fenceSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + + // THEN + QVERIFY(sync != nullptr); + QCOMPARE(m_func->glIsSync(sync), GL_TRUE); + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void clientWaitSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + QElapsedTimer t; + t.start(); + + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + + m_glHelper.clientWaitSync(sync, 1000000); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + qDebug() << t.nsecsElapsed(); + } + + void waitSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_func->glFlush(); + m_glHelper.waitSync(sync); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + } + + void wasSyncSignaled() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_func->glFlush(); + m_glHelper.waitSync(sync); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + + // Shouldn't loop forever + while (!m_glHelper.wasSyncSignaled(sync)) + ; + } + + void deleteSync() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 Core functions not supported"); + + m_func->glGetError(); + + // WHEN + GLsync sync = reinterpret_cast(m_glHelper.fenceSync()); + m_glHelper.clientWaitSync(sync, GLuint64(-1)); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + QVERIFY(m_glHelper.wasSyncSignaled(sync) == true); + + // WHEN + m_glHelper.deleteSync(sync); + + // THEN + QCOMPARE(m_func->glIsSync(sync), GL_FALSE); + } + + void rasterMode() + { + if (!m_initializationSuccessful) + QSKIP("Initialization failed, OpenGL 4.3 functions not supported"); + + m_func->glGetError(); + m_glHelper.rasterMode(GL_FRONT_AND_BACK, GL_LINE); + + // THEN + const GLint error = m_func->glGetError(); + QVERIFY(error == 0); + GLint p; + m_func->glGetIntegerv(GL_POLYGON_MODE, &p); + QCOMPARE(p, GL_LINE); + } + +private: + QScopedPointer m_window; + QOpenGLContext m_glContext; + GraphicsHelperGL4 m_glHelper; + QOpenGLFunctions_4_3_Core *m_func = nullptr; + bool m_initializationSuccessful = false; +}; + +#endif + +int main(int argc, char *argv[]) +{ +#ifdef TEST_SHOULD_BE_PERFORMED + QGuiApplication app(argc, argv); + app.setAttribute(Qt::AA_Use96Dpi, true); + tst_GraphicsHelperGL4 tc; + QTEST_SET_MAIN_SOURCE_PATH + return QTest::qExec(&tc, argc, argv); +#endif + return 0; +} + +#ifdef TEST_SHOULD_BE_PERFORMED +#include "tst_graphicshelpergl4.moc" +#endif diff --git a/tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro b/tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro new file mode 100644 index 000000000..106e7a263 --- /dev/null +++ b/tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro @@ -0,0 +1,14 @@ +TEMPLATE = app + +TARGET = tst_materialparametergathererjob + +QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_materialparametergathererjob.cpp + +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp b/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp new file mode 100644 index 000000000..e6b78c47b --- /dev/null +++ b/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp @@ -0,0 +1,801 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class TestAspect : public Qt3DRender::QRenderAspect +{ +public: + TestAspect(Qt3DCore::QNode *root) + : Qt3DRender::QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) + , m_jobManager(new Qt3DCore::QAspectJobManager()) + { + Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); + QRenderAspect::onRegistered(); + + QVector nodes; + Qt3DCore::QNodeVisitor v; + v.traverse(root, [&nodes](Qt3DCore::QNode *node) { + Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(node); + d->m_typeInfo = const_cast(Qt3DCore::QNodePrivate::findStaticMetaObject(node->metaObject())); + d->m_hasBackendNode = true; + nodes << node; + }); + + for (const auto node: nodes) + d_func()->createBackendNode({ + node->id(), + Qt3DCore::QNodePrivate::get(node)->m_typeInfo, + Qt3DCore::NodeTreeChange::Added, + node + }); + + const auto handles = nodeManagers()->techniqueManager()->activeHandles(); + for (const auto &handle: handles) { + Render::Technique *technique = nodeManagers()->techniqueManager()->data(handle); + technique->setCompatibleWithRenderer(true); + } + } + + ~TestAspect() + { + QRenderAspect::onUnregistered(); + } + + Qt3DRender::Render::NodeManagers *nodeManagers() const + { + return d_func()->m_renderer->nodeManagers(); + } + + void initializeRenderer() + { + d_func()->m_renderer->initialize(); + } + + Render::MaterialParameterGathererJobPtr materialGathererJob() const + { + Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); + job->setNodeManagers(nodeManagers()); + return job; + } + + void onRegistered() { QRenderAspect::onRegistered(); } + void onUnregistered() { QRenderAspect::onUnregistered(); } + +private: + QScopedPointer m_jobManager; +}; + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +namespace { + +class TestMaterial : public Qt3DRender::QMaterial +{ + Q_OBJECT +public: + explicit TestMaterial(Qt3DCore::QNode *parent = nullptr) + : Qt3DRender::QMaterial(parent) + , m_effect(new Qt3DRender::QEffect()) + , m_gl3Technique(new Qt3DRender::QTechnique()) + , m_gl2Technique(new Qt3DRender::QTechnique()) + , m_es2Technique(new Qt3DRender::QTechnique()) + , m_gl3Pass(new Qt3DRender::QRenderPass()) + , m_gl2Pass(new Qt3DRender::QRenderPass()) + , m_es2Pass(new Qt3DRender::QRenderPass()) + , m_gl3Program(new Qt3DRender::QShaderProgram()) + , m_gl2es2Program(new Qt3DRender::QShaderProgram()) + { + m_gl3Pass->setShaderProgram(m_gl3Program); + m_gl2Pass->setShaderProgram(m_gl2es2Program); + m_es2Pass->setShaderProgram(m_gl2es2Program); + + m_gl3Technique->addRenderPass(m_gl3Pass); + m_gl2Technique->addRenderPass(m_gl2Pass); + m_es2Technique->addRenderPass(m_es2Pass); + + m_effect->addTechnique(m_gl3Technique); + m_effect->addTechnique(m_gl2Technique); + m_effect->addTechnique(m_es2Technique); + + setEffect(m_effect); + } + + Qt3DRender::QTechnique *gl3Technique() const { return m_gl3Technique; } + Qt3DRender::QTechnique *gl2Technique() const { return m_gl2Technique; } + Qt3DRender::QTechnique *es2Technique() const { return m_es2Technique; } + + Qt3DRender::QRenderPass *gl3Pass() const { return m_gl3Pass; } + Qt3DRender::QRenderPass *gl2Pass() const { return m_gl2Pass; } + Qt3DRender::QRenderPass *es2Pass() const { return m_es2Pass; } + + Qt3DRender::QShaderProgram *gl3Shader() const { return m_gl3Program; } + Qt3DRender::QShaderProgram *gl2shader() const { return m_gl2es2Program; } + Qt3DRender::QShaderProgram *es2Shader() const { return m_gl2es2Program; } + +private: + Qt3DRender::QEffect *m_effect; + Qt3DRender::QTechnique *m_gl3Technique; + Qt3DRender::QTechnique *m_gl2Technique; + Qt3DRender::QTechnique *m_es2Technique; + Qt3DRender::QRenderPass *m_gl3Pass; + Qt3DRender::QRenderPass *m_gl2Pass; + Qt3DRender::QRenderPass *m_es2Pass; + Qt3DRender::QShaderProgram *m_gl3Program; + Qt3DRender::QShaderProgram *m_gl2es2Program; +}; + +Qt3DRender::QViewport *viewportFrameGraph() +{ + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + return viewport; +} + +Qt3DRender::QTechniqueFilter *techniqueFilterFrameGraph() +{ + Qt3DRender::QTechniqueFilter *techniqueFilter = new Qt3DRender::QTechniqueFilter(); + return techniqueFilter; +} + +Qt3DRender::QRenderPassFilter *renderPassFilter() +{ + Qt3DRender::QRenderPassFilter *passFilter = new Qt3DRender::QRenderPassFilter(); + return passFilter; +} + +Qt3DCore::QEntity *buildScene(Qt3DRender::QFrameGraphNode *frameGraph, Qt3DRender::QMaterial *material = nullptr) +{ + Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); + + // FrameGraph + Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); + renderSettings->setActiveFrameGraph(frameGraph); + root->addComponent(renderSettings); + + // Scene + for (int i = 0; i < 10; i++) { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + if (material != nullptr) + e->addComponent(material); + e->setParent(root); + } + + return root; +} + +} // anonymous + +class tst_MaterialParameterGatherer : public QObject +{ + Q_OBJECT +private Q_SLOTS: + + void checkRunNoHandlesNoTechniqueFilterNoPassFilter() + { + // GIVEN + Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph()); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 0); + + // WHEN + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); + } + + void checkRunSelectAllNoTechniqueFilterNoPassFilter() + { + // GIVEN + TestMaterial material; + Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph(), &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + } + + void checkRunDisabledMaterial() + { + // GIVEN + TestMaterial material; + material.setEnabled(false); + Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph(), &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); + } + + void checkRunSelectAllTechniqueFilterWithNoFilterNoPassFilter() + { + // GIVEN + Qt3DRender::QTechniqueFilter *frameGraphFilter = techniqueFilterFrameGraph(); + + TestMaterial material; + + Qt3DRender::QFilterKey techniqueFilterKey; + techniqueFilterKey.setName(QStringLiteral("renderingStyle")); + techniqueFilterKey.setValue(QVariant(QStringLiteral("backward"))); + + material.gl2Technique()->addFilterKey(&techniqueFilterKey); + material.gl3Technique()->addFilterKey(&techniqueFilterKey); + material.es2Technique()->addFilterKey(&techniqueFilterKey); + + Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); + QVERIFY(backendTechniqueFilter != nullptr); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + } + + void checkRunSelectAllTechniqueFilterWithIncompatibleFilterNoPassFilter() + { + // GIVEN + Qt3DRender::QTechniqueFilter *frameGraphFilter = techniqueFilterFrameGraph(); + TestMaterial material; + + Qt3DRender::QFilterKey techniqueFilterFilterKey; + techniqueFilterFilterKey.setName(QStringLiteral("renderingStyle")); + techniqueFilterFilterKey.setValue(QVariant(QStringLiteral("forward"))); + + Qt3DRender::QFilterKey techniqueFilterKey; + techniqueFilterKey.setName(QStringLiteral("renderingStyle")); + techniqueFilterKey.setValue(QVariant(QStringLiteral("backward"))); + + frameGraphFilter->addMatch(&techniqueFilterFilterKey); + + material.gl2Technique()->addFilterKey(&techniqueFilterKey); + material.gl3Technique()->addFilterKey(&techniqueFilterKey); + material.es2Technique()->addFilterKey(&techniqueFilterKey); + + Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); + QVERIFY(backendTechniqueFilter != nullptr); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); + } + + void checkRunSelectAllTechniqueFilterWithCompatibleFilterNoPassFilter() + { + // GIVEN + Qt3DRender::QTechniqueFilter *frameGraphFilter = techniqueFilterFrameGraph(); + TestMaterial material; + + Qt3DRender::QFilterKey techniqueFilterKey; + techniqueFilterKey.setName(QStringLiteral("renderingStyle")); + techniqueFilterKey.setValue(QVariant(QStringLiteral("backward"))); + + frameGraphFilter->addMatch(&techniqueFilterKey); + + material.gl2Technique()->addFilterKey(&techniqueFilterKey); + material.gl3Technique()->addFilterKey(&techniqueFilterKey); + material.es2Technique()->addFilterKey(&techniqueFilterKey); + + Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); + QVERIFY(backendTechniqueFilter != nullptr); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + } + + void checkRunSelectAllNoTechniqueFilterPassFilterWithNoFilter() + { + // GIVEN + Qt3DRender::QRenderPassFilter *frameGraphFilter = renderPassFilter(); + TestMaterial material; + + Qt3DRender::QFilterKey passFilterKey; + passFilterKey.setName(QStringLiteral("renderingStyle")); + passFilterKey.setValue(QVariant(QStringLiteral("backward"))); + + material.gl3Pass()->addFilterKey(&passFilterKey); + material.gl2Pass()->addFilterKey(&passFilterKey); + material.es2Pass()->addFilterKey(&passFilterKey); + + Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::RenderPassFilter *backendPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); + QVERIFY(backendPassFilter != nullptr); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendPassFilter); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + } + + void checkRunSelectAllNoTechniqueFilterPassFilterWithIncompatibleFilter() + { + // GIVEN + Qt3DRender::QRenderPassFilter *frameGraphFilter = renderPassFilter(); + TestMaterial material; + + Qt3DRender::QFilterKey passFilterFilterKey; + passFilterFilterKey.setName(QStringLiteral("renderingStyle")); + passFilterFilterKey.setValue(QVariant(QStringLiteral("forward"))); + + Qt3DRender::QFilterKey passFilterKey; + passFilterKey.setName(QStringLiteral("renderingStyle")); + passFilterKey.setValue(QVariant(QStringLiteral("backward"))); + + frameGraphFilter->addMatch(&passFilterFilterKey); + + material.gl3Pass()->addFilterKey(&passFilterKey); + material.gl2Pass()->addFilterKey(&passFilterKey); + material.es2Pass()->addFilterKey(&passFilterKey); + + Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + + testAspect.initializeRenderer(); + + // THEN + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::RenderPassFilter *backendPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(frameGraphFilter->id())); + QVERIFY(backendPassFilter != nullptr); + + // WHEN + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendPassFilter); + gatherer->run(); + + // THEN + QCOMPARE(gatherer->materialToPassAndParameter().size(), 0); + } + + void checkParameterPriorityGathering() + { + { + // GIVEN + Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); + Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); + + renderPassFG->setParent(techniqueFilterFG); + + TestMaterial material; + + Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); + + // WHEN + techniqueFilterFG->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::red)))); + + auto renderPassParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); + + renderPassFG->addParameter(renderPassParameter); + material.addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::green)))); + material.effect()->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::blue)))); + + auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); + + material.gl3Technique()->addParameter(techniqueParam); + material.gl2Technique()->addParameter(techniqueParam); + material.es2Technique()->addParameter(techniqueParam); + + auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); + + material.gl3Pass()->addParameter(passParam); + material.gl2Pass()->addParameter(passParam); + material.es2Pass()->addParameter(passParam); + + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + testAspect.initializeRenderer(); + + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); + Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); + QVERIFY(backendTechniqueFilter != nullptr); + QVERIFY(backendRenderPassFilter != nullptr); + + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendRenderPassFilter); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN -> RenderPassFilter wins + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + QCOMPARE(passParameterData.size(), 1); + + const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + + QCOMPARE(data.parameterInfo.size(), 1); + QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(renderPassParameter->id())); + } + { + // GIVEN + Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); + Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); + + renderPassFG->setParent(techniqueFilterFG); + + TestMaterial material; + + Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); + + // WHEN + auto techniqueFilterParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); + techniqueFilterFG->addParameter(techniqueFilterParameter); + + material.addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::green)))); + material.effect()->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::blue)))); + + auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); + + material.gl3Technique()->addParameter(techniqueParam); + material.gl2Technique()->addParameter(techniqueParam); + material.es2Technique()->addParameter(techniqueParam); + + auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); + + material.gl3Pass()->addParameter(passParam); + material.gl2Pass()->addParameter(passParam); + material.es2Pass()->addParameter(passParam); + + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + testAspect.initializeRenderer(); + + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); + Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); + QVERIFY(backendTechniqueFilter != nullptr); + QVERIFY(backendRenderPassFilter != nullptr); + + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendRenderPassFilter); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN -> TechniqueFilter wins + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + QCOMPARE(passParameterData.size(), 1); + + const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + + QCOMPARE(data.parameterInfo.size(), 1); + QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(techniqueFilterParameter->id())); + } + { + // GIVEN + Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); + Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); + + renderPassFG->setParent(techniqueFilterFG); + + TestMaterial material; + + Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); + + // WHEN + auto materialParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); + + material.addParameter(materialParameter); + material.effect()->addParameter(new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::blue)))); + + auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); + + material.gl3Technique()->addParameter(techniqueParam); + material.gl2Technique()->addParameter(techniqueParam); + material.es2Technique()->addParameter(techniqueParam); + + auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); + + material.gl3Pass()->addParameter(passParam); + material.gl2Pass()->addParameter(passParam); + material.es2Pass()->addParameter(passParam); + + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + testAspect.initializeRenderer(); + + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); + Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); + QVERIFY(backendTechniqueFilter != nullptr); + QVERIFY(backendRenderPassFilter != nullptr); + + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendRenderPassFilter); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN -> TechniqueFilter wins + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + QCOMPARE(passParameterData.size(), 1); + + const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + + QCOMPARE(data.parameterInfo.size(), 1); + QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(materialParameter->id())); + } + { + // GIVEN + Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); + Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); + + renderPassFG->setParent(techniqueFilterFG); + + TestMaterial material; + + Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); + + // WHEN + auto effectParameter = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::cyan))); + + material.effect()->addParameter(effectParameter); + + auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); + + material.gl3Technique()->addParameter(techniqueParam); + material.gl2Technique()->addParameter(techniqueParam); + material.es2Technique()->addParameter(techniqueParam); + + auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); + + material.gl3Pass()->addParameter(passParam); + material.gl2Pass()->addParameter(passParam); + material.es2Pass()->addParameter(passParam); + + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + testAspect.initializeRenderer(); + + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); + Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); + QVERIFY(backendTechniqueFilter != nullptr); + QVERIFY(backendRenderPassFilter != nullptr); + + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendRenderPassFilter); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN -> TechniqueFilter wins + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + QCOMPARE(passParameterData.size(), 1); + + const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + + QCOMPARE(data.parameterInfo.size(), 1); + QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(effectParameter->id())); + } + { + // GIVEN + Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); + Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); + + renderPassFG->setParent(techniqueFilterFG); + + TestMaterial material; + + Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); + + // WHEN + auto techniqueParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::white))); + + material.gl3Technique()->addParameter(techniqueParam); + material.gl2Technique()->addParameter(techniqueParam); + material.es2Technique()->addParameter(techniqueParam); + + auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); + + material.gl3Pass()->addParameter(passParam); + material.gl2Pass()->addParameter(passParam); + material.es2Pass()->addParameter(passParam); + + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + testAspect.initializeRenderer(); + + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); + Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); + QVERIFY(backendTechniqueFilter != nullptr); + QVERIFY(backendRenderPassFilter != nullptr); + + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendRenderPassFilter); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN -> TechniqueFilter wins + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + QCOMPARE(passParameterData.size(), 1); + + const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + + QCOMPARE(data.parameterInfo.size(), 1); + QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(techniqueParam->id())); + } + { + // GIVEN + Qt3DRender::QTechniqueFilter *techniqueFilterFG = techniqueFilterFrameGraph(); + Qt3DRender::QRenderPassFilter *renderPassFG = renderPassFilter(); + + renderPassFG->setParent(techniqueFilterFG); + + TestMaterial material; + + Qt3DCore::QEntity *sceneRoot = buildScene(techniqueFilterFG, &material); + + // WHEN + auto passParam = new Qt3DRender::QParameter(QStringLiteral("color"), QVariant(QColor(Qt::gray))); + + material.gl3Pass()->addParameter(passParam); + material.gl2Pass()->addParameter(passParam); + material.es2Pass()->addParameter(passParam); + + Qt3DRender::TestAspect testAspect(sceneRoot); + Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + testAspect.initializeRenderer(); + + QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); + Qt3DRender::Render::TechniqueFilter *backendTechniqueFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(techniqueFilterFG->id())); + Qt3DRender::Render::RenderPassFilter *backendRenderPassFilter = static_cast(testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFG->id())); + QVERIFY(backendTechniqueFilter != nullptr); + QVERIFY(backendRenderPassFilter != nullptr); + + gatherer->setHandles(testAspect.nodeManagers()->materialManager()->activeHandles()); + gatherer->setRenderPassFilter(backendRenderPassFilter); + gatherer->setTechniqueFilter(backendTechniqueFilter); + gatherer->run(); + + // THEN -> TechniqueFilter wins + QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); + + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + QCOMPARE(passParameterData.size(), 1); + + const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + + QCOMPARE(data.parameterInfo.size(), 1); + QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(passParam->id())); + } + } +}; + +QTEST_MAIN(tst_MaterialParameterGatherer) + +#include "tst_materialparametergathererjob.moc" diff --git a/tests/auto/render/opengl/opengl.pro b/tests/auto/render/opengl/opengl.pro new file mode 100644 index 000000000..5299ebd36 --- /dev/null +++ b/tests/auto/render/opengl/opengl.pro @@ -0,0 +1,19 @@ +TEMPLATE = subdirs + +SUBDIRS += \ + filtercompatibletechniquejob \ + graphicshelpergl3_3 \ + graphicshelpergl3_2 \ + graphicshelpergl2 \ + glshadermanager \ + materialparametergathererjob \ + textures \ + renderer \ + renderviewutils \ + renderviews \ + renderqueue \ + renderviewbuilder \ + qgraphicsutils \ + computecommand + +!macos: SUBDIRS += graphicshelpergl4 diff --git a/tests/auto/render/opengl/opengl_render_plugin.pri b/tests/auto/render/opengl/opengl_render_plugin.pri new file mode 100644 index 000000000..50fade878 --- /dev/null +++ b/tests/auto/render/opengl/opengl_render_plugin.pri @@ -0,0 +1,18 @@ +# Found no way of having the test runner include the correct +# library path as runtime + +#PLUGIN_SRC_PATH = $$PWD/../../../../src/plugins/renderers/opengl + +#INCLUDEPATH += \ +# $$PLUGIN_SRC_PATH/graphicshelpers \ +# $$PLUGIN_SRC_PATH/io \ +# $$PLUGIN_SRC_PATH/jobs \ +# $$PLUGIN_SRC_PATH/managers \ +# $$PLUGIN_SRC_PATH/renderer \ +# $$PLUGIN_SRC_PATH/renderstates \ +# $$PLUGIN_SRC_PATH/textures + +#LIBS += -L$$[QT_INSTALL_PLUGINS]/renderers/ -lopenglrenderer + +# Instead we link against the sources directly +include(../../../../src/plugins/renderers/opengl/opengl.pri) diff --git a/tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro b/tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro new file mode 100644 index 000000000..8c936c527 --- /dev/null +++ b/tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro @@ -0,0 +1,12 @@ +TEMPLATE = app + +TARGET = tst_qgraphicsutils + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_qgraphicsutils.cpp + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp b/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp new file mode 100644 index 000000000..2e0dd0f96 --- /dev/null +++ b/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp @@ -0,0 +1,355 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +class tst_QGraphicsUtils : public QObject +{ + Q_OBJECT +private slots: + void fillScalarInDataArray(); + void fillArray(); + void fillScalarWithOffsets(); + void fillMatrix4x4(); + void fillMatrix3x4(); + void fillMatrix4x3(); + void fillMatrixArray(); +}; + +void tst_QGraphicsUtils::fillScalarInDataArray() +{ + Qt3DRender::Render::ShaderUniform description; + + description.m_size = 1; + description.m_offset = 0; + description.m_arrayStride = 10; + + QVector4D testVector(8.0f, 8.0f, 3.0f, 1.0f); + const GLfloat *vectorData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(testVector, 1, 4); + + for (int i = 0; i < 4; i++) { + if (i == 0) + QVERIFY(vectorData[i] == testVector.x()); + else if (i == 1) + QVERIFY(vectorData[i] == testVector.y()); + else if (i == 2) + QVERIFY(vectorData[i] == testVector.z()); + else if (i == 3) + QVERIFY(vectorData[i] == testVector.w()); + } + + QByteArray data(description.m_size * 4 * sizeof(GLfloat), 0); + char *innerData = data.data(); + + // Checked that we are not overflowing + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 2); + for (int i = 0; i < 4; ++i) { + if (i < 2) + QVERIFY(vectorData[i] == ((GLfloat*)innerData)[i]); + else + QVERIFY(((GLfloat*)innerData)[i] == 0.0f); + } + + // Check that all values are copied + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); + for (int i = 0; i < 4; ++i) + QVERIFY(vectorData[i] == ((GLfloat*)innerData)[i]); + + // check that offsetting works + description.m_offset = 16; + data = QByteArray(description.m_size * 8 * sizeof(GLfloat), 0); + innerData = data.data(); + + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); + for (int i = 0; i < 8; ++i) { + if (i < 4) + QVERIFY(((GLfloat*)innerData)[i] == 0.0f); + else + QVERIFY(vectorData[i - 4] == ((GLfloat*)innerData)[i]); + } +} + +void tst_QGraphicsUtils::fillArray() +{ + QVector4D testVector(8.0f, 8.0f, 3.0f, 1.0f); + QVector4D testVector2(3.0f, 5.0f, 0.0f, 7.0f); + QVector4D testVector3(4.0f, 5.0f, 4.0f, 2.0f); + + QVariantList variantList = QVariantList() << testVector << testVector2 << testVector3; + const GLfloat *vectorData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant(variantList), 3, 4); + + Qt3DRender::Render::ShaderUniform description; + + description.m_size = 3; + description.m_offset = 16; + description.m_arrayStride = 16; + + QByteArray data(description.m_size * (4 + description.m_arrayStride) * sizeof(GLfloat) + description.m_offset, 0); + char *innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); + + int offset = description.m_offset / sizeof(GLfloat); + int stride = description.m_arrayStride / sizeof(GLfloat); + + GLfloat *innerDataFloat = (GLfloat*)innerData; + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 4; ++j) { + int idx = i * 4 + j; + QVERIFY(innerDataFloat[offset + j] == vectorData[idx]); + } + offset += stride; + } +} + +void tst_QGraphicsUtils::fillScalarWithOffsets() +{ + // Simulates Uniform Block + + // uniform Block { + // vec3 position; // Offset 0 - 12 bytes + // vec3 direction; // Offset 16 - 12 bytes + // vec4 color; // Offset 32 - 16 bytes + // float intensity; // Offset 48 - bytes + // } // total size 64 bytes + + QVector3D position(8.0f, 8.0f, 3.0f); + QVector3D direction(3.0f, 5.0f, 2.0f); + QVector4D color(4.0f, 5.0f, 4.0f, 1.0f); + float intensity = 1.0f; + + Qt3DRender::Render::ShaderUniform posUniform; + posUniform.m_size = 1; + posUniform.m_arrayStride = 0; + posUniform.m_matrixStride = 0; + posUniform.m_offset = 0; + + Qt3DRender::Render::ShaderUniform dirUniform; + dirUniform.m_size = 1; + dirUniform.m_arrayStride = 0; + dirUniform.m_matrixStride = 0; + dirUniform.m_offset = 16; + + Qt3DRender::Render::ShaderUniform colUniform; + colUniform.m_size = 1; + colUniform.m_arrayStride = 0; + colUniform.m_matrixStride = 0; + colUniform.m_offset = 32; + + Qt3DRender::Render::ShaderUniform intUniform; + intUniform.m_size = 1; + intUniform.m_arrayStride = 0; + intUniform.m_matrixStride = 0; + intUniform.m_offset = 48; + + QVector data(16); + void *innerData = data.data(); + + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(position, 1, 3), + posUniform, 3); + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(direction, 1, 3), + dirUniform, 3); + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(color, 1, 4), + colUniform, 4); + Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(intensity, 1, 1), + intUniform, 1); + + GLfloat *floatData = (GLfloat*)innerData; + + // Check first 16 bytes - position + QVERIFY(floatData[0] == position.x()); + QVERIFY(floatData[1] == position.y()); + QVERIFY(floatData[2] == position.z()); + QVERIFY(floatData[3] == 0.0f); + // Check 16 - 32 bytes - direction + QVERIFY(floatData[4] == direction.x()); + QVERIFY(floatData[5] == direction.y()); + QVERIFY(floatData[6] == direction.z()); + QVERIFY(floatData[7] == 0.0f); + // Check 32 - 48 bytes - color + QVERIFY(floatData[8] == color.x()); + QVERIFY(floatData[9] == color.y()); + QVERIFY(floatData[10] == color.z()); + QVERIFY(floatData[11] == color.w()); + // Check 48 - 64 bytes - intensity + QVERIFY(floatData[12] == intensity); + QVERIFY(floatData[13] == 0.0f); + QVERIFY(floatData[14] == 0.0f); + QVERIFY(floatData[15] == 0.0f); +} + +void tst_QGraphicsUtils::fillMatrix4x4() +{ + // row major + QMatrix4x4 mat(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f); + + // column major + const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(mat, 1, 16); + + Qt3DRender::Render::ShaderUniform description; + + description.m_size = 1; + description.m_offset = 0; + description.m_arrayStride = 0; + description.m_matrixStride = 16; + + + QByteArray data(description.m_size * 16 * sizeof(GLfloat), 0); + char *innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); + // Check for no offset/no stride + for (int i = 0; i < 16; ++i) + QVERIFY((((GLfloat *)innerData)[i]) == matData[i]); + + description.m_offset = 12; + data = QByteArray((description.m_size * 16 + description.m_offset) * sizeof(GLfloat), 0); + innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); + // Check with 12 offset/no stride + for (int i = 0; i < 16; ++i) + QVERIFY((((GLfloat *)innerData)[3 + i]) == matData[i]); + + description.m_matrixStride = 16; + data = QByteArray((description.m_size * 16 + 4 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); + innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); + // Check with 10 offset/ 16 stride + int offset = description.m_offset / sizeof(GLfloat); + int matrixStride = description.m_matrixStride / sizeof(GLfloat); + + for (int col = 0; col < 4; ++col) { + for (int row = 0; row < 4; ++row) + QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[col * 4 + row]); + offset += matrixStride; + } +} + +void tst_QGraphicsUtils::fillMatrix3x4() +{ + QMatrix3x4 mat; + + mat.fill(6.0f); + const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); + + Qt3DRender::Render::ShaderUniform description; + + description.m_size = 1; + description.m_offset = 16; + description.m_arrayStride = 0; + description.m_matrixStride = 12; + + QByteArray data((description.m_size * 12 + 3 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); + char *innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 3, 4); + // Check with 16 offset/ 12 stride + int offset = description.m_offset / sizeof(GLfloat); + int matrixStride = description.m_matrixStride / sizeof(GLfloat); + + for (int col = 0; col < 3; ++col) { + for (int row = 0; row < 4; ++row) + QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[col * 4 + row]); + offset += matrixStride; + } +} + +void tst_QGraphicsUtils::fillMatrix4x3() +{ + QMatrix4x3 mat; + + mat.fill(6.0f); + const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); + + Qt3DRender::Render::ShaderUniform description; + + description.m_size = 1; + description.m_offset = 16; + description.m_arrayStride = 0; + description.m_matrixStride = 16; + + QByteArray data((description.m_size * 12 + 4 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); + char *innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); + // Check with 16 offset/ 16 stride + int offset = description.m_offset / sizeof(GLfloat); + int matrixStride = description.m_matrixStride / sizeof(GLfloat); + + for (int col = 0; col < 4; ++col) { + for (int row = 0; row < 3; ++row) + QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[col * 3 + row]); + offset += matrixStride; + } +} + +void tst_QGraphicsUtils::fillMatrixArray() +{ + QMatrix4x3 mat1; + QMatrix4x3 mat2; + QMatrix4x3 mat3; + mat1.fill(6.0f); + mat2.fill(2.0f); + mat3.fill(7.0f); + + QVariantList matrices = QVariantList() << QVariant::fromValue(mat1) << QVariant::fromValue(mat2) << QVariant::fromValue(mat3); + + const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(matrices), 3, 12); + + Qt3DRender::Render::ShaderUniform description; + + description.m_size = 3; + description.m_offset = 12; + description.m_arrayStride = 4; + description.m_matrixStride = 16; + + QByteArray data((description.m_size * (12 + 4 * description.m_matrixStride + description.m_arrayStride) + description.m_offset) * sizeof(GLfloat), 0); + char *innerData = data.data(); + Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); + // Check with 12 offset/ 4 array stride / 16 matrix stride + int offset = description.m_offset / sizeof(GLfloat); + int matrixStride = description.m_matrixStride / sizeof(GLfloat); + int arrayStride = description.m_arrayStride / sizeof(GLfloat); + + for (int i = 0; i < 3; ++i) { + for (int col = 0; col < 4; ++col) { + for (int row = 0; row < 3; ++row) { + int idx = i * 4 * 3 + col * 3 + row; + QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[idx]); + } + offset += matrixStride; + } + offset += arrayStride; + } +} + +QTEST_APPLESS_MAIN(tst_QGraphicsUtils) + +#include "tst_qgraphicsutils.moc" diff --git a/tests/auto/render/opengl/renderer/renderer.pro b/tests/auto/render/opengl/renderer/renderer.pro new file mode 100644 index 000000000..d481c7b9e --- /dev/null +++ b/tests/auto/render/opengl/renderer/renderer.pro @@ -0,0 +1,12 @@ +TEMPLATE = app + +TARGET = tst_renderer + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_renderer.cpp + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/renderer/tst_renderer.cpp b/tests/auto/render/opengl/renderer/tst_renderer.cpp new file mode 100644 index 000000000..6aed6ed5f --- /dev/null +++ b/tests/auto/render/opengl/renderer/tst_renderer.cpp @@ -0,0 +1,348 @@ +/**************************************************************************** +** +** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class tst_Renderer : public QObject +{ + Q_OBJECT +public : + tst_Renderer() {} + ~tst_Renderer() {} + +private Q_SLOTS: + + void checkPreRenderBinJobs() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OffscreenSurfaceHelper offscreenHelper(&renderer); + Qt3DRender::Render::RenderSettings settings; + // owned by FG manager + Qt3DRender::Render::ViewportNode *fgRoot = new Qt3DRender::Render::ViewportNode(); + const Qt3DCore::QNodeId fgRootId = Qt3DCore::QNodeId::createId(); + + nodeManagers.frameGraphManager()->appendNode(fgRootId, fgRoot); + settings.setActiveFrameGraphId(fgRootId); + + renderer.setNodeManagers(&nodeManagers); + renderer.setSettings(&settings); + renderer.setOffscreenSurfaceHelper(&offscreenHelper); + renderer.initialize(); + + // Ensure invoke calls are performed + QCoreApplication::processEvents(); + + // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) + QVector jobs = renderer.preRenderingJobs(); + + // THEN + QCOMPARE(jobs.size(), + 1 + // PickBoundingVolumeJob + 1); // RayCastingJob + + // WHEN + renderer.m_sendBufferCaptureJob->addRequest({Qt3DCore::QNodeId(), {}}); + jobs = renderer.preRenderingJobs(); + + // THEN + QCOMPARE(jobs.size(), + 1 + // PickBoundingVolumeJob + 1 + // RayCastingJob + 1); // SendBufferCaptureJob + // Note: pending render buffer captures are only cleared when the job is run + + // WHEN + renderer.m_updatedSetFences.push_back({Qt3DCore::QNodeId(), nullptr}); + jobs = renderer.preRenderingJobs(); + + // THEN + QCOMPARE(jobs.size(), + 1 + // PickBoundingVolumeJob + 1 + // RayCastingJob + 1 + // SendBufferCaptureJob + 1); // SendSetFenceHandlesJob + // Note: pending set fence handles are only cleared when the job is run + + // Properly shutdown command thread + renderer.shutdown(); + } + + void checkRenderBinJobs() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::RenderQueue *renderQueue = renderer.renderQueue(); + Qt3DRender::Render::OffscreenSurfaceHelper offscreenHelper(&renderer); + Qt3DRender::Render::RenderSettings settings; + // owned by FG manager + Qt3DRender::Render::ViewportNode *fgRoot = new Qt3DRender::Render::ViewportNode(); + const Qt3DCore::QNodeId fgRootId = Qt3DCore::QNodeId::createId(); + + nodeManagers.frameGraphManager()->appendNode(fgRootId, fgRoot); + settings.setActiveFrameGraphId(fgRootId); + + renderer.setNodeManagers(&nodeManagers); + renderer.setSettings(&settings); + renderer.setOffscreenSurfaceHelper(&offscreenHelper); + renderer.initialize(); + + // Ensure invoke calls are performed + QCoreApplication::processEvents(); + + // NOTE: FilterCompatibleTechniqueJob and ShaderGathererJob cannot run because the context + // is not initialized in this test + + const int renderViewBuilderMaterialCacheJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + // syncMaterialGathererJob + // n * materialGathererJob + const int layerCacheJobCount = 2; + // filterEntityByLayerJob, + // syncFilterEntityByLayerJob + + const int singleRenderViewCommandRebuildJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + + const int singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + // RenderViewBuilder renderViewJob, + // syncRenderViewInitializationJob, + // syncFrustumCullingJob, + // filterProximityJob, + // setClearDrawBufferIndexJob, + // frustumCullingJob, + // syncRenderCommandUpdateJob, + // syncRenderViewCommandPostUpdateJob + // n * (RenderViewCommandBuildJobs) + + // WHEN + QVector jobs = renderer.renderBinJobs(); + + // THEN -> AllDirty + // (Renderer is not initialized so FilterCompatibleTechniqueJob + // and ShaderGathererJob are not added here) + QCOMPARE(jobs.size(), + 1 + // EntityEnabledDirty + 1 + // WorldTransformJob + 1 + // UpdateWorldBoundingVolume + 1 + // UpdateShaderDataTransform + 1 + // ExpandBoundingVolumeJob + 1 + // CalculateBoundingVolumeJob + 1 + // UpdateMeshTriangleListJob + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // BufferGathererJob + 1 + // TexturesGathererJob + 1 + // UpdateEntityLayersJob + 1 + // LightGathererJob + 1 + // CacheLightJob + 1 + // RenderableEntityFilterJob + 1 + // CacheRenderableEntitiesJob + 1 + // ComputableEntityFilterJob + 1 + // CacheComputableEntitiesJob + singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + + layerCacheJobCount + + renderViewBuilderMaterialCacheJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) (Nothing in cache) + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::FrameGraphDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + + renderViewBuilderMaterialCacheJobCount + + layerCacheJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) (RV leaf in cache) + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::FrameGraphDirty, nullptr); + renderer.cache()->leafNodeCache[renderer.m_frameGraphLeaves.first()] = {}; + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + + renderViewBuilderMaterialCacheJobCount + + layerCacheJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::EntityEnabledDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + 1 + // EntityEnabledDirty + singleRenderViewJobCount + + layerCacheJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::TransformDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // WorldTransformJob + 1 + // UpdateWorldBoundingVolume + 1 + // UpdateShaderDataTransform + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + 1 + // ExpandBoundingVolumeJob + singleRenderViewJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::MaterialDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + singleRenderViewJobCount + + singleRenderViewCommandRebuildJobCount + + renderViewBuilderMaterialCacheJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::GeometryDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // CalculateBoundingVolumeJob + 1 + // UpdateMeshTriangleListJob + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + 1 + // ExpandBoundingVolumeJob + 1 + // RenderableEntityFilterPtr + 1 + // SyncRenderableEntities + singleRenderViewCommandRebuildJobCount + + singleRenderViewJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::BuffersDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // updateSkinningPaletteJob + 1 + // SyncLoadingJobs + 1 + // CalculateBoundingVolumeJob + 1 + // UpdateMeshTriangleListJob + 1 + // BufferGathererJob + singleRenderViewJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // WHEN + renderer.markDirty(Qt3DRender::Render::AbstractRenderer::TexturesDirty, nullptr); + jobs = renderer.renderBinJobs(); + + // THEN (level + QCOMPARE(jobs.size(), + 1 + // updateLevelOfDetailJob + 1 + // cleanupJob + 1 + // VAOGatherer + 1 + // TexturesGathererJob + 1 + // updateSkinningPaletteJob + 1 + // SyncTexturesGathererJob + singleRenderViewJobCount); + + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + renderQueue->reset(); + + // Properly shutdown command thread + renderer.shutdown(); + } +}; + +QTEST_MAIN(tst_Renderer) + +#include "tst_renderer.moc" diff --git a/tests/auto/render/opengl/renderqueue/renderqueue.pro b/tests/auto/render/opengl/renderqueue/renderqueue.pro new file mode 100644 index 000000000..19106ba92 --- /dev/null +++ b/tests/auto/render/opengl/renderqueue/renderqueue.pro @@ -0,0 +1,14 @@ +TEMPLATE = app + +TARGET = tst_renderqueue + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_renderqueue.cpp + +include(../../../core/common/common.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp b/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp new file mode 100644 index 000000000..2be089495 --- /dev/null +++ b/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp @@ -0,0 +1,243 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +class tst_RenderQueue : public QObject +{ + Q_OBJECT +public : + tst_RenderQueue() {} + ~tst_RenderQueue() {} + +private Q_SLOTS: + void setRenderViewCount(); + void circleQueues(); + void checkOrder(); + void checkTimeToSubmit(); + void concurrentQueueAccess(); + void resetQueue(); +}; + + +void tst_RenderQueue::setRenderViewCount() +{ + // GIVEN + Qt3DRender::Render::RenderQueue renderQueue; + + // THEN + QCOMPARE(renderQueue.wasReset(), true); + + // WHEN + renderQueue.setTargetRenderViewCount(7); + + // THEN + QCOMPARE(renderQueue.wasReset(), false); + QVERIFY(renderQueue.targetRenderViewCount() == 7); + QVERIFY(renderQueue.currentRenderViewCount()== 0); +} + +void tst_RenderQueue::circleQueues() +{ + // GIVEN + Qt3DRender::Render::RenderQueue renderQueue; + renderQueue.setTargetRenderViewCount(7); + + // WHEN + for (int j = 0; j < 10; j++) { + + // WHEN + renderQueue.reset(); + renderQueue.setTargetRenderViewCount(7); + + // THEN + QVERIFY(!renderQueue.isFrameQueueComplete()); + QCOMPARE(renderQueue.currentRenderViewCount(), 0); + + // WHEN + QList renderViews; + for (int i = 0; i < 7; i++) { + renderViews << new Qt3DRender::Render::RenderView(); + renderQueue.queueRenderView(renderViews.at(i), i); + } + + // THEN + QVERIFY(renderQueue.isFrameQueueComplete()); + } +} + +void tst_RenderQueue::checkOrder() +{ + // GIVEN + Qt3DRender::Render::RenderQueue renderQueue; + renderQueue.setTargetRenderViewCount(7); + QVector renderViews(7); + + // WHEN + for (int i = 0; i < 7; ++i) { + int processingOrder = (i % 2 == 0) ? (6 - i) : i; + renderViews[processingOrder] = new Qt3DRender::Render::RenderView(); + renderQueue.queueRenderView(renderViews[processingOrder], processingOrder); + } + + // THEN + QVector frame = renderQueue.nextFrameQueue(); + for (int i = 0; i < 7; ++i) { + QVERIFY(frame[i] == renderViews[i]); + } +} + +void tst_RenderQueue::checkTimeToSubmit() +{ + // GIVEN + Qt3DRender::Render::RenderQueue renderQueue; + renderQueue.setTargetRenderViewCount(7); + QVector renderViews(7); + + // WHEN + for (int i = 0; i < 7; i++) { + int processingOrder = (i % 2 == 0) ? (6 - i) : i; + renderViews[processingOrder] = new Qt3DRender::Render::RenderView(); + renderQueue.queueRenderView(renderViews[processingOrder], processingOrder); + + // THEN + if (i < 6) + QVERIFY(!renderQueue.isFrameQueueComplete()); + else + QVERIFY(renderQueue.isFrameQueueComplete()); + } +} + +class SimpleWorker : public QThread +{ + Q_OBJECT +public: + QSemaphore m_waitSubmit; + QSemaphore m_waitQueue; + Qt3DRender::Render::RenderQueue *m_renderQueues; + +public Q_SLOTS: + + void run() final // In Thread + { + for (int i = 0; i < 5; i++) { + m_waitQueue.acquire(); + + QVERIFY(m_renderQueues->currentRenderViewCount() == 0); + QVERIFY(!m_renderQueues->isFrameQueueComplete()); + + for (int j = 0; j < 7; ++j) { + // THEN + QCOMPARE(m_renderQueues->currentRenderViewCount(), j); + // WHEN + m_renderQueues->queueRenderView(new Qt3DRender::Render::RenderView(), j); + // THEN + QVERIFY(m_renderQueues->targetRenderViewCount() == 7); + QCOMPARE(m_renderQueues->currentRenderViewCount(), j + 1); + QVERIFY(m_renderQueues->isFrameQueueComplete() == (j == 6)); + QThread::msleep(20); // Simulates business + } + + QVERIFY(m_renderQueues->isFrameQueueComplete()); + m_waitSubmit.release(); + } + } +}; + + +void tst_RenderQueue::concurrentQueueAccess() +{ + // GIVEN + Qt3DRender::Render::RenderQueue *renderQueue = new Qt3DRender::Render::RenderQueue; + + SimpleWorker *jobsThread = new SimpleWorker(); + renderQueue->setTargetRenderViewCount(7); + jobsThread->m_renderQueues = renderQueue; + + // THEN + QVERIFY(jobsThread->m_renderQueues->targetRenderViewCount() == renderQueue->targetRenderViewCount()); + QVERIFY(jobsThread->m_renderQueues->currentRenderViewCount() == renderQueue->currentRenderViewCount()); + + // Start thread + jobsThread->start(); + + jobsThread->m_waitQueue.release(); + + for (int i = 0; i < 5; ++i) { + jobsThread->m_waitSubmit.acquire(); + + // WHEN unlocked + // THEN + QVERIFY (renderQueue->isFrameQueueComplete()); + QCOMPARE(renderQueue->nextFrameQueue().size(), renderQueue->targetRenderViewCount()); + + // reset queue for next frame + renderQueue->reset(); + renderQueue->setTargetRenderViewCount(7); + jobsThread->m_waitQueue.release(); + } + jobsThread->wait(); +} + +void tst_RenderQueue::resetQueue() +{ + // GIVEN + Qt3DRender::Render::RenderQueue renderQueue; + + for (int j = 0; j < 5; j++) { + // WHEN + renderQueue.setTargetRenderViewCount(5); + // THEN + QCOMPARE(renderQueue.wasReset(), false); + QVERIFY(renderQueue.currentRenderViewCount() == 0); + + // WHEN + QVector renderViews(5); + for (int i = 0; i < 5; ++i) { + renderQueue.queueRenderView(renderViews.at(i), i); + } + // THEN + QCOMPARE(renderQueue.currentRenderViewCount(), 5); + QVERIFY(renderQueue.isFrameQueueComplete()); + + // WHEN + renderQueue.reset(); + QCOMPARE(renderQueue.wasReset(), true); + // THEN + QVERIFY(renderQueue.currentRenderViewCount() == 0); + } +} + +QTEST_APPLESS_MAIN(tst_RenderQueue) + +#include "tst_renderqueue.moc" diff --git a/tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro b/tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro new file mode 100644 index 000000000..b7b8f5b81 --- /dev/null +++ b/tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_renderviewbuilder + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_renderviewbuilder.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp b/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp new file mode 100644 index 000000000..6dc463589 --- /dev/null +++ b/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp @@ -0,0 +1,669 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Paul Lemire +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +class TestAspect : public QRenderAspect +{ +public: + TestAspect(Qt3DCore::QNode *root) + : QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) + , m_jobManager(new Qt3DCore::QAspectJobManager()) + { + Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); + QRenderAspect::onRegistered(); + + QVector nodes; + Qt3DCore::QNodeVisitor v; + v.traverse(root, [&nodes](Qt3DCore::QNode *node) { + Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(node); + d->m_typeInfo = const_cast(Qt3DCore::QNodePrivate::findStaticMetaObject(node->metaObject())); + d->m_hasBackendNode = true; + nodes << node; + }); + + for (const auto node: nodes) + d_func()->createBackendNode({ + node->id(), + Qt3DCore::QNodePrivate::get(node)->m_typeInfo, + Qt3DCore::NodeTreeChange::Added, + node + }); + } + + ~TestAspect() + { + QRenderAspect::onUnregistered(); + } + + Qt3DRender::Render::NodeManagers *nodeManagers() const + { + return d_func()->m_renderer->nodeManagers(); + } + + Render::Renderer *renderer() const + { + return static_cast(d_func()->m_renderer); + } + + Render::MaterialParameterGathererJobPtr materialGathererJob() const + { + Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); + job->setNodeManagers(nodeManagers()); + return job; + } + + void onRegistered() { QRenderAspect::onRegistered(); } + void onUnregistered() { QRenderAspect::onUnregistered(); } + +private: + QScopedPointer m_jobManager; +}; + +} // namespace Qt3DRender + +QT_END_NAMESPACE + +namespace { + +Qt3DCore::QEntity *buildSimpleScene(Qt3DRender::QFrameGraphNode *fg) +{ + Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); + + Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); + renderSettings->setActiveFrameGraph(fg); + root->addComponent(renderSettings); + + // Scene + { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + Qt3DRender::QMaterial *material = new Qt3DRender::QMaterial(); + Qt3DRender::QGeometryRenderer *geometryRenderer = new Qt3DRender::QGeometryRenderer(); + e->addComponent(material); + e->addComponent(geometryRenderer); + e->setParent(root); + } + { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + Qt3DRender::QMaterial *material = new Qt3DRender::QMaterial(); + Qt3DRender::QComputeCommand *computeCommand = new Qt3DRender::QComputeCommand(); + e->addComponent(material); + e->addComponent(computeCommand); + e->setParent(root); + } + + { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + Qt3DRender::QPointLight *light = new Qt3DRender::QPointLight(); + e->addComponent(light); + e->setParent(root); + } + + { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + Qt3DRender::QSpotLight *light = new Qt3DRender::QSpotLight(); + e->addComponent(light); + e->setParent(root); + } + + { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + Qt3DRender::QEnvironmentLight *light = new Qt3DRender::QEnvironmentLight(); + e->addComponent(light); + e->setParent(root); + } + + return root; +} + +Qt3DCore::QEntity *buildEntityFilterTestScene(Qt3DRender::QFrameGraphNode *fg, Qt3DRender::QLayer *layer) +{ + Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); + + Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); + renderSettings->setActiveFrameGraph(fg); + root->addComponent(renderSettings); + + // Scene + for (int i = 0; i < 200; ++i) { + Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); + Qt3DRender::QMaterial *material = new Qt3DRender::QMaterial(); + Qt3DRender::QGeometryRenderer *geometryRenderer = new Qt3DRender::QGeometryRenderer(); + e->addComponent(material); + e->addComponent(geometryRenderer); + if (i % 2 == 0) + e->addComponent(layer); + e->setParent(root); + } + + return root; +} + +} // anonymous + + +class tst_RenderViewBuilder : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + + void checkInitialState() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); + QVERIFY(leafNode != nullptr); + + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + + // THEN + QCOMPARE(renderViewBuilder.renderViewIndex(), 0); + QCOMPARE(renderViewBuilder.renderer(), testAspect.renderer()); + QCOMPARE(renderViewBuilder.layerCacheNeedsToBeRebuilt(), false); + QCOMPARE(renderViewBuilder.materialGathererCacheNeedsToBeRebuilt(), false); + QVERIFY(!renderViewBuilder.renderViewJob().isNull()); + QVERIFY(!renderViewBuilder.frustumCullingJob().isNull()); + QVERIFY(!renderViewBuilder.syncPreFrustumCullingJob().isNull()); + QVERIFY(!renderViewBuilder.setClearDrawBufferIndexJob().isNull()); + + QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); + QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob().isNull()); + QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob().isNull()); + QVERIFY(renderViewBuilder.syncRenderViewPostInitializationJob().isNull()); + + QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), 0); + QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); + + // WHEN + renderViewBuilder.prepareJobs(); + + // THEN + QVERIFY(!renderViewBuilder.syncRenderViewPreCommandUpdateJob().isNull()); + QVERIFY(!renderViewBuilder.syncRenderViewPostCommandUpdateJob().isNull()); + QVERIFY(!renderViewBuilder.syncRenderViewPostInitializationJob().isNull()); + QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); + QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); + + QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); + QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + } + + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); + renderViewBuilder.prepareJobs(); + + // THEN + QCOMPARE(renderViewBuilder.layerCacheNeedsToBeRebuilt(), true); + QVERIFY(!renderViewBuilder.filterEntityByLayerJob().isNull()); + QVERIFY(!renderViewBuilder.syncFilterEntityByLayerJob().isNull()); + + // mark jobs dirty and recheck + QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + } + + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.setMaterialGathererCacheNeedsToBeRebuilt(true); + renderViewBuilder.prepareJobs(); + + // THEN + QCOMPARE(renderViewBuilder.materialGathererCacheNeedsToBeRebuilt(), true); + QCOMPARE(renderViewBuilder.materialGathererJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QVERIFY(!renderViewBuilder.syncMaterialGathererJob().isNull()); + + // mark jobs dirty and recheck + QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 9 + 2 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + } + } + + void checkCheckJobDependencies() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); + QVERIFY(leafNode != nullptr); + + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + + // THEN + // Step 1 + QCOMPARE(renderViewBuilder.renderViewJob()->dependencies().size(), 1); // Depends upon skinning palette update + + + // Step 2 + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().size(), 1); + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().constFirst().toStrongRef().data(), + renderViewBuilder.renderViewJob().data()); + + // Step 3 + QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); + QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); + + QCOMPARE(renderViewBuilder.filterProximityJob()->dependencies().size(), 2); + QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); + + QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().size(), 1); + QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().constFirst().toStrongRef().data(), + renderViewBuilder.syncRenderViewPostInitializationJob().data()); + + QCOMPARE(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().size(), 3); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); + + // Step 4 + QCOMPARE(renderViewBuilder.frustumCullingJob()->dependencies().size(), 2); + QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncPreFrustumCullingJob())); + QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); + + + QCOMPARE(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().size(), renderViewBuilder.materialGathererJobs().size() + 7); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->cacheLightJob())); + + // Step 5 + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { + QCOMPARE(renderViewBuilderJob->dependencies().size(), 1); + QCOMPARE(renderViewBuilderJob->dependencies().constFirst().toStrongRef().data(), + renderViewBuilder.syncRenderViewPreCommandUpdateJob().data()); + } + + // Step 6 + QCOMPARE(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().size(), renderViewBuilder.renderViewCommandUpdaterJobs().size()); + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { + QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().contains(renderViewBuilderJob)); + } + } + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); + renderViewBuilder.setMaterialGathererCacheNeedsToBeRebuilt(true); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + + // THEN + // Step 1 + QCOMPARE(renderViewBuilder.renderViewJob()->dependencies().size(), 1); // Depends upon skinning palette update + + // Step 2 + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().size(), 1); + QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().constFirst().toStrongRef().data(), + renderViewBuilder.renderViewJob().data()); + + // Step 3 + QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->dependencies().size(), 3); + QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(testAspect.renderer()->updateEntityLayersJob())); + QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(testAspect.renderer()->updateTreeEnabledJob())); + + QCOMPARE(renderViewBuilder.syncFilterEntityByLayerJob()->dependencies().size(), 1); + QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob()->dependencies().contains(renderViewBuilder.filterEntityByLayerJob())); + + QCOMPARE(renderViewBuilder.filterProximityJob()->dependencies().size(), 2); + QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); + + QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().size(), 1); + QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().constFirst().toStrongRef().data(), + renderViewBuilder.syncRenderViewPostInitializationJob().data()); + + QCOMPARE(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().size(), 3); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); + QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); + + for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { + QCOMPARE(materialGatherer->dependencies().size(), 3); + QVERIFY(materialGatherer->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(materialGatherer->dependencies().contains(testAspect.renderer()->introspectShadersJob())); + QVERIFY(materialGatherer->dependencies().contains(testAspect.renderer()->filterCompatibleTechniqueJob())); + } + + // Step 4 + QCOMPARE(renderViewBuilder.frustumCullingJob()->dependencies().size(), 2); + QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncPreFrustumCullingJob())); + QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); + + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncFilterEntityByLayerJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); + QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); + + // Step 5 + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { + QCOMPARE(renderViewBuilderJob->dependencies().size(), 1); + QCOMPARE(renderViewBuilderJob->dependencies().constFirst().toStrongRef().data(), + renderViewBuilder.syncRenderViewPreCommandUpdateJob().data()); + } + + // Step 6 + QCOMPARE(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().size(), renderViewBuilder.renderViewCommandUpdaterJobs().size()); + for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { + QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().contains(renderViewBuilderJob)); + } + } + } + + void checkRenderViewJobExecution() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); + QVERIFY(leafNode != nullptr); + + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + renderViewBuilder.renderViewJob()->run(); + + // THEN + QVERIFY(renderViewBuilder.renderViewJob()->renderView() != nullptr); + } + + void checkLightGatherExecution() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); + QVERIFY(leafNode != nullptr); + + // WHEN + renderer->lightGathererJob()->run(); + + // THEN + QCOMPARE(renderer->lightGathererJob()->lights().size(), 2); + QVERIFY(renderer->lightGathererJob()->takeEnvironmentLight() != nullptr); + } + + void checkRenderableEntitiesFilteringExecution() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); + QVERIFY(leafNode != nullptr); + + // WHEN + renderer->renderableEntityFilterJob()->run(); + + // THEN + QCOMPARE(renderer->renderableEntityFilterJob()->filteredEntities().size(), 1); + } + + void checkComputableEntitiesFilteringExecution() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); + QVERIFY(leafNode != nullptr); + + // WHEN + renderer->computableEntityFilterJob()->run(); + + // THEN + QCOMPARE(renderer->computableEntityFilterJob()->filteredEntities().size(), 1); + } + + void checkSyncRenderViewInitializationExecution() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::QLayerFilter *layerFilter = new Qt3DRender::QLayerFilter(clearBuffer); + Qt3DRender::QFrustumCulling *frustumCulling = new Qt3DRender::QFrustumCulling(layerFilter); + Qt3DRender::QTechniqueFilter *techniqueFilter = new Qt3DRender::QTechniqueFilter(frustumCulling); + Qt3DRender::QRenderPassFilter *renderPassFilter = new Qt3DRender::QRenderPassFilter(techniqueFilter); + Qt3DRender::QLayer *layer = new Qt3DRender::QLayer(); + + layerFilter->addLayer(layer); + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFilter->id()); + QVERIFY(leafNode != nullptr); + + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + + // THEN + QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), false); + for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { + QVERIFY(materialGatherer->techniqueFilter() == nullptr); + QVERIFY(materialGatherer->renderPassFilter() == nullptr); + } + + // WHEN + renderViewBuilder.renderViewJob()->run(); + renderViewBuilder.syncRenderViewPostInitializationJob()->run(); + + // THEN + QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true); + for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { + QVERIFY(materialGatherer->techniqueFilter() != nullptr); + QVERIFY(materialGatherer->renderPassFilter() != nullptr); + } + } + { + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + + // THEN + QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), false); + QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->hasLayerFilter(), false); + QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->layerFilters().size(), 0); + for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { + QVERIFY(materialGatherer->techniqueFilter() == nullptr); + QVERIFY(materialGatherer->renderPassFilter() == nullptr); + } + + // WHEN + renderViewBuilder.renderViewJob()->run(); + renderViewBuilder.syncRenderViewPostInitializationJob()->run(); + + // THEN + QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true); + QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->hasLayerFilter(), true); + QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->layerFilters().size(), 1); + for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { + QVERIFY(materialGatherer->techniqueFilter() != nullptr); + QVERIFY(materialGatherer->renderPassFilter() != nullptr); + } + } + } + + void checkSyncFrustumCullingExecution() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::QFrustumCulling *frustumCulling = new Qt3DRender::QFrustumCulling(clearBuffer); + Qt3DRender::QCameraSelector *cameraSelector = new Qt3DRender::QCameraSelector(frustumCulling); + Qt3DRender::QCamera *camera = new Qt3DRender::QCamera(); + cameraSelector->setCamera(camera); + + Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(cameraSelector->id()); + QVERIFY(leafNode != nullptr); + + // WHEN + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + + // THEN + QCOMPARE(renderViewBuilder.frustumCullingJob()->viewProjection(), Matrix4x4()); + + // WHEN + renderViewBuilder.renderViewJob()->run(); + renderViewBuilder.syncPreFrustumCullingJob()->run(); + + // THEN + QCOMPARE(convertToQMatrix4x4(renderViewBuilder.frustumCullingJob()->viewProjection()), camera->projectionMatrix() * camera->viewMatrix()); + } + + void checkRemoveEntitiesNotInSubset() + { + // GIVEN + Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); + Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); + Qt3DRender::QLayerFilter *layerFilter = new Qt3DRender::QLayerFilter(clearBuffer); + Qt3DRender::QLayer *layer = new Qt3DRender::QLayer(); + layerFilter->addLayer(layer); + Qt3DRender::TestAspect testAspect(buildEntityFilterTestScene(viewport, layer)); + Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + + // THEN + Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(layerFilter->id()); + QVERIFY(leafNode != nullptr); + + // WHEN + renderer->markDirty(Qt3DRender::Render::AbstractRenderer::AllDirty, nullptr); + + Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); + renderViewBuilder.prepareJobs(); + renderViewBuilder.buildJobHierachy(); + + renderer->renderableEntityFilterJob()->run(); + renderer->cacheRenderableEntitiesJob()->run(); + + renderViewBuilder.renderViewJob()->run(); + renderViewBuilder.syncRenderViewPostInitializationJob()->run(); + renderViewBuilder.filterEntityByLayerJob()->run(); + + QVector renderableEntity = renderer->renderableEntityFilterJob()->filteredEntities(); + QVector filteredEntity = renderViewBuilder.filterEntityByLayerJob()->filteredEntities(); + + // THEN + QCOMPARE(renderableEntity.size(), 200); + QCOMPARE(filteredEntity.size(), 100); + + std::sort(renderableEntity.begin(), renderableEntity.end()); + + // WHEN + renderableEntity = Qt3DRender::Render::RenderViewBuilder::entitiesInSubset(renderableEntity, filteredEntity); + + // THEN + QCOMPARE(renderableEntity.size(), 100); + for (const auto entity : renderableEntity) { + QVERIFY(filteredEntity.contains(entity)); + } + } + +}; + +QTEST_MAIN(tst_RenderViewBuilder) + +#include "tst_renderviewbuilder.moc" diff --git a/tests/auto/render/opengl/renderviews/renderviews.pro b/tests/auto/render/opengl/renderviews/renderviews.pro new file mode 100644 index 000000000..7efbaec14 --- /dev/null +++ b/tests/auto/render/opengl/renderviews/renderviews.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_renderviews + +QT += 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_renderviews.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/renderviews/tst_renderviews.cpp b/tests/auto/render/opengl/renderviews/tst_renderviews.cpp new file mode 100644 index 000000000..d30b8ddca --- /dev/null +++ b/tests/auto/render/opengl/renderviews/tst_renderviews.cpp @@ -0,0 +1,554 @@ +/**************************************************************************** +** +** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { + +namespace Render { + +namespace { + +void compareShaderParameterPacks(const ShaderParameterPack &t1, + const ShaderParameterPack &t2) +{ + const PackUniformHash hash1 = t1.uniforms(); + const PackUniformHash hash2 = t2.uniforms(); + + QCOMPARE(hash1.keys.size(), hash2.keys.size()); + + for (int i = 0, m = hash1.keys.size(); i < m; ++i) { + const int key = hash1.keys.at(i); + QCOMPARE(hash1.value(key), hash2.value(key)); + } +} + +} // anonymous + +class tst_RenderViews : public Qt3DCore::QBackendNodeTester +{ + Q_OBJECT + +private Q_SLOTS: + + void checkRenderViewSizeFitsWithAllocator() + { + QSKIP("Allocated Disabled"); + QVERIFY(sizeof(RenderView) <= 192); + QVERIFY(sizeof(RenderView::InnerData) <= 192); + } + + void checkRenderViewInitialState() + { + // GIVEN + RenderView renderView; + + // THEN + QCOMPARE(renderView.memoryBarrier(), QMemoryBarrier::None); + } + + void checkMemoryBarrierInitialization() + { + // GIVEN + RenderView renderView; + + // THEN + QCOMPARE(renderView.memoryBarrier(), QMemoryBarrier::None); + + // WHEN + const QMemoryBarrier::Operations barriers(QMemoryBarrier::BufferUpdate|QMemoryBarrier::ShaderImageAccess); + renderView.setMemoryBarrier(barriers); + + // THEN + QCOMPARE(renderView.memoryBarrier(), barriers); + } + + void checkSetRenderViewConfig() + { + TestRenderer renderer; + { + // GIVEN + const QMemoryBarrier::Operations barriers(QMemoryBarrier::AtomicCounter|QMemoryBarrier::ShaderStorage); + Qt3DRender::QMemoryBarrier frontendBarrier; + FrameGraphManager frameGraphManager; + MemoryBarrier backendBarrier; + RenderView renderView; + // setRenderViewConfigFromFrameGraphLeafNode assumes node has a manager + backendBarrier.setFrameGraphManager(&frameGraphManager); + backendBarrier.setRenderer(&renderer); + + // WHEN + frontendBarrier.setWaitOperations(barriers); + simulateInitializationSync(&frontendBarrier, &backendBarrier); + + // THEN + QCOMPARE(renderView.memoryBarrier(), QMemoryBarrier::None); + QCOMPARE(backendBarrier.waitOperations(), barriers); + + // WHEN + Qt3DRender::Render::setRenderViewConfigFromFrameGraphLeafNode(&renderView, &backendBarrier); + + // THEN + QCOMPARE(backendBarrier.waitOperations(), renderView.memoryBarrier()); + } + // TO DO: Complete tests for other framegraph node types + } + + void checkRenderCommandBackToFrontSorting() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + RenderView renderView; + QVector rawCommands; + QVector sortTypes; + + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + + sortTypes.push_back(QSortPolicy::BackToFront); + + for (int i = 0; i < 200; ++i) { + RenderCommand c; + c.m_depth = float(i); + rawCommands.push_back(c); + } + + // WHEN + renderView.addSortType(sortTypes); + renderView.setCommands(rawCommands); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands.size(), sortedCommands.size()); + for (int j = 1; j < sortedCommands.size(); ++j) + QVERIFY(sortedCommands.at(j - 1).m_depth > sortedCommands.at(j).m_depth); + + // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); + } + + void checkRenderCommandMaterialSorting() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + RenderView renderView; + QVector rawCommands; + QVector sortTypes; + + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + + sortTypes.push_back(QSortPolicy::Material); + + GLShader *dnas[5] = { + reinterpret_cast(0x250), + reinterpret_cast(0x500), + reinterpret_cast(0x1000), + reinterpret_cast(0x1500), + reinterpret_cast(0x2000) + }; + + for (int i = 0; i < 20; ++i) { + RenderCommand c; + c.m_glShader = dnas[i % 5]; + rawCommands.push_back(c); + } + + // WHEN + renderView.addSortType(sortTypes); + renderView.setCommands(rawCommands); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands.size(), sortedCommands.size()); + GLShader *targetShader; + + for (int j = 0; j < sortedCommands.size(); ++j) { + + if (j % 4 == 0) { + targetShader = sortedCommands.at(j).m_glShader; + if (j > 0) + QVERIFY(targetShader != sortedCommands.at(j - 1).m_glShader); + } + QCOMPARE(targetShader, sortedCommands.at(j).m_glShader); + } + + // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); + } + + void checkRenderViewUniformMinification_data() + { + QTest::addColumn>("shaders"); + QTest::addColumn>("rawParameters"); + QTest::addColumn>("expectedMinimizedParameters"); + + Qt3DCore::QNodeId fakeTextureNodeId = Qt3DCore::QNodeId::createId(); + + ShaderParameterPack pack1; + pack1.setUniform(1, UniformValue(883)); + pack1.setUniform(2, UniformValue(1584.0f)); + pack1.setTexture(3, 0, fakeTextureNodeId); + + QShaderProgram *shader1 = new QShaderProgram(); + QShaderProgram *shader2 = new QShaderProgram(); + + shader1->setShaderCode(QShaderProgram::Vertex, QByteArrayLiteral("1")); + shader2->setShaderCode(QShaderProgram::Vertex, QByteArrayLiteral("2")); + + ShaderParameterPack minifiedPack1; + + QTest::newRow("NoMinification") + << (QVector() << shader1 << shader2) + << (QVector() << pack1 << pack1) + << (QVector() << pack1 << pack1); + + QTest::newRow("SingleShaderMinified") + << (QVector() << shader1 << shader1 << shader1) + << (QVector() << pack1 << pack1 << pack1) + << (QVector() << pack1 << minifiedPack1 << minifiedPack1); + + QTest::newRow("MultipleShadersMinified") + << (QVector() << shader1 << shader1 << shader1 << shader2 << shader2 << shader2) + << (QVector() << pack1 << pack1 << pack1 << pack1 << pack1 << pack1) + << (QVector() << pack1 << minifiedPack1 << minifiedPack1 << pack1 << minifiedPack1 << minifiedPack1); + } + + void checkRenderViewUniformMinification() + { + QFETCH(QVector, shaders); + QFETCH(QVector, rawParameters); + QFETCH(QVector, expectedMinimizedParameters); + + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + renderer.setNodeManagers(&nodeManagers); + + GLShaderManager *shaderManager = renderer.glResourceManagers()->glShaderManager(); + for (int i = 0, m = shaders.size(); i < m; ++i) { + Shader* backend = new Shader(); + backend->setRenderer(&renderer); + simulateInitializationSync(shaders.at(i), backend); + shaderManager->createOrAdoptExisting(backend); + } + + RenderView renderView; + QVector rawCommands; + renderView.setRenderer(&renderer); + + for (int i = 0, m = shaders.size(); i < m; ++i) { + RenderCommand c; + c.m_shaderId = shaders.at(i)->id(); + c.m_glShader = shaderManager->lookupResource(c.m_shaderId); + c.m_parameterPack = rawParameters.at(i); + rawCommands.push_back(c); + } + + // WHEN + renderView.setCommands(rawCommands); + renderView.addSortType((QVector() << QSortPolicy::Uniform)); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands, sortedCommands); + + for (int i = 0, m = shaders.size(); i < m; ++i) { + const RenderCommand c = sortedCommands.at(i); + QCOMPARE(c.m_shaderId, shaders.at(i)->id()); + compareShaderParameterPacks(c.m_parameterPack, expectedMinimizedParameters.at(i)); + } + + renderer.shutdown(); + } + + + void checkRenderCommandFrontToBackSorting() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + RenderView renderView; + QVector rawCommands; + QVector sortTypes; + + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + + sortTypes.push_back(QSortPolicy::FrontToBack); + + for (int i = 0; i < 200; ++i) { + RenderCommand c; + c.m_depth = float(i); + rawCommands.push_back(c); + } + + // WHEN + renderView.addSortType(sortTypes); + renderView.setCommands(rawCommands); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands.size(), sortedCommands.size()); + for (int j = 1; j < sortedCommands.size(); ++j) + QVERIFY(sortedCommands.at(j - 1).m_depth < sortedCommands.at(j).m_depth); + + // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); + } + + void checkRenderCommandStateCostSorting() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + RenderView renderView; + QVector rawCommands; + QVector sortTypes; + + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + + sortTypes.push_back(QSortPolicy::StateChangeCost); + + for (int i = 0; i < 200; ++i) { + RenderCommand c; + c.m_changeCost = i; + rawCommands.push_back(c); + } + + // WHEN + renderView.addSortType(sortTypes); + renderView.setCommands(rawCommands); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands.size(), sortedCommands.size()); + for (int j = 1; j < sortedCommands.size(); ++j) + QVERIFY(sortedCommands.at(j - 1).m_changeCost > sortedCommands.at(j).m_changeCost); + + // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); + } + + void checkRenderCommandCombinedStateMaterialDepthSorting() + { + // GIVEN + Qt3DRender::Render::NodeManagers nodeManagers; + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + RenderView renderView; + QVector rawCommands; + QVector sortTypes; + + renderer.setNodeManagers(&nodeManagers); + renderView.setRenderer(&renderer); + + sortTypes.push_back(QSortPolicy::StateChangeCost); + sortTypes.push_back(QSortPolicy::Material); + sortTypes.push_back(QSortPolicy::BackToFront); + + GLShader *dna[5] = { + reinterpret_cast(0x250), + reinterpret_cast(0x500), + reinterpret_cast(0x1000), + reinterpret_cast(0x1500), + reinterpret_cast(0x2000) + }; + + float depth[3] = { + 10.0f, + 25.0f, + 30.0f + }; + + int stateChangeCost[2] = { + 100, + 200 + }; + + auto buildRC = [] (GLShader *dna, float depth, int changeCost) { + RenderCommand c; + c.m_glShader = dna; + c.m_depth = depth; + c.m_changeCost = changeCost; + return c; + }; + + RenderCommand c5 = buildRC(dna[3], depth[1], stateChangeCost[1]); + RenderCommand c3 = buildRC(dna[3], depth[0], stateChangeCost[1]); + RenderCommand c4 = buildRC(dna[2], depth[1], stateChangeCost[1]); + RenderCommand c8 = buildRC(dna[1], depth[1], stateChangeCost[1]); + RenderCommand c0 = buildRC(dna[0], depth[2], stateChangeCost[1]); + + RenderCommand c2 = buildRC(dna[2], depth[2], stateChangeCost[0]); + RenderCommand c9 = buildRC(dna[2], depth[0], stateChangeCost[0]); + RenderCommand c1 = buildRC(dna[1], depth[0], stateChangeCost[0]); + RenderCommand c7 = buildRC(dna[0], depth[2], stateChangeCost[0]); + RenderCommand c6 = buildRC(dna[0], depth[1], stateChangeCost[0]); + + rawCommands << c0 << c1 << c2 << c3 << c4 << c5 << c6 << c7 << c8 << c9; + + // WHEN + renderView.addSortType(sortTypes); + renderView.setCommands(rawCommands); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands.size(), sortedCommands.size()); + + // Ordered by higher state, higher shaderDNA and higher depth + QCOMPARE(c0, sortedCommands.at(4)); + QCOMPARE(c3, sortedCommands.at(1)); + QCOMPARE(c4, sortedCommands.at(2)); + QCOMPARE(c5, sortedCommands.at(0)); + QCOMPARE(c8, sortedCommands.at(3)); + + QCOMPARE(c1, sortedCommands.at(7)); + QCOMPARE(c2, sortedCommands.at(5)); + QCOMPARE(c6, sortedCommands.at(9)); + QCOMPARE(c7, sortedCommands.at(8)); + QCOMPARE(c9, sortedCommands.at(6)); + + // RenderCommands are deleted by RenderView dtor + renderer.shutdown(); + } + + void checkRenderCommandTextureSorting() + { + // GIVEN + RenderView renderView; + QVector sortTypes; + + sortTypes.push_back(QSortPolicy::Texture); + + + Qt3DCore::QNodeId tex1 = Qt3DCore::QNodeId::createId(); + Qt3DCore::QNodeId tex2 = Qt3DCore::QNodeId::createId(); + Qt3DCore::QNodeId tex3 = Qt3DCore::QNodeId::createId(); + Qt3DCore::QNodeId tex4 = Qt3DCore::QNodeId::createId(); + + RenderCommand a; + { + ShaderParameterPack pack; + pack.setTexture(0, 0, tex1); + pack.setTexture(1, 0, tex3); + pack.setTexture(2, 0, tex4); + pack.setTexture(3, 0, tex2); + a.m_parameterPack = pack; + } + RenderCommand b; + RenderCommand c; + { + ShaderParameterPack pack; + pack.setTexture(0, 0, tex1); + pack.setTexture(3, 0, tex2); + c.m_parameterPack = pack; + } + RenderCommand d; + { + ShaderParameterPack pack; + pack.setTexture(1, 0, tex3); + pack.setTexture(2, 0, tex4); + d.m_parameterPack = pack; + } + RenderCommand e; + { + ShaderParameterPack pack; + pack.setTexture(3, 0, tex2); + e.m_parameterPack = pack; + } + RenderCommand f; + { + ShaderParameterPack pack; + pack.setTexture(3, 0, tex2); + f.m_parameterPack = pack; + } + RenderCommand g; + { + ShaderParameterPack pack; + pack.setTexture(0, 0, tex1); + pack.setTexture(1, 0, tex3); + pack.setTexture(2, 0, tex4); + pack.setTexture(3, 0, tex2); + g.m_parameterPack = pack; + } + + // WHEN + QVector rawCommands = {a, b, c, d, e, f, g}; + renderView.addSortType(sortTypes); + renderView.setCommands(rawCommands); + renderView.sort(); + + // THEN + const QVector sortedCommands = renderView.commands(); + QCOMPARE(rawCommands.size(), sortedCommands.size()); + QCOMPARE(sortedCommands.at(0), a); + QCOMPARE(sortedCommands.at(1), g); + QCOMPARE(sortedCommands.at(2), d); + QCOMPARE(sortedCommands.at(3), c); + QCOMPARE(sortedCommands.at(4), e); + QCOMPARE(sortedCommands.at(5), f); + QCOMPARE(sortedCommands.at(6), b); + // RenderCommands are deleted by RenderView dtor + } +private: +}; + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +//APPLESS_ +QTEST_MAIN(Qt3DRender::Render::tst_RenderViews) + +#include "tst_renderviews.moc" diff --git a/tests/auto/render/opengl/renderviewutils/renderviewutils.pro b/tests/auto/render/opengl/renderviewutils/renderviewutils.pro new file mode 100644 index 000000000..e9c9f8d51 --- /dev/null +++ b/tests/auto/render/opengl/renderviewutils/renderviewutils.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_renderviewutils + +QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_renderviewutils.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp b/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp new file mode 100644 index 000000000..8a345d840 --- /dev/null +++ b/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp @@ -0,0 +1,801 @@ +/**************************************************************************** +** +** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "testrenderer.h" +#include "testpostmanarbiter.h" + +class tst_RenderViewUtils : public Qt3DCore::QBackendNodeTester +{ + Q_OBJECT +private Q_SLOTS: + void topLevelScalarValueNoUniforms(); + void topLevelScalarValue(); + void topLevelTextureValueNoUniforms(); + void topLevelTextureValue(); + void topLevelArrayValue(); + void nestedShaderDataValue(); + void topLevelStructValue_data(); + void topLevelStructValue(); + void topLevelDynamicProperties(); + void transformedProperties(); + void shouldNotifyDynamicPropertyChanges(); + +private: + void initBackendShaderData(Qt3DRender::Render::AbstractRenderer *renderer, + Qt3DRender::QShaderData *frontend, + Qt3DRender::Render::ShaderDataManager *manager) + { + // Create children first + for (QObject *c : frontend->children()) { + Qt3DRender::QShaderData *cShaderData = qobject_cast(c); + if (cShaderData) + initBackendShaderData(renderer, cShaderData, manager); + } + + // Create backend element for frontend one + Qt3DRender::Render::ShaderData *backend = manager->getOrCreateResource(frontend->id()); + // Init the backend element + backend->setRenderer(renderer); + simulateInitializationSync(frontend, backend); + } + + void initBackendTexture(Qt3DRender::QAbstractTexture *frontend, + Qt3DRender::Render::TextureManager *manager) + { + // Create backend element for frontend one + Qt3DRender::Render::Texture *backend = manager->getOrCreateResource(frontend->id()); + // Init the backend element + simulateInitialization(frontend, backend); + } +}; + +class ScalarShaderData : public Qt3DRender::QShaderData +{ + Q_OBJECT + Q_PROPERTY(float scalar READ scalar WRITE setScalar NOTIFY scalarChanged) + +public: + ScalarShaderData(Qt3DCore::QNode *parent = nullptr) + : Qt3DRender::QShaderData(parent) + , m_scalar(0.0f) + { + } + + void setScalar(float scalar) + { + if (scalar != m_scalar) { + m_scalar = scalar; + emit scalarChanged(); + } + } + + float scalar() const + { + return m_scalar; + } + + QHash buildUniformMap(const QString &blockName) + { + QHash uniforms; + + uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform()); + + return uniforms; + } + +Q_SIGNALS: + void scalarChanged(); + +private: + float m_scalar; +}; + +class TextureShaderData : public Qt3DRender::QShaderData +{ + Q_OBJECT + Q_PROPERTY(Qt3DRender::QAbstractTexture* texture READ texture WRITE setTexture NOTIFY textureChanged) + +public: + TextureShaderData() + : Qt3DRender::QShaderData() + , m_texture(nullptr) + { + } + + void setTexture(Qt3DRender::QAbstractTexture *texture) + { + if (texture != m_texture) { + m_texture = texture; + emit textureChanged(); + } + } + + Qt3DRender::QAbstractTexture *texture() const + { + return m_texture; + } + + QHash buildUniformMap(const QString &blockName) + { + QHash uniforms; + + uniforms.insert(blockName + QStringLiteral(".texture"), Qt3DRender::Render::ShaderUniform()); + + return uniforms; + } + +Q_SIGNALS: + void textureChanged(); + +private: + Qt3DRender::QAbstractTexture *m_texture; +}; + + +class ArrayShaderData : public Qt3DRender::QShaderData +{ + Q_OBJECT + Q_PROPERTY(QVariantList array READ array WRITE setArray NOTIFY arrayChanged) + +public: + ArrayShaderData() + : Qt3DRender::QShaderData() + { + } + + void setArray(const QVariantList &array) + { + if (array != m_array) { + m_array = array; + emit arrayChanged(); + } + } + + QVariantList array() const + { + return m_array; + } + + QHash buildUniformMap(const QString &blockName) + { + QHash uniforms; + + uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform()); + + return uniforms; + } + +Q_SIGNALS: + void arrayChanged(); + +private: + QVariantList m_array; +}; + +class StructShaderData : public Qt3DRender::QShaderData +{ + Q_OBJECT + Q_PROPERTY(float scalar READ scalar WRITE setScalar NOTIFY scalarChanged) + Q_PROPERTY(QVariantList array READ array WRITE setArray NOTIFY arrayChanged) + +public: + StructShaderData() + : Qt3DRender::QShaderData() + , m_scalar(0.0f) + { + } + + void setScalar(float scalar) + { + if (scalar != m_scalar) { + m_scalar = scalar; + emit scalarChanged(); + } + } + + float scalar() const + { + return m_scalar; + } + + void setArray(const QVariantList &array) + { + if (array != m_array) { + m_array = array; + emit arrayChanged(); + } + } + + QVariantList array() const + { + return m_array; + } + + virtual QHash buildUniformMap(const QString &blockName) + { + QHash uniforms; + + uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform()); + uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform()); + + return uniforms; + } + + virtual QHash buildUniformMapValues(const QString &blockName) + { + QHash uniforms; + + uniforms.insert(blockName + QStringLiteral(".scalar"), QVariant(scalar())); + uniforms.insert(blockName + QStringLiteral(".array[0]"), QVariant(array())); + + return uniforms; + } + +Q_SIGNALS: + void scalarChanged(); + void arrayChanged(); + +private: + float m_scalar; + QVariantList m_array; +}; + +class MultiLevelStructShaderData : public StructShaderData +{ + Q_OBJECT + Q_PROPERTY(Qt3DRender::QShaderData *inner READ inner WRITE setInner NOTIFY innerChanged) + +public: + MultiLevelStructShaderData() + : StructShaderData() + , m_inner(nullptr) + { + } + + void setInner(Qt3DRender::QShaderData *inner) + { + if (inner != m_inner) { + m_inner = inner; + emit innerChanged(); + } + } + + Qt3DRender::QShaderData *inner() const + { + return m_inner; + } + + QHash buildUniformMap(const QString &blockName) override + { + QHash innerUniforms; + + StructShaderData *innerData = nullptr; + if ((innerData = qobject_cast(m_inner)) != nullptr) + innerUniforms = innerData->buildUniformMap(QStringLiteral(".inner")); + + QHash uniforms = StructShaderData::buildUniformMap(blockName); + QHash::const_iterator it = innerUniforms.begin(); + const QHash::const_iterator end = innerUniforms.end(); + + while (it != end) { + uniforms.insert(blockName + it.key(), it.value()); + ++it; + } + return uniforms; + } + + QHash buildUniformMapValues(const QString &blockName) override + { + QHash innerUniformsValues; + + StructShaderData *innerData = nullptr; + if ((innerData = qobject_cast(m_inner)) != nullptr) + innerUniformsValues = innerData->buildUniformMapValues(QStringLiteral(".inner")); + + QHash uniformsValues = StructShaderData::buildUniformMapValues(blockName); + QHash::const_iterator it = innerUniformsValues.begin(); + const QHash::const_iterator end = innerUniformsValues.end(); + + while (it != end) { + uniformsValues.insert(blockName + it.key(), it.value()); + ++it; + } + + return uniformsValues; + } + +Q_SIGNALS: + void innerChanged(); + +private: + Qt3DRender::QShaderData *m_inner; +}; + +void tst_RenderViewUtils::topLevelScalarValueNoUniforms() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer shaderData(new ScalarShaderData()); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + shaderData->setScalar(883.0f); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEB + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("")); + + // THEN + // activeUniformNamesToValue should be empty as blockBuilder.uniforms is + QVERIFY(blockBuilder.activeUniformNamesToValue.isEmpty()); +} + +void tst_RenderViewUtils::topLevelScalarValue() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer shaderData(new ScalarShaderData()); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + shaderData->setScalar(883.0f); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + blockBuilder.uniforms = shaderData->buildUniformMap(QStringLiteral("MyBlock")); + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); + + // THEN + QVERIFY(blockBuilder.uniforms.count() == 1); + QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + + while (it != end) { + // THEN + QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); + QCOMPARE(it.value(), QVariant(shaderData->scalar())); + ++it; + } +} + +void tst_RenderViewUtils::topLevelTextureValueNoUniforms() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer shaderData(new TextureShaderData); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager); + QScopedPointer texture(new Qt3DRender::QTexture2D); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + shaderData->setTexture(texture.data()); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEB + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("")); + + // THEN + // activeUniformNamesToValue should be empty as blockBuilder.uniforms is + QVERIFY(blockBuilder.activeUniformNamesToValue.isEmpty()); +} + +void tst_RenderViewUtils::topLevelTextureValue() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer shaderData(new TextureShaderData); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager); + QScopedPointer texture(new Qt3DRender::QTexture2D); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + initBackendTexture(texture.data(), textureManager.data()); + shaderData->setTexture(texture.data()); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + blockBuilder.uniforms = shaderData->buildUniformMap(QStringLiteral("MyBlock")); + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); + + // THEN + QVERIFY(blockBuilder.uniforms.count() == 1); + QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + + while (it != end) { + // THEN + QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); + QCOMPARE(it.value(), QVariant::fromValue(shaderData->texture()->id())); + ++it; + } +} + +void tst_RenderViewUtils::topLevelArrayValue() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer shaderData(new ArrayShaderData()); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + QVariantList arrayValues = QVariantList() << 454 << 350 << 383 << 427 << 552; + shaderData->setArray(arrayValues); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + blockBuilder.uniforms = shaderData->buildUniformMap(QStringLiteral("MyBlock")); + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); + + // THEN + QVERIFY(blockBuilder.uniforms.count() == 1); + QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + + while (it != end) { + // THEN + QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); + QCOMPARE(it.value(), QVariant(arrayValues)); + ++it; + } +} + +void tst_RenderViewUtils::nestedShaderDataValue() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer arrayShaderData(new ArrayShaderData()); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + QScopedPointer shaderData1(new ScalarShaderData(arrayShaderData.data())); + QScopedPointer shaderData2(new ScalarShaderData(arrayShaderData.data())); + QScopedPointer shaderData3(new ScalarShaderData(arrayShaderData.data())); + + shaderData1->setScalar(883.0f); + shaderData2->setScalar(1200.0f); + shaderData3->setScalar(1340.0f); + QHash scalarValues; + scalarValues[QStringLiteral("MyBlock.array[0].scalar")] = shaderData1->scalar(); + scalarValues[QStringLiteral("MyBlock.array[1].scalar")] = shaderData2->scalar(); + scalarValues[QStringLiteral("MyBlock.array[2].scalar")] = shaderData3->scalar(); + + + const Qt3DCore::QNodeId id1 = shaderData1->id(); + const Qt3DCore::QNodeId id2 = shaderData2->id(); + const Qt3DCore::QNodeId id3 = shaderData3->id(); + + // WHEN + const QVariantList arrayValues = QVariantList() << QVariant::fromValue(id1) << QVariant::fromValue(id2) << QVariant::fromValue(id3); + arrayShaderData->setArray(arrayValues); + initBackendShaderData(&renderer, arrayShaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendArrayShaderData = manager->lookupResource(arrayShaderData->id()); + Qt3DRender::Render::ShaderData *backendShaderData1 = manager->lookupResource(id1); + Qt3DRender::Render::ShaderData *backendShaderData2 = manager->lookupResource(id2); + Qt3DRender::Render::ShaderData *backendShaderData3 = manager->lookupResource(id3); + QVERIFY(backendArrayShaderData != nullptr); + QVERIFY(backendShaderData1 != nullptr); + QVERIFY(backendShaderData2 != nullptr); + QVERIFY(backendShaderData3 != nullptr); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0].scalar"), Qt3DRender::Render::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[1].scalar"), Qt3DRender::Render::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[2].scalar"), Qt3DRender::Render::ShaderUniform()); + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendArrayShaderData, QStringLiteral("MyBlock")); + + // THEN + QVERIFY(blockBuilder.uniforms.count() == 3); + QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 3); + + // WHEN + auto it = blockBuilder.uniforms.cbegin(); + const auto end = blockBuilder.uniforms.cend(); + + while (it != end) { + // THEN + const int nameId = Qt3DRender::Render::StringToInt::lookupId(it.key()); + QVERIFY(blockBuilder.activeUniformNamesToValue.contains(nameId)); + QCOMPARE(blockBuilder.activeUniformNamesToValue[nameId], scalarValues.value(it.key())); + ++it; + } +} + +void tst_RenderViewUtils::topLevelStructValue_data() +{ + QTest::addColumn("shaderData"); + QTest::addColumn("blockName"); + + QVariantList arrayValues2 = QVariantList() << 180 << 220 << 250 << 270 << 300 << 350 << 550; + QVariantList arrayValues = QVariantList() << 454 << 350 << 383 << 427 << 552; + + MultiLevelStructShaderData *twoLevelsNestedShaderData = new MultiLevelStructShaderData(); + MultiLevelStructShaderData *singleLevelShaderData = new MultiLevelStructShaderData(); + StructShaderData *shaderData = new StructShaderData(); + + // Don't forget to set the parent so that initBackendShaderData + // properly initializes nested members + shaderData->setParent(singleLevelShaderData); + shaderData->setArray(arrayValues); + shaderData->setScalar(1584.0f); + + singleLevelShaderData->setParent(twoLevelsNestedShaderData); + singleLevelShaderData->setInner(shaderData); + singleLevelShaderData->setScalar(1200.0f); + singleLevelShaderData->setArray(arrayValues2); + + twoLevelsNestedShaderData->setInner(singleLevelShaderData); + twoLevelsNestedShaderData->setArray(arrayValues + arrayValues2); + twoLevelsNestedShaderData->setScalar(1340.0f); + + QTest::newRow("simple struct") << shaderData << QStringLiteral("Block"); + QTest::newRow("single level inner struct") << (StructShaderData *)singleLevelShaderData << QStringLiteral("Block"); + QTest::newRow("tow level inner struct") << (StructShaderData *)twoLevelsNestedShaderData << QStringLiteral("Block"); +} + +void tst_RenderViewUtils::topLevelStructValue() +{ + // GIVEN + TestRenderer renderer; + QFETCH(StructShaderData *, shaderData); + QFETCH(QString, blockName); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + initBackendShaderData(&renderer, shaderData, manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + blockBuilder.uniforms = shaderData->buildUniformMap(blockName); + const QHash expectedValues = shaderData->buildUniformMapValues(blockName); + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, blockName); + + // THEN + QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), blockBuilder.uniforms.count()); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + + while (it != end) { + // THEN + QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); + QVERIFY(expectedValues.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); + QCOMPARE(it.value(), expectedValues.value(Qt3DRender::Render::StringToInt::lookupString(it.key()))); + ++it; + } +} + +void tst_RenderViewUtils::topLevelDynamicProperties() +{ + // GIVEN + TestRenderer renderer; + QScopedPointer shaderData(new Qt3DRender::QShaderData()); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + QScopedPointer texture(new Qt3DRender::QTexture2D); + QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); + + // WHEN + initBackendTexture(texture.data(), textureManager.data()); + shaderData->setProperty("scalar", 883.0f); + shaderData->setProperty("array", QVariantList() << 454 << 350 << 383 << 427 << 552); + shaderData->setProperty("texture", QVariant::fromValue(texture.data())); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + + // WHEN + Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + blockBuilder.shaderDataManager = manager.data(); + blockBuilder.textureManager = textureManager.data(); + blockBuilder.updatedPropertiesOnly = false; + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.scalar"), Qt3DRender::Render::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0]"), Qt3DRender::Render::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.texture"), Qt3DRender::Render::ShaderUniform()); + // build name-value map + blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); + + // THEN + QVERIFY(blockBuilder.uniforms.count() == 3); + QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 3); + + QCOMPARE(blockBuilder.activeUniformNamesToValue.value(Qt3DRender::Render::StringToInt::lookupId("MyBlock.scalar")), + shaderData->property("scalar")); + QCOMPARE(blockBuilder.activeUniformNamesToValue.value(Qt3DRender::Render::StringToInt::lookupId("MyBlock.array[0]")), + shaderData->property("array")); + QCOMPARE(blockBuilder.activeUniformNamesToValue.value(Qt3DRender::Render::StringToInt::lookupId("MyBlock.texture")), + QVariant::fromValue(texture->id())); +} + +void tst_RenderViewUtils::transformedProperties() +{ + // GIVEN + QScopedPointer shaderData(new Qt3DRender::QShaderData()); + QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); + TestRenderer renderer; + + // WHEN + const Vector3D position = Vector3D(15.0f, -5.0f, 10.0f); + const QVector3D positionQt = convertToQVector3D(position); + Matrix4x4 worldMatrix; + { + QMatrix4x4 m; + m.translate(-3.0f, 2.0f, 7.5f); + worldMatrix = Matrix4x4(m); + } + Matrix4x4 viewMatrix; + { + QMatrix4x4 m; + m.translate(9.0f, 6.0f, 12.0f); + viewMatrix = Matrix4x4(m); + } + + shaderData->setProperty("position0", positionQt); + shaderData->setProperty("position1", positionQt); + shaderData->setProperty("position2", positionQt); + shaderData->setProperty("position3", positionQt); + shaderData->setProperty("position1Transformed", Qt3DRender::Render::ShaderData::ModelToEye); + shaderData->setProperty("position2Transformed", Qt3DRender::Render::ShaderData::ModelToWorld); + shaderData->setProperty("position3Transformed", Qt3DRender::Render::ShaderData::ModelToWorldDirection); + initBackendShaderData(&renderer, shaderData.data(), manager.data()); + + // THEN + Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); + QVERIFY(backendShaderData != nullptr); + QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position0")), Qt3DRender::Render::ShaderData::NoTransform); + QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position1")), Qt3DRender::Render::ShaderData::ModelToEye); + QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position2")), Qt3DRender::Render::ShaderData::ModelToWorld); + QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position3")), Qt3DRender::Render::ShaderData::ModelToWorldDirection); + + // WHEN + backendShaderData->updateWorldTransform(worldMatrix); + const Vector3D position1Value = backendShaderData->getTransformedProperty(QStringLiteral("position1"), viewMatrix).value(); + const Vector3D position2Value = backendShaderData->getTransformedProperty(QStringLiteral("position2"), viewMatrix).value(); + const Vector3D position3Value = backendShaderData->getTransformedProperty(QStringLiteral("position3"), viewMatrix).value(); + const QVariant position0Value = backendShaderData->getTransformedProperty(QStringLiteral("position0"), viewMatrix); + + // THEN + QCOMPARE(position0Value, positionQt); + QCOMPARE(position1Value, viewMatrix * worldMatrix * position); + QCOMPARE(position2Value, worldMatrix * position); + QCOMPARE(position3Value, Vector3D((worldMatrix * Vector4D(position, 0.0f)))); +} + +void tst_RenderViewUtils::shouldNotifyDynamicPropertyChanges() +{ + // GIVEN + TestArbiter arbiter; + QScopedPointer shaderData(new Qt3DRender::QShaderData()); + arbiter.setArbiterOnNode(shaderData.data()); + + // WHEN + shaderData->setProperty("scalar", 883.0f); + + // THEN + QCOMPARE(arbiter.events.size(), 0); + QCOMPARE(arbiter.dirtyNodes.size(), 1); + QCOMPARE(arbiter.dirtyNodes.front(), shaderData.data()); + + arbiter.dirtyNodes.clear(); + + // WHEN + QScopedPointer texture(new Qt3DRender::QTexture2D); + shaderData->setProperty("texture", QVariant::fromValue(texture.data())); + + // THEN + QCOMPARE(arbiter.events.size(), 0); + QCOMPARE(arbiter.dirtyNodes.size(), 1); + QCOMPARE(arbiter.dirtyNodes.front(), shaderData.data()); +} + +QTEST_MAIN(tst_RenderViewUtils) + +#include "tst_renderviewutils.moc" diff --git a/tests/auto/render/opengl/textures/textures.pro b/tests/auto/render/opengl/textures/textures.pro new file mode 100644 index 000000000..a116756af --- /dev/null +++ b/tests/auto/render/opengl/textures/textures.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +TARGET = tst_textures + +QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib + +CONFIG += testcase + +SOURCES += tst_textures.cpp + +include(../../../core/common/common.pri) +include(../../commons/commons.pri) + +# Link Against OpenGL Renderer Plugin +include(../opengl_render_plugin.pri) diff --git a/tests/auto/render/opengl/textures/tst_textures.cpp b/tests/auto/render/opengl/textures/tst_textures.cpp new file mode 100644 index 000000000..984d49a3e --- /dev/null +++ b/tests/auto/render/opengl/textures/tst_textures.cpp @@ -0,0 +1,821 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// TODO Remove in Qt6 +#include +QT_WARNING_DISABLE_DEPRECATED + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/** + * @brief Dummy QTextureImageDataGenerator + */ +class TestImageDataGenerator : public Qt3DRender::QTextureImageDataGenerator +{ + int m_id; +public: + TestImageDataGenerator(int id) : m_id(id) {} + + Qt3DRender::QTextureImageDataPtr operator ()() override { + return Qt3DRender::QTextureImageDataPtr::create(); + } + + bool operator ==(const Qt3DRender::QTextureImageDataGenerator &other) const override { + const TestImageDataGenerator *otherFunctor = Qt3DRender::functor_cast(&other); + return (otherFunctor != nullptr && otherFunctor->m_id == m_id); + } + + QT3D_FUNCTOR(TestImageDataGenerator) +}; + +/** + * @brief Dummy QTextureGenerator + */ +class TestTextureGenerator : public Qt3DRender::QTextureGenerator +{ + int m_id; +public: + TestTextureGenerator(int id) : m_id(id) {} + + Qt3DRender::QTextureDataPtr operator ()() override { + return Qt3DRender::QTextureDataPtr::create(); + } + + bool operator ==(const Qt3DRender::QTextureGenerator &other) const override { + const TestTextureGenerator *otherFunctor = Qt3DRender::functor_cast(&other); + return (otherFunctor != nullptr && otherFunctor->m_id == m_id); + } + + QT3D_FUNCTOR(TestTextureGenerator) +}; + +typedef QSharedPointer TestTextureGeneratorPtr; + +class TestTexturePrivate : public Qt3DRender::QAbstractTexturePrivate +{ +public: + int genId; +}; + +/** + * @brief Test QTexture. Assign texture data functor if genId > 0. + */ +class TestTexture : public Qt3DRender::QAbstractTexture +{ +public: + TestTexture(int genId, Qt3DCore::QNode *p = nullptr) + : QAbstractTexture(*new TestTexturePrivate(), p) + { + d_func()->genId = genId; + if (genId > 0) + d_func()->setDataFunctor(TestTextureGeneratorPtr::create(genId)); + } +private: + Q_DECLARE_PRIVATE(TestTexture) +}; + +class TestSharedGLTexturePrivate : public Qt3DRender::QAbstractTexturePrivate +{ +}; + +class TestSharedGLTexture : public Qt3DRender::QAbstractTexture +{ +public: + TestSharedGLTexture(int textureId, Qt3DCore::QNode *p = nullptr) + : QAbstractTexture(*new TestSharedGLTexturePrivate(), p) + { + d_func()->m_sharedTextureId = textureId; + } + +private: + Q_DECLARE_PRIVATE(TestSharedGLTexture) +}; + + +/** + * @brief Test QTextureImage + */ +class TestTextureImage : public Qt3DRender::QAbstractTextureImage +{ +public: + TestTextureImage(int genId, Qt3DCore::QNode *p = nullptr) + : QAbstractTextureImage(p) + , m_genId(genId) + { + } + + void updateGenerator() + { + Qt3DRender::QAbstractTextureImage::notifyDataGeneratorChanged(); + } + + Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator() const + { + return Qt3DRender::QTextureImageDataGeneratorPtr(new TestImageDataGenerator(m_genId)); + } +protected: + int m_genId; +}; + +class EmptyTextureImage : public Qt3DRender::QAbstractTextureImage +{ +public: + EmptyTextureImage(Qt3DCore::QNode *p = nullptr) + : QAbstractTextureImage(p) + { + } + + Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator() const + { + return {}; + } +}; + +class tst_RenderTextures : public Qt3DCore::QBackendNodeTester +{ + Q_OBJECT + + Qt3DRender::QAbstractTexture *createQTexture(int genId, + const QVector &imgGenIds, + bool genMipMaps) + { + TestTexture *tex = new TestTexture(genId); + + for (int imgGen : imgGenIds) + tex->addTextureImage(new TestTextureImage(imgGen)); + tex->setGenerateMipMaps(genMipMaps); + + return tex; + } + + Qt3DRender::QAbstractTexture *createQTextureWithTextureId(int textureId) + { + return new TestSharedGLTexture(textureId); + } + + Qt3DRender::Render::Texture *createBackendTexture(Qt3DRender::QAbstractTexture *frontend, + Qt3DRender::Render::TextureManager *texMgr, + Qt3DRender::Render::TextureImageManager *texImgMgr, + Qt3DRender::Render::AbstractRenderer *renderer) + { + Qt3DRender::Render::Texture *backend = texMgr->getOrCreateResource(frontend->id()); + backend->setRenderer(renderer); + simulateInitializationSync(frontend, backend); + + // create texture images + for (const auto texImgFrontend : frontend->textureImages()) { + // make sure TextureImageManager has backend node for this QTextureImage + if (!texImgMgr->contains(texImgFrontend->id())) { + Qt3DRender::Render::TextureImage *texImgBackend = texImgMgr->getOrCreateResource(texImgFrontend->id()); + texImgBackend->setRenderer(renderer); + simulateInitializationSync(texImgFrontend, texImgBackend); + } + } + + return backend; + } + +private Q_SLOTS: + + void shouldCreateSameGLTextures() + { + QSKIP("Texture Sharing is now disabled"); + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + renderer.setNodeManagers(mgrs.data()); + + // GIVEN + Qt3DRender::QAbstractTexture *tex1a = createQTexture(-1, {1,2}, true); + Qt3DRender::QAbstractTexture *tex1b = createQTexture(-1, {1,2}, true); + + // WHEN + Qt3DRender::Render::Texture *bt1a = createBackendTexture(tex1a, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + Qt3DRender::Render::Texture *bt1b = createBackendTexture(tex1b, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + renderer.updateTexture(bt1a); + renderer.updateTexture(bt1b); + + // THEN + QCOMPARE(renderer.glResourceManagers()->glTextureManager()->lookupResource(bt1a->peerId()), + renderer.glResourceManagers()->glTextureManager()->lookupResource(bt1b->peerId())); + renderer.shutdown(); + } + + void shouldCreateDifferentGLTexturess() + { + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + renderer.setNodeManagers(mgrs.data()); + + // GIVEN + QVector textures; + textures << createQTexture(-1, {1,2}, true); + textures << createQTexture(-1, {1,2}, false); + textures << createQTexture(1, {1,2}, true); + textures << createQTexture(1, {1,2}, false); + textures << createQTexture(1, {1,2,3}, true); + textures << createQTexture(1, {1,2,3}, false); + + // WHEN + QVector backend; + for (auto *t : textures) { + Qt3DRender::Render::Texture *backendTexture = createBackendTexture(t, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + backend.push_back(backendTexture); + renderer.updateTexture(backendTexture); + } + + // THEN + + // no 2 textures must be the same + for (int i = 0; i < backend.size(); i++) + for (int k = i+1; k < backend.size(); k++) + QVERIFY(renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[i]->peerId()) != + renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[k]->peerId())); + + QVector glTextures; + for (Qt3DRender::Render::Texture *t : backend) + glTextures.push_back(renderer.glResourceManagers()->glTextureManager()->lookupResource(t->peerId())); + + // some texture generators must be the same + QVERIFY(glTextures[0]->textureGenerator().data() == nullptr); + QVERIFY(glTextures[1]->textureGenerator().data() == nullptr); + QCOMPARE(*(glTextures[2]->textureGenerator()), *(glTextures[3]->textureGenerator())); + + // some images must be the same + QCOMPARE(glTextures[0]->images(), glTextures[1]->images()); + QCOMPARE(glTextures[0]->images(), glTextures[2]->images()); + QCOMPARE(glTextures[0]->images(), glTextures[3]->images()); + QCOMPARE(glTextures[4]->images(), glTextures[5]->images()); + + QCOMPARE(glTextures[0]->properties(), glTextures[2]->properties()); + QCOMPARE(glTextures[1]->properties(), glTextures[3]->properties()); + QVERIFY(glTextures[0]->properties() != glTextures[1]->properties()); + + renderer.shutdown(); + } + + void shouldCreateDifferentGLTexturesWhenUsingSharedTextureIds() + { + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + renderer.setNodeManagers(mgrs.data()); + + Qt3DRender::Render::GLResourceManagers *glMgrs = renderer.glResourceManagers(); + + // both texture having the same sharedTextureId + { + // GIVEN + Qt3DRender::QAbstractTexture *tex1a = createQTextureWithTextureId(1); + Qt3DRender::QAbstractTexture *tex1b = createQTextureWithTextureId(1); + + // WHEN + Qt3DRender::Render::Texture *bt1 = createBackendTexture(tex1a, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + Qt3DRender::Render::Texture *bt2 = createBackendTexture(tex1b, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + // THEN + QCOMPARE(bt1->sharedTextureId(), 1); + QCOMPARE(bt2->sharedTextureId(), 1); + + // WHEN + renderer.updateTexture(bt1); + renderer.updateTexture(bt2); + + // THEN + Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); + Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); + QVERIFY(glt1 != glt2); + QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); + QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); + } + + // textures having a different sharedTextureId + { + // GIVEN + Qt3DRender::QAbstractTexture *tex1a = createQTextureWithTextureId(1); + Qt3DRender::QAbstractTexture *tex1b = createQTextureWithTextureId(2); + + // WHEN + Qt3DRender::Render::Texture *bt1 = createBackendTexture(tex1a, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + Qt3DRender::Render::Texture *bt2 = createBackendTexture(tex1b, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + // THEN + QCOMPARE(bt1->sharedTextureId(), 1); + QCOMPARE(bt2->sharedTextureId(), 2); + + // WHEN + renderer.updateTexture(bt1); + renderer.updateTexture(bt2); + + // THEN + Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); + Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); + QVERIFY(glt1 != glt2); + QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); + QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); + } + + renderer.shutdown(); + } + + void generatorsShouldCreateSameData() + { + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + renderer.setNodeManagers(mgrs.data()); + + // GIVEN + QVector textures; + textures << createQTexture(1, {1}, true); + textures << createQTexture(2, {1,2}, true); + textures << createQTexture(1, {1,2}, true); + + // WHEN + QVector backend; + for (auto *t : textures) { + Qt3DRender::Render::Texture *backendTexture = createBackendTexture(t, + mgrs->textureManager(), + mgrs->textureImageManager(), + &renderer); + backend.push_back(backendTexture); + renderer.updateTexture(backendTexture); + } + + Qt3DRender::QTextureImageDataGeneratorPtr idg1a = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[0]->peerId())->images()[0].generator; + Qt3DRender::QTextureImageDataGeneratorPtr idg1b = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->images()[0].generator; + Qt3DRender::QTextureImageDataGeneratorPtr idg2 = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->images()[1].generator; + Qt3DRender::QTextureGeneratorPtr tg1a = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[0]->peerId())->textureGenerator(); + Qt3DRender::QTextureGeneratorPtr tg1b = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[2]->peerId())->textureGenerator(); + Qt3DRender::QTextureGeneratorPtr tg2 = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->textureGenerator(); + + // THEN + QVERIFY(idg1a); + QVERIFY(idg1b); + QVERIFY(idg2); + QVERIFY(tg1a); + QVERIFY(tg1b); + QVERIFY(tg2); + + QCOMPARE(*idg1a, *idg1b); + QVERIFY(!(*idg1a == *idg2)); + QCOMPARE(*tg1a, *tg1b); + QVERIFY(!(*tg1a == *tg2)); + + renderer.shutdown(); + } + + void checkTextureImageInitialState() + { + // GIVEN + Qt3DRender::Render::TextureImage img; + + // THEN + QCOMPARE(img.layer(), 0); + QCOMPARE(img.mipLevel(), 0); + QCOMPARE(img.isDirty(), false); + QCOMPARE(img.face(), Qt3DRender::QAbstractTexture::CubeMapPositiveX); + QVERIFY(img.dataGenerator().isNull()); + } + + void checkTextureImageCleanupState() + { + // GIVEN + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + TestTextureImage img(1); + img.setLayer(2); + img.setMipLevel(3); + + // WHEN + Qt3DRender::Render::TextureImage texImgBackend; + texImgBackend.setRenderer(&renderer); + simulateInitializationSync(&img, &texImgBackend); + texImgBackend.cleanup(); + + // THEN + QCOMPARE(texImgBackend.isDirty(), false); + QCOMPARE(texImgBackend.layer(), 0); + QCOMPARE(texImgBackend.mipLevel(), 0); + QCOMPARE(texImgBackend.face(), Qt3DRender::QAbstractTexture::CubeMapPositiveX); + QVERIFY(texImgBackend.dataGenerator().isNull()); + + renderer.shutdown(); + } + + void checkTextureImageInitializeFromPeer() + { + // GIVEN + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + TestTextureImage img(1); + + { + // WHEN + img.setLayer(2); + img.setMipLevel(3); + + Qt3DRender::Render::TextureImage texImgBackend; + texImgBackend.setRenderer(&renderer); + simulateInitializationSync(&img, &texImgBackend); + + // THEN + QCOMPARE(texImgBackend.isEnabled(), true); + QCOMPARE(texImgBackend.isDirty(), true); + QCOMPARE(texImgBackend.peerId(), img.id()); + QCOMPARE(texImgBackend.layer(), 2); + QCOMPARE(texImgBackend.mipLevel(), 3); + QCOMPARE(texImgBackend.face(), Qt3DRender::QAbstractTexture::CubeMapPositiveX); + QVERIFY(!texImgBackend.dataGenerator().isNull()); + } + + { + // WHEN + img.setEnabled(false); + + Qt3DRender::Render::TextureImage texImgBackend; + texImgBackend.setRenderer(&renderer); + simulateInitializationSync(&img, &texImgBackend); + + // THEN + QCOMPARE(texImgBackend.isEnabled(), false); + QCOMPARE(texImgBackend.peerId(), img.id()); + } + + renderer.shutdown(); + } + + void checkTextureImageSceneChangeEvents() + { + // GIVEN + Qt3DRender::Render::TextureImage backendImage; + TestTextureImage textureImage(1); + TestRenderer renderer; + backendImage.setRenderer(&renderer); + simulateInitializationSync(&textureImage, &backendImage); + + { + // WHEN + const bool newValue = false; + textureImage.setEnabled(newValue); + backendImage.syncFromFrontEnd(&textureImage, false); + + // THEN + QCOMPARE(backendImage.isEnabled(), newValue); + QVERIFY(backendImage.isDirty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + backendImage.unsetDirty(); + } + + { + // WHEN + const int newValue = 7; + textureImage.setLayer(newValue); + backendImage.syncFromFrontEnd(&textureImage, false); + + // THEN + QCOMPARE(backendImage.layer(), newValue); + QVERIFY(backendImage.isDirty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + backendImage.unsetDirty(); + } + + { + // WHEN + const int newValue = 3; + textureImage.setMipLevel(newValue); + backendImage.syncFromFrontEnd(&textureImage, false); + + + // THEN + QCOMPARE(backendImage.mipLevel(), newValue); + QVERIFY(backendImage.isDirty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + backendImage.unsetDirty(); + } + + { + // WHEN + const Qt3DRender::QAbstractTexture::CubeMapFace newValue = Qt3DRender::QAbstractTexture::CubeMapNegativeX; + textureImage.setFace(newValue); + backendImage.syncFromFrontEnd(&textureImage, false); + + // THEN + QCOMPARE(backendImage.face(), newValue); + QVERIFY(backendImage.isDirty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + backendImage.unsetDirty(); + } + + { + // WHEN + textureImage.updateGenerator(); + backendImage.syncFromFrontEnd(&textureImage, false); + + // THEN + QVERIFY(backendImage.isDirty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + backendImage.unsetDirty(); + + // WHEN + textureImage.updateGenerator(); + backendImage.syncFromFrontEnd(&textureImage, false); + + // THEN + QVERIFY(backendImage.isDirty()); + QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); + renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); + backendImage.unsetDirty(); + } + + renderer.shutdown(); + } + + void checkTextureImageProperlyReleaseGenerator() + { + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); + Qt3DRender::Render::TextureImageManager *texImgMgr = mgrs->textureImageManager(); + renderer.setNodeManagers(mgrs.data()); + + // GIVEN + Qt3DRender::QAbstractTexture* frontendTexture = createQTexture(1, {1}, true); + + Qt3DRender::Render::Texture *backendTexture = texMgr->getOrCreateResource(frontendTexture->id()); + backendTexture->setRenderer(&renderer); + simulateInitializationSync(frontendTexture, backendTexture); + + // THEN + QCOMPARE(backendTexture->textureImageIds().size(), 1); + QCOMPARE(frontendTexture->textureImages().size(), 1); + + // WHEN + TestTextureImage *texImgFrontend = static_cast(frontendTexture->textureImages().first()); + const Qt3DRender::QTextureImageDataGeneratorPtr frontendGenerator = texImgFrontend->dataGenerator(); + + // THEN + QVERIFY(!frontendGenerator.isNull()); + + // WHEN + Qt3DRender::Render::TextureImage *texImgBackend = texImgMgr->getOrCreateResource(texImgFrontend->id()); + texImgBackend->setRenderer(&renderer); + simulateInitializationSync(texImgFrontend, texImgBackend); + + // THEN + qDebug() << frontendGenerator << texImgBackend->dataGenerator(); + const Qt3DRender::QTextureImageDataGeneratorPtr backendGenerator = texImgFrontend->dataGenerator(); + QVERIFY(frontendGenerator != backendGenerator); + QVERIFY(*frontendGenerator == *backendGenerator); + + renderer.shutdown(); + } + + void checkTextureIsMarkedForDeletion() + { + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); + renderer.setNodeManagers(mgrs.data()); + + Qt3DRender::Render::TextureFunctor textureBackendNodeMapper(&renderer, + texMgr); + + // GIVEN + Qt3DRender::QAbstractTexture* frontendTexture = createQTexture(1, {1}, true); + + Qt3DRender::Render::Texture *backendTexture = static_cast(textureBackendNodeMapper.create(creationChange(frontendTexture))); + backendTexture->setRenderer(&renderer); + simulateInitializationSync(frontendTexture, backendTexture); + + // THEN + QVERIFY(backendTexture != nullptr); + QCOMPARE(texMgr->textureIdsToCleanup().size(), 0); + + QCOMPARE(texMgr->lookupResource(frontendTexture->id()), backendTexture); + + // WHEN + textureBackendNodeMapper.destroy(frontendTexture->id()); + + // THEN + QCOMPARE(texMgr->textureIdsToCleanup().size(), 1); + QCOMPARE(texMgr->textureIdsToCleanup().first(), frontendTexture->id()); + QVERIFY(texMgr->lookupResource(frontendTexture->id()) == nullptr); + + renderer.shutdown(); + } + + void checkTextureDestructionReconstructionWithinSameLoop() + { + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); + renderer.setNodeManagers(mgrs.data()); + + Qt3DRender::Render::TextureFunctor textureBackendNodeMapper(&renderer, + texMgr); + + // GIVEN + Qt3DRender::QAbstractTexture* frontendTexture = createQTexture(1, {1}, true); + + Qt3DRender::Render::Texture *backendTexture = static_cast(textureBackendNodeMapper.create(creationChange(frontendTexture))); + backendTexture->setRenderer(&renderer); + simulateInitializationSync(frontendTexture, backendTexture); + + // WHEN + textureBackendNodeMapper.destroy(frontendTexture->id()); + + // THEN + QCOMPARE(texMgr->textureIdsToCleanup().size(), 1); + QCOMPARE(texMgr->textureIdsToCleanup().first(), frontendTexture->id()); + QVERIFY(texMgr->lookupResource(frontendTexture->id()) == nullptr); + + // WHEN + backendTexture = static_cast(textureBackendNodeMapper.create(creationChange(frontendTexture))); + backendTexture->setRenderer(&renderer); + simulateInitializationSync(frontendTexture, backendTexture); + + // THEN + QVERIFY(backendTexture != nullptr); + QCOMPARE(texMgr->textureIdsToCleanup().size(), 0); + QCOMPARE(texMgr->lookupResource(frontendTexture->id()), backendTexture); + + renderer.shutdown(); + } + + void checkTextureImageDirtinessPropagatesToTextures() + { + // GIVEN + QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); + Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); + Qt3DRender::Render::TextureImageManager *texImgMgr = mgrs->textureImageManager(); + renderer.setNodeManagers(mgrs.data()); + + Qt3DRender::QTexture2D *texture1 = new Qt3DRender::QTexture2D(); + TestTextureImage *image1 = new TestTextureImage(1); + + Qt3DRender::QTexture2D *texture2 = new Qt3DRender::QTexture2D(); + TestTextureImage *image2 = new TestTextureImage(2); + + Qt3DRender::QTexture2D *texture3 = new Qt3DRender::QTexture2D(); + + texture1->addTextureImage(image1); + texture2->addTextureImage(image2); + texture3->addTextureImage(image1); + texture3->addTextureImage(image2); + + Qt3DRender::Render::Texture *backendTexture1 = texMgr->getOrCreateResource(texture1->id()); + Qt3DRender::Render::Texture *backendTexture2 = texMgr->getOrCreateResource(texture2->id()); + Qt3DRender::Render::Texture *backendTexture3 = texMgr->getOrCreateResource(texture3->id()); + Qt3DRender::Render::TextureImage *backendImage1 = texImgMgr->getOrCreateResource(image1->id()); + Qt3DRender::Render::TextureImage *backendImage2 = texImgMgr->getOrCreateResource(image2->id()); + + backendTexture1->setRenderer(&renderer); + backendTexture2->setRenderer(&renderer); + backendTexture3->setRenderer(&renderer); + backendImage1->setRenderer(&renderer); + backendImage2->setRenderer(&renderer); + + simulateInitializationSync(texture1, backendTexture1); + simulateInitializationSync(texture2, backendTexture2); + simulateInitializationSync(texture3, backendTexture3); + simulateInitializationSync(image1, backendImage1); + simulateInitializationSync(image2, backendImage2); + + // THEN + QCOMPARE(backendTexture1->textureImageIds().size(), 1); + QCOMPARE(backendTexture1->textureImageIds().first(), image1->id()); + QCOMPARE(backendTexture2->textureImageIds().size(), 1); + QCOMPARE(backendTexture2->textureImageIds().first(), image2->id()); + QCOMPARE(backendTexture3->textureImageIds().size(), 2); + QCOMPARE(backendTexture3->textureImageIds().first(), image1->id()); + QCOMPARE(backendTexture3->textureImageIds().last(), image2->id()); + + // WHEN + backendTexture1->unsetDirty(); + backendTexture2->unsetDirty(); + backendTexture3->unsetDirty(); + backendImage1->unsetDirty(); + backendImage2->unsetDirty(); + + // THEN + QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + + // WHEN + renderer.textureGathererJob()->run(); + + // THEN + QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + + // WHEN + // Make Image1 dirty + image1->updateGenerator(); + backendImage1->syncFromFrontEnd(image1, false); + + // THEN + QVERIFY(backendImage1->isDirty()); + QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + + // WHEN + renderer.textureGathererJob()->run(); + + // THEN + QVERIFY(backendTexture1->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); + QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture3->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); + + backendImage1->unsetDirty(); + backendTexture1->unsetDirty(); + backendTexture3->unsetDirty(); + + // WHEN + image2->updateGenerator(); + backendImage2->syncFromFrontEnd(image2, false); + + // THEN + QVERIFY(backendImage2->isDirty()); + QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + + // WHEN + renderer.textureGathererJob()->run(); + + QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); + QVERIFY(backendTexture2->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); + QVERIFY(backendTexture3->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); + + renderer.shutdown(); + } +}; + +QTEST_MAIN(tst_RenderTextures) + +#include "tst_textures.moc" diff --git a/tests/auto/render/pickboundingvolumejob/tst_pickboundingvolumejob.cpp b/tests/auto/render/pickboundingvolumejob/tst_pickboundingvolumejob.cpp index 5191b1a36..f1587c27c 100644 --- a/tests/auto/render/pickboundingvolumejob/tst_pickboundingvolumejob.cpp +++ b/tests/auto/render/pickboundingvolumejob/tst_pickboundingvolumejob.cpp @@ -45,10 +45,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include diff --git a/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp b/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp index 1b65388af..51b59bffc 100644 --- a/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp +++ b/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp @@ -38,6 +38,10 @@ #include #include #include +#include +#include +#include +#include #include #include "testaspect.h" diff --git a/tests/auto/render/qcamera/tst_qcamera.cpp b/tests/auto/render/qcamera/tst_qcamera.cpp index 0dcbce63f..fae8aa14e 100644 --- a/tests/auto/render/qcamera/tst_qcamera.cpp +++ b/tests/auto/render/qcamera/tst_qcamera.cpp @@ -49,6 +49,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE diff --git a/tests/auto/render/qgraphicsutils/qgraphicsutils.pro b/tests/auto/render/qgraphicsutils/qgraphicsutils.pro deleted file mode 100644 index 031a26246..000000000 --- a/tests/auto/render/qgraphicsutils/qgraphicsutils.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app - -TARGET = tst_qgraphicsutils - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_qgraphicsutils.cpp diff --git a/tests/auto/render/qgraphicsutils/tst_qgraphicsutils.cpp b/tests/auto/render/qgraphicsutils/tst_qgraphicsutils.cpp deleted file mode 100644 index e3676ad3b..000000000 --- a/tests/auto/render/qgraphicsutils/tst_qgraphicsutils.cpp +++ /dev/null @@ -1,355 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -class tst_QGraphicsUtils : public QObject -{ - Q_OBJECT -private slots: - void fillScalarInDataArray(); - void fillArray(); - void fillScalarWithOffsets(); - void fillMatrix4x4(); - void fillMatrix3x4(); - void fillMatrix4x3(); - void fillMatrixArray(); -}; - -void tst_QGraphicsUtils::fillScalarInDataArray() -{ - Qt3DRender::Render::ShaderUniform description; - - description.m_size = 1; - description.m_offset = 0; - description.m_arrayStride = 10; - - QVector4D testVector(8.0f, 8.0f, 3.0f, 1.0f); - const GLfloat *vectorData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(testVector, 1, 4); - - for (int i = 0; i < 4; i++) { - if (i == 0) - QVERIFY(vectorData[i] == testVector.x()); - else if (i == 1) - QVERIFY(vectorData[i] == testVector.y()); - else if (i == 2) - QVERIFY(vectorData[i] == testVector.z()); - else if (i == 3) - QVERIFY(vectorData[i] == testVector.w()); - } - - QByteArray data(description.m_size * 4 * sizeof(GLfloat), 0); - char *innerData = data.data(); - - // Checked that we are not overflowing - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 2); - for (int i = 0; i < 4; ++i) { - if (i < 2) - QVERIFY(vectorData[i] == ((GLfloat*)innerData)[i]); - else - QVERIFY(((GLfloat*)innerData)[i] == 0.0f); - } - - // Check that all values are copied - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); - for (int i = 0; i < 4; ++i) - QVERIFY(vectorData[i] == ((GLfloat*)innerData)[i]); - - // check that offsetting works - description.m_offset = 16; - data = QByteArray(description.m_size * 8 * sizeof(GLfloat), 0); - innerData = data.data(); - - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); - for (int i = 0; i < 8; ++i) { - if (i < 4) - QVERIFY(((GLfloat*)innerData)[i] == 0.0f); - else - QVERIFY(vectorData[i - 4] == ((GLfloat*)innerData)[i]); - } -} - -void tst_QGraphicsUtils::fillArray() -{ - QVector4D testVector(8.0f, 8.0f, 3.0f, 1.0f); - QVector4D testVector2(3.0f, 5.0f, 0.0f, 7.0f); - QVector4D testVector3(4.0f, 5.0f, 4.0f, 2.0f); - - QVariantList variantList = QVariantList() << testVector << testVector2 << testVector3; - const GLfloat *vectorData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant(variantList), 3, 4); - - Qt3DRender::Render::ShaderUniform description; - - description.m_size = 3; - description.m_offset = 16; - description.m_arrayStride = 16; - - QByteArray data(description.m_size * (4 + description.m_arrayStride) * sizeof(GLfloat) + description.m_offset, 0); - char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); - - int offset = description.m_offset / sizeof(GLfloat); - int stride = description.m_arrayStride / sizeof(GLfloat); - - GLfloat *innerDataFloat = (GLfloat*)innerData; - - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 4; ++j) { - int idx = i * 4 + j; - QVERIFY(innerDataFloat[offset + j] == vectorData[idx]); - } - offset += stride; - } -} - -void tst_QGraphicsUtils::fillScalarWithOffsets() -{ - // Simulates Uniform Block - - // uniform Block { - // vec3 position; // Offset 0 - 12 bytes - // vec3 direction; // Offset 16 - 12 bytes - // vec4 color; // Offset 32 - 16 bytes - // float intensity; // Offset 48 - bytes - // } // total size 64 bytes - - QVector3D position(8.0f, 8.0f, 3.0f); - QVector3D direction(3.0f, 5.0f, 2.0f); - QVector4D color(4.0f, 5.0f, 4.0f, 1.0f); - float intensity = 1.0f; - - Qt3DRender::Render::ShaderUniform posUniform; - posUniform.m_size = 1; - posUniform.m_arrayStride = 0; - posUniform.m_matrixStride = 0; - posUniform.m_offset = 0; - - Qt3DRender::Render::ShaderUniform dirUniform; - dirUniform.m_size = 1; - dirUniform.m_arrayStride = 0; - dirUniform.m_matrixStride = 0; - dirUniform.m_offset = 16; - - Qt3DRender::Render::ShaderUniform colUniform; - colUniform.m_size = 1; - colUniform.m_arrayStride = 0; - colUniform.m_matrixStride = 0; - colUniform.m_offset = 32; - - Qt3DRender::Render::ShaderUniform intUniform; - intUniform.m_size = 1; - intUniform.m_arrayStride = 0; - intUniform.m_matrixStride = 0; - intUniform.m_offset = 48; - - QVector data(16); - void *innerData = data.data(); - - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(position, 1, 3), - posUniform, 3); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(direction, 1, 3), - dirUniform, 3); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(color, 1, 4), - colUniform, 4); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(intensity, 1, 1), - intUniform, 1); - - GLfloat *floatData = (GLfloat*)innerData; - - // Check first 16 bytes - position - QVERIFY(floatData[0] == position.x()); - QVERIFY(floatData[1] == position.y()); - QVERIFY(floatData[2] == position.z()); - QVERIFY(floatData[3] == 0.0f); - // Check 16 - 32 bytes - direction - QVERIFY(floatData[4] == direction.x()); - QVERIFY(floatData[5] == direction.y()); - QVERIFY(floatData[6] == direction.z()); - QVERIFY(floatData[7] == 0.0f); - // Check 32 - 48 bytes - color - QVERIFY(floatData[8] == color.x()); - QVERIFY(floatData[9] == color.y()); - QVERIFY(floatData[10] == color.z()); - QVERIFY(floatData[11] == color.w()); - // Check 48 - 64 bytes - intensity - QVERIFY(floatData[12] == intensity); - QVERIFY(floatData[13] == 0.0f); - QVERIFY(floatData[14] == 0.0f); - QVERIFY(floatData[15] == 0.0f); -} - -void tst_QGraphicsUtils::fillMatrix4x4() -{ - // row major - QMatrix4x4 mat(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f); - - // column major - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(mat, 1, 16); - - Qt3DRender::Render::ShaderUniform description; - - description.m_size = 1; - description.m_offset = 0; - description.m_arrayStride = 0; - description.m_matrixStride = 16; - - - QByteArray data(description.m_size * 16 * sizeof(GLfloat), 0); - char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); - // Check for no offset/no stride - for (int i = 0; i < 16; ++i) - QVERIFY((((GLfloat *)innerData)[i]) == matData[i]); - - description.m_offset = 12; - data = QByteArray((description.m_size * 16 + description.m_offset) * sizeof(GLfloat), 0); - innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); - // Check with 12 offset/no stride - for (int i = 0; i < 16; ++i) - QVERIFY((((GLfloat *)innerData)[3 + i]) == matData[i]); - - description.m_matrixStride = 16; - data = QByteArray((description.m_size * 16 + 4 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); - innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); - // Check with 10 offset/ 16 stride - int offset = description.m_offset / sizeof(GLfloat); - int matrixStride = description.m_matrixStride / sizeof(GLfloat); - - for (int col = 0; col < 4; ++col) { - for (int row = 0; row < 4; ++row) - QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[col * 4 + row]); - offset += matrixStride; - } -} - -void tst_QGraphicsUtils::fillMatrix3x4() -{ - QMatrix3x4 mat; - - mat.fill(6.0f); - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); - - Qt3DRender::Render::ShaderUniform description; - - description.m_size = 1; - description.m_offset = 16; - description.m_arrayStride = 0; - description.m_matrixStride = 12; - - QByteArray data((description.m_size * 12 + 3 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); - char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 3, 4); - // Check with 16 offset/ 12 stride - int offset = description.m_offset / sizeof(GLfloat); - int matrixStride = description.m_matrixStride / sizeof(GLfloat); - - for (int col = 0; col < 3; ++col) { - for (int row = 0; row < 4; ++row) - QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[col * 4 + row]); - offset += matrixStride; - } -} - -void tst_QGraphicsUtils::fillMatrix4x3() -{ - QMatrix4x3 mat; - - mat.fill(6.0f); - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); - - Qt3DRender::Render::ShaderUniform description; - - description.m_size = 1; - description.m_offset = 16; - description.m_arrayStride = 0; - description.m_matrixStride = 16; - - QByteArray data((description.m_size * 12 + 4 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); - char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); - // Check with 16 offset/ 16 stride - int offset = description.m_offset / sizeof(GLfloat); - int matrixStride = description.m_matrixStride / sizeof(GLfloat); - - for (int col = 0; col < 4; ++col) { - for (int row = 0; row < 3; ++row) - QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[col * 3 + row]); - offset += matrixStride; - } -} - -void tst_QGraphicsUtils::fillMatrixArray() -{ - QMatrix4x3 mat1; - QMatrix4x3 mat2; - QMatrix4x3 mat3; - mat1.fill(6.0f); - mat2.fill(2.0f); - mat3.fill(7.0f); - - QVariantList matrices = QVariantList() << QVariant::fromValue(mat1) << QVariant::fromValue(mat2) << QVariant::fromValue(mat3); - - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(matrices), 3, 12); - - Qt3DRender::Render::ShaderUniform description; - - description.m_size = 3; - description.m_offset = 12; - description.m_arrayStride = 4; - description.m_matrixStride = 16; - - QByteArray data((description.m_size * (12 + 4 * description.m_matrixStride + description.m_arrayStride) + description.m_offset) * sizeof(GLfloat), 0); - char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); - // Check with 12 offset/ 4 array stride / 16 matrix stride - int offset = description.m_offset / sizeof(GLfloat); - int matrixStride = description.m_matrixStride / sizeof(GLfloat); - int arrayStride = description.m_arrayStride / sizeof(GLfloat); - - for (int i = 0; i < 3; ++i) { - for (int col = 0; col < 4; ++col) { - for (int row = 0; row < 3; ++row) { - int idx = i * 4 * 3 + col * 3 + row; - QVERIFY((((GLfloat *)innerData)[offset + row]) == matData[idx]); - } - offset += matrixStride; - } - offset += arrayStride; - } -} - -QTEST_APPLESS_MAIN(tst_QGraphicsUtils) - -#include "tst_qgraphicsutils.moc" diff --git a/tests/auto/render/raycastingjob/tst_raycastingjob.cpp b/tests/auto/render/raycastingjob/tst_raycastingjob.cpp index 1ff899936..daec0b86c 100644 --- a/tests/auto/render/raycastingjob/tst_raycastingjob.cpp +++ b/tests/auto/render/raycastingjob/tst_raycastingjob.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include diff --git a/tests/auto/render/render.pro b/tests/auto/render/render.pro index 2b73ec8b7..14fc74883 100644 --- a/tests/auto/render/render.pro +++ b/tests/auto/render/render.pro @@ -4,7 +4,6 @@ qtConfig(private_tests) { SUBDIRS += \ entity \ renderpass \ - qgraphicsutils \ shader \ shaderbuilder \ texture \ @@ -125,19 +124,8 @@ QT_FOR_CONFIG += 3drender-private qtConfig(qt3d-opengl-renderer):qtConfig(private_tests) { SUBDIRS += \ - filtercompatibletechniquejob \ - graphicshelpergl3_3 \ - graphicshelpergl3_2 \ - graphicshelpergl2 \ - glshadermanager \ - materialparametergathererjob \ - textures \ - renderer \ - renderviewutils \ - renderviews \ - renderqueue \ - renderviewbuilder \ - gltexture + opengl \ + scene2d qtConfig(qt3d-extras) { SUBDIRS += \ @@ -158,8 +146,6 @@ qtConfig(qt3d-opengl-renderer):qtConfig(private_tests) { scene2d } - !macos: SUBDIRS += graphicshelpergl4 - qtConfig(qt3d-simd-avx2): SUBDIRS += alignedresourcesmanagers-avx qtConfig(qt3d-simd-sse2):!qtConfig(qt3d-simd-avx2): SUBDIRS += alignedresourcesmanagers-sse } diff --git a/tests/auto/render/renderer/renderer.pro b/tests/auto/render/renderer/renderer.pro deleted file mode 100644 index cbafc156b..000000000 --- a/tests/auto/render/renderer/renderer.pro +++ /dev/null @@ -1,9 +0,0 @@ -TEMPLATE = app - -TARGET = tst_renderer - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_renderer.cpp diff --git a/tests/auto/render/renderer/tst_renderer.cpp b/tests/auto/render/renderer/tst_renderer.cpp deleted file mode 100644 index 0cbc1aefc..000000000 --- a/tests/auto/render/renderer/tst_renderer.cpp +++ /dev/null @@ -1,349 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class tst_Renderer : public QObject -{ - Q_OBJECT -public : - tst_Renderer() {} - ~tst_Renderer() {} - -private Q_SLOTS: - - void checkPreRenderBinJobs() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::OffscreenSurfaceHelper offscreenHelper(&renderer); - Qt3DRender::Render::RenderSettings settings; - // owned by FG manager - Qt3DRender::Render::ViewportNode *fgRoot = new Qt3DRender::Render::ViewportNode(); - const Qt3DCore::QNodeId fgRootId = Qt3DCore::QNodeId::createId(); - - nodeManagers.frameGraphManager()->appendNode(fgRootId, fgRoot); - settings.setActiveFrameGraphId(fgRootId); - - renderer.setNodeManagers(&nodeManagers); - renderer.setSettings(&settings); - renderer.setOffscreenSurfaceHelper(&offscreenHelper); - renderer.initialize(); - - // Ensure invoke calls are performed - QCoreApplication::processEvents(); - - // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) - QVector jobs = renderer.preRenderingJobs(); - - // THEN - QCOMPARE(jobs.size(), - 1 + // PickBoundingVolumeJob - 1); // RayCastingJob - - // WHEN - renderer.m_sendBufferCaptureJob->addRequest({Qt3DCore::QNodeId(), {}}); - jobs = renderer.preRenderingJobs(); - - // THEN - QCOMPARE(jobs.size(), - 1 + // PickBoundingVolumeJob - 1 + // RayCastingJob - 1); // SendBufferCaptureJob - // Note: pending render buffer captures are only cleared when the job is run - - // WHEN - renderer.m_updatedSetFences.push_back({Qt3DCore::QNodeId(), nullptr}); - jobs = renderer.preRenderingJobs(); - - // THEN - QCOMPARE(jobs.size(), - 1 + // PickBoundingVolumeJob - 1 + // RayCastingJob - 1 + // SendBufferCaptureJob - 1); // SendSetFenceHandlesJob - // Note: pending set fence handles are only cleared when the job is run - - // Properly shutdown command thread - renderer.shutdown(); - } - - void checkRenderBinJobs() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::RenderQueue *renderQueue = renderer.renderQueue(); - Qt3DRender::Render::OffscreenSurfaceHelper offscreenHelper(&renderer); - Qt3DRender::Render::RenderSettings settings; - // owned by FG manager - Qt3DRender::Render::ViewportNode *fgRoot = new Qt3DRender::Render::ViewportNode(); - const Qt3DCore::QNodeId fgRootId = Qt3DCore::QNodeId::createId(); - - nodeManagers.frameGraphManager()->appendNode(fgRootId, fgRoot); - settings.setActiveFrameGraphId(fgRootId); - - renderer.setNodeManagers(&nodeManagers); - renderer.setSettings(&settings); - renderer.setOffscreenSurfaceHelper(&offscreenHelper); - renderer.initialize(); - - // Ensure invoke calls are performed - QCoreApplication::processEvents(); - - // NOTE: FilterCompatibleTechniqueJob and ShaderGathererJob cannot run because the context - // is not initialized in this test - - const int renderViewBuilderMaterialCacheJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); - // syncMaterialGathererJob - // n * materialGathererJob - const int layerCacheJobCount = 2; - // filterEntityByLayerJob, - // syncFilterEntityByLayerJob - - const int singleRenderViewCommandRebuildJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); - - const int singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); - // RenderViewBuilder renderViewJob, - // syncRenderViewInitializationJob, - // syncFrustumCullingJob, - // filterProximityJob, - // setClearDrawBufferIndexJob, - // frustumCullingJob, - // syncRenderCommandUpdateJob, - // syncRenderViewCommandPostUpdateJob - // n * (RenderViewCommandBuildJobs) - - // WHEN - QVector jobs = renderer.renderBinJobs(); - - // THEN -> AllDirty - // (Renderer is not initialized so FilterCompatibleTechniqueJob - // and ShaderGathererJob are not added here) - QCOMPARE(jobs.size(), - 1 + // EntityEnabledDirty - 1 + // WorldTransformJob - 1 + // UpdateWorldBoundingVolume - 1 + // UpdateShaderDataTransform - 1 + // ExpandBoundingVolumeJob - 1 + // CalculateBoundingVolumeJob - 1 + // UpdateMeshTriangleListJob - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // BufferGathererJob - 1 + // TexturesGathererJob - 1 + // UpdateEntityLayersJob - 1 + // LightGathererJob - 1 + // CacheLightJob - 1 + // RenderableEntityFilterJob - 1 + // CacheRenderableEntitiesJob - 1 + // ComputableEntityFilterJob - 1 + // CacheComputableEntitiesJob - singleRenderViewJobCount + - singleRenderViewCommandRebuildJobCount + - layerCacheJobCount + - renderViewBuilderMaterialCacheJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) (Nothing in cache) - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::FrameGraphDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - singleRenderViewJobCount + - singleRenderViewCommandRebuildJobCount + - renderViewBuilderMaterialCacheJobCount + - layerCacheJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN (nothing dirty, no buffers, no layers to be rebuilt, no materials to be rebuilt) (RV leaf in cache) - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::FrameGraphDirty, nullptr); - renderer.cache()->leafNodeCache[renderer.m_frameGraphLeaves.first()] = {}; - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - singleRenderViewJobCount + - singleRenderViewCommandRebuildJobCount + - renderViewBuilderMaterialCacheJobCount + - layerCacheJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::EntityEnabledDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - 1 + // EntityEnabledDirty - singleRenderViewJobCount + - layerCacheJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::TransformDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // WorldTransformJob - 1 + // UpdateWorldBoundingVolume - 1 + // UpdateShaderDataTransform - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - 1 + // ExpandBoundingVolumeJob - singleRenderViewJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::MaterialDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - singleRenderViewJobCount + - singleRenderViewCommandRebuildJobCount + - renderViewBuilderMaterialCacheJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::GeometryDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // CalculateBoundingVolumeJob - 1 + // UpdateMeshTriangleListJob - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - 1 + // ExpandBoundingVolumeJob - 1 + // RenderableEntityFilterPtr - 1 + // SyncRenderableEntities - singleRenderViewCommandRebuildJobCount + - singleRenderViewJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::BuffersDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // updateSkinningPaletteJob - 1 + // SyncLoadingJobs - 1 + // CalculateBoundingVolumeJob - 1 + // UpdateMeshTriangleListJob - 1 + // BufferGathererJob - singleRenderViewJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // WHEN - renderer.markDirty(Qt3DRender::Render::AbstractRenderer::TexturesDirty, nullptr); - jobs = renderer.renderBinJobs(); - - // THEN (level - QCOMPARE(jobs.size(), - 1 + // updateLevelOfDetailJob - 1 + // cleanupJob - 1 + // VAOGatherer - 1 + // TexturesGathererJob - 1 + // updateSkinningPaletteJob - 1 + // SyncTexturesGathererJob - singleRenderViewJobCount); - - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - renderQueue->reset(); - - // Properly shutdown command thread - renderer.shutdown(); - } -}; - -QTEST_MAIN(tst_Renderer) - -#include "tst_renderer.moc" diff --git a/tests/auto/render/renderqueue/renderqueue.pro b/tests/auto/render/renderqueue/renderqueue.pro deleted file mode 100644 index 945fe4cf4..000000000 --- a/tests/auto/render/renderqueue/renderqueue.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = app - -TARGET = tst_renderqueue - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_renderqueue.cpp - -include(../../core/common/common.pri) diff --git a/tests/auto/render/renderqueue/tst_renderqueue.cpp b/tests/auto/render/renderqueue/tst_renderqueue.cpp deleted file mode 100644 index 071f9b3a5..000000000 --- a/tests/auto/render/renderqueue/tst_renderqueue.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -class tst_RenderQueue : public QObject -{ - Q_OBJECT -public : - tst_RenderQueue() {} - ~tst_RenderQueue() {} - -private Q_SLOTS: - void setRenderViewCount(); - void circleQueues(); - void checkOrder(); - void checkTimeToSubmit(); - void concurrentQueueAccess(); - void resetQueue(); -}; - - -void tst_RenderQueue::setRenderViewCount() -{ - // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; - - // THEN - QCOMPARE(renderQueue.wasReset(), true); - - // WHEN - renderQueue.setTargetRenderViewCount(7); - - // THEN - QCOMPARE(renderQueue.wasReset(), false); - QVERIFY(renderQueue.targetRenderViewCount() == 7); - QVERIFY(renderQueue.currentRenderViewCount()== 0); -} - -void tst_RenderQueue::circleQueues() -{ - // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; - renderQueue.setTargetRenderViewCount(7); - - // WHEN - for (int j = 0; j < 10; j++) { - - // WHEN - renderQueue.reset(); - renderQueue.setTargetRenderViewCount(7); - - // THEN - QVERIFY(!renderQueue.isFrameQueueComplete()); - QCOMPARE(renderQueue.currentRenderViewCount(), 0); - - // WHEN - QList renderViews; - for (int i = 0; i < 7; i++) { - renderViews << new Qt3DRender::Render::RenderView(); - renderQueue.queueRenderView(renderViews.at(i), i); - } - - // THEN - QVERIFY(renderQueue.isFrameQueueComplete()); - } -} - -void tst_RenderQueue::checkOrder() -{ - // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; - renderQueue.setTargetRenderViewCount(7); - QVector renderViews(7); - - // WHEN - for (int i = 0; i < 7; ++i) { - int processingOrder = (i % 2 == 0) ? (6 - i) : i; - renderViews[processingOrder] = new Qt3DRender::Render::RenderView(); - renderQueue.queueRenderView(renderViews[processingOrder], processingOrder); - } - - // THEN - QVector frame = renderQueue.nextFrameQueue(); - for (int i = 0; i < 7; ++i) { - QVERIFY(frame[i] == renderViews[i]); - } -} - -void tst_RenderQueue::checkTimeToSubmit() -{ - // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; - renderQueue.setTargetRenderViewCount(7); - QVector renderViews(7); - - // WHEN - for (int i = 0; i < 7; i++) { - int processingOrder = (i % 2 == 0) ? (6 - i) : i; - renderViews[processingOrder] = new Qt3DRender::Render::RenderView(); - renderQueue.queueRenderView(renderViews[processingOrder], processingOrder); - - // THEN - if (i < 6) - QVERIFY(!renderQueue.isFrameQueueComplete()); - else - QVERIFY(renderQueue.isFrameQueueComplete()); - } -} - -class SimpleWorker : public QThread -{ - Q_OBJECT -public: - QSemaphore m_waitSubmit; - QSemaphore m_waitQueue; - Qt3DRender::Render::RenderQueue *m_renderQueues; - -public Q_SLOTS: - - void run() final // In Thread - { - for (int i = 0; i < 5; i++) { - m_waitQueue.acquire(); - - QVERIFY(m_renderQueues->currentRenderViewCount() == 0); - QVERIFY(!m_renderQueues->isFrameQueueComplete()); - - for (int j = 0; j < 7; ++j) { - // THEN - QCOMPARE(m_renderQueues->currentRenderViewCount(), j); - // WHEN - m_renderQueues->queueRenderView(new Qt3DRender::Render::RenderView(), j); - // THEN - QVERIFY(m_renderQueues->targetRenderViewCount() == 7); - QCOMPARE(m_renderQueues->currentRenderViewCount(), j + 1); - QVERIFY(m_renderQueues->isFrameQueueComplete() == (j == 6)); - QThread::msleep(20); // Simulates business - } - - QVERIFY(m_renderQueues->isFrameQueueComplete()); - m_waitSubmit.release(); - } - } -}; - - -void tst_RenderQueue::concurrentQueueAccess() -{ - // GIVEN - Qt3DRender::Render::RenderQueue *renderQueue = new Qt3DRender::Render::RenderQueue; - - SimpleWorker *jobsThread = new SimpleWorker(); - renderQueue->setTargetRenderViewCount(7); - jobsThread->m_renderQueues = renderQueue; - - // THEN - QVERIFY(jobsThread->m_renderQueues->targetRenderViewCount() == renderQueue->targetRenderViewCount()); - QVERIFY(jobsThread->m_renderQueues->currentRenderViewCount() == renderQueue->currentRenderViewCount()); - - // Start thread - jobsThread->start(); - - jobsThread->m_waitQueue.release(); - - for (int i = 0; i < 5; ++i) { - jobsThread->m_waitSubmit.acquire(); - - // WHEN unlocked - // THEN - QVERIFY (renderQueue->isFrameQueueComplete()); - QCOMPARE(renderQueue->nextFrameQueue().size(), renderQueue->targetRenderViewCount()); - - // reset queue for next frame - renderQueue->reset(); - renderQueue->setTargetRenderViewCount(7); - jobsThread->m_waitQueue.release(); - } - jobsThread->wait(); -} - -void tst_RenderQueue::resetQueue() -{ - // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; - - for (int j = 0; j < 5; j++) { - // WHEN - renderQueue.setTargetRenderViewCount(5); - // THEN - QCOMPARE(renderQueue.wasReset(), false); - QVERIFY(renderQueue.currentRenderViewCount() == 0); - - // WHEN - QVector renderViews(5); - for (int i = 0; i < 5; ++i) { - renderQueue.queueRenderView(renderViews.at(i), i); - } - // THEN - QCOMPARE(renderQueue.currentRenderViewCount(), 5); - QVERIFY(renderQueue.isFrameQueueComplete()); - - // WHEN - renderQueue.reset(); - QCOMPARE(renderQueue.wasReset(), true); - // THEN - QVERIFY(renderQueue.currentRenderViewCount() == 0); - } -} - -QTEST_APPLESS_MAIN(tst_RenderQueue) - -#include "tst_renderqueue.moc" diff --git a/tests/auto/render/renderviewbuilder/renderviewbuilder.pro b/tests/auto/render/renderviewbuilder/renderviewbuilder.pro deleted file mode 100644 index 00fdd49cf..000000000 --- a/tests/auto/render/renderviewbuilder/renderviewbuilder.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app - -TARGET = tst_renderviewbuilder - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_renderviewbuilder.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp b/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp deleted file mode 100644 index 6024084bd..000000000 --- a/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp +++ /dev/null @@ -1,669 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Paul Lemire -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -class TestAspect : public QRenderAspect -{ -public: - TestAspect(Qt3DCore::QNode *root) - : QRenderAspect(Qt3DRender::QRenderAspect::Synchronous) - , m_jobManager(new Qt3DCore::QAspectJobManager()) - { - Qt3DCore::QAbstractAspectPrivate::get(this)->m_jobManager = m_jobManager.data(); - QRenderAspect::onRegistered(); - - QVector nodes; - Qt3DCore::QNodeVisitor v; - v.traverse(root, [&nodes](Qt3DCore::QNode *node) { - Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(node); - d->m_typeInfo = const_cast(Qt3DCore::QNodePrivate::findStaticMetaObject(node->metaObject())); - d->m_hasBackendNode = true; - nodes << node; - }); - - for (const auto node: nodes) - d_func()->createBackendNode({ - node->id(), - Qt3DCore::QNodePrivate::get(node)->m_typeInfo, - Qt3DCore::NodeTreeChange::Added, - node - }); - } - - ~TestAspect() - { - QRenderAspect::onUnregistered(); - } - - Qt3DRender::Render::NodeManagers *nodeManagers() const - { - return d_func()->m_renderer->nodeManagers(); - } - - Render::Renderer *renderer() const - { - return static_cast(d_func()->m_renderer); - } - - Render::MaterialParameterGathererJobPtr materialGathererJob() const - { - Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); - job->setNodeManagers(nodeManagers()); - return job; - } - - void onRegistered() { QRenderAspect::onRegistered(); } - void onUnregistered() { QRenderAspect::onUnregistered(); } - -private: - QScopedPointer m_jobManager; -}; - -} // namespace Qt3DRender - -QT_END_NAMESPACE - -namespace { - -Qt3DCore::QEntity *buildSimpleScene(Qt3DRender::QFrameGraphNode *fg) -{ - Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); - - Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); - renderSettings->setActiveFrameGraph(fg); - root->addComponent(renderSettings); - - // Scene - { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - Qt3DRender::QMaterial *material = new Qt3DRender::QMaterial(); - Qt3DRender::QGeometryRenderer *geometryRenderer = new Qt3DRender::QGeometryRenderer(); - e->addComponent(material); - e->addComponent(geometryRenderer); - e->setParent(root); - } - { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - Qt3DRender::QMaterial *material = new Qt3DRender::QMaterial(); - Qt3DRender::QComputeCommand *computeCommand = new Qt3DRender::QComputeCommand(); - e->addComponent(material); - e->addComponent(computeCommand); - e->setParent(root); - } - - { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - Qt3DRender::QPointLight *light = new Qt3DRender::QPointLight(); - e->addComponent(light); - e->setParent(root); - } - - { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - Qt3DRender::QSpotLight *light = new Qt3DRender::QSpotLight(); - e->addComponent(light); - e->setParent(root); - } - - { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - Qt3DRender::QEnvironmentLight *light = new Qt3DRender::QEnvironmentLight(); - e->addComponent(light); - e->setParent(root); - } - - return root; -} - -Qt3DCore::QEntity *buildEntityFilterTestScene(Qt3DRender::QFrameGraphNode *fg, Qt3DRender::QLayer *layer) -{ - Qt3DCore::QEntity *root = new Qt3DCore::QEntity(); - - Qt3DRender::QRenderSettings* renderSettings = new Qt3DRender::QRenderSettings(); - renderSettings->setActiveFrameGraph(fg); - root->addComponent(renderSettings); - - // Scene - for (int i = 0; i < 200; ++i) { - Qt3DCore::QEntity *e = new Qt3DCore::QEntity(); - Qt3DRender::QMaterial *material = new Qt3DRender::QMaterial(); - Qt3DRender::QGeometryRenderer *geometryRenderer = new Qt3DRender::QGeometryRenderer(); - e->addComponent(material); - e->addComponent(geometryRenderer); - if (i % 2 == 0) - e->addComponent(layer); - e->setParent(root); - } - - return root; -} - -} // anonymous - - -class tst_RenderViewBuilder : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - - void checkInitialState() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); - QVERIFY(leafNode != nullptr); - - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - - // THEN - QCOMPARE(renderViewBuilder.renderViewIndex(), 0); - QCOMPARE(renderViewBuilder.renderer(), testAspect.renderer()); - QCOMPARE(renderViewBuilder.layerCacheNeedsToBeRebuilt(), false); - QCOMPARE(renderViewBuilder.materialGathererCacheNeedsToBeRebuilt(), false); - QVERIFY(!renderViewBuilder.renderViewJob().isNull()); - QVERIFY(!renderViewBuilder.frustumCullingJob().isNull()); - QVERIFY(!renderViewBuilder.syncPreFrustumCullingJob().isNull()); - QVERIFY(!renderViewBuilder.setClearDrawBufferIndexJob().isNull()); - - QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); - QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob().isNull()); - QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob().isNull()); - QVERIFY(renderViewBuilder.syncRenderViewPostInitializationJob().isNull()); - - QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), 0); - QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); - - // WHEN - renderViewBuilder.prepareJobs(); - - // THEN - QVERIFY(!renderViewBuilder.syncRenderViewPreCommandUpdateJob().isNull()); - QVERIFY(!renderViewBuilder.syncRenderViewPostCommandUpdateJob().isNull()); - QVERIFY(!renderViewBuilder.syncRenderViewPostInitializationJob().isNull()); - QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); - QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - - QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); - QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); - QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); - } - - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); - renderViewBuilder.prepareJobs(); - - // THEN - QCOMPARE(renderViewBuilder.layerCacheNeedsToBeRebuilt(), true); - QVERIFY(!renderViewBuilder.filterEntityByLayerJob().isNull()); - QVERIFY(!renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - - // mark jobs dirty and recheck - QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); - } - - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.setMaterialGathererCacheNeedsToBeRebuilt(true); - renderViewBuilder.prepareJobs(); - - // THEN - QCOMPARE(renderViewBuilder.materialGathererCacheNeedsToBeRebuilt(), true); - QCOMPARE(renderViewBuilder.materialGathererJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); - QVERIFY(!renderViewBuilder.syncMaterialGathererJob().isNull()); - - // mark jobs dirty and recheck - QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 9 + 2 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); - } - } - - void checkCheckJobDependencies() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); - QVERIFY(leafNode != nullptr); - - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - - // THEN - // Step 1 - QCOMPARE(renderViewBuilder.renderViewJob()->dependencies().size(), 1); // Depends upon skinning palette update - - - // Step 2 - QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().size(), 1); - QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.renderViewJob().data()); - - // Step 3 - QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); - QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - - QCOMPARE(renderViewBuilder.filterProximityJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); - - QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().size(), 1); - QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderViewPostInitializationJob().data()); - - QCOMPARE(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().size(), 3); - QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); - QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); - - // Step 4 - QCOMPARE(renderViewBuilder.frustumCullingJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncPreFrustumCullingJob())); - QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); - - - QCOMPARE(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().size(), renderViewBuilder.materialGathererJobs().size() + 7); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->cacheLightJob())); - - // Step 5 - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { - QCOMPARE(renderViewBuilderJob->dependencies().size(), 1); - QCOMPARE(renderViewBuilderJob->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderViewPreCommandUpdateJob().data()); - } - - // Step 6 - QCOMPARE(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().size(), renderViewBuilder.renderViewCommandUpdaterJobs().size()); - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { - QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().contains(renderViewBuilderJob)); - } - } - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); - renderViewBuilder.setMaterialGathererCacheNeedsToBeRebuilt(true); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - - // THEN - // Step 1 - QCOMPARE(renderViewBuilder.renderViewJob()->dependencies().size(), 1); // Depends upon skinning palette update - - // Step 2 - QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().size(), 1); - QCOMPARE(renderViewBuilder.syncRenderViewPostInitializationJob()->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.renderViewJob().data()); - - // Step 3 - QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->dependencies().size(), 3); - QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(testAspect.renderer()->updateEntityLayersJob())); - QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.filterEntityByLayerJob()->dependencies().contains(testAspect.renderer()->updateTreeEnabledJob())); - - QCOMPARE(renderViewBuilder.syncFilterEntityByLayerJob()->dependencies().size(), 1); - QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob()->dependencies().contains(renderViewBuilder.filterEntityByLayerJob())); - - QCOMPARE(renderViewBuilder.filterProximityJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.filterProximityJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); - - QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().size(), 1); - QCOMPARE(renderViewBuilder.setClearDrawBufferIndexJob()->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderViewPostInitializationJob().data()); - - QCOMPARE(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().size(), 3); - QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateWorldTransformJob())); - QVERIFY(renderViewBuilder.syncPreFrustumCullingJob()->dependencies().contains(testAspect.renderer()->updateShaderDataTransformJob())); - - for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { - QCOMPARE(materialGatherer->dependencies().size(), 3); - QVERIFY(materialGatherer->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(materialGatherer->dependencies().contains(testAspect.renderer()->introspectShadersJob())); - QVERIFY(materialGatherer->dependencies().contains(testAspect.renderer()->filterCompatibleTechniqueJob())); - } - - // Step 4 - QCOMPARE(renderViewBuilder.frustumCullingJob()->dependencies().size(), 2); - QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(renderViewBuilder.syncPreFrustumCullingJob())); - QVERIFY(renderViewBuilder.frustumCullingJob()->dependencies().contains(testAspect.renderer()->expandBoundingVolumeJob())); - - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncRenderViewPostInitializationJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.syncFilterEntityByLayerJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.frustumCullingJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(renderViewBuilder.filterProximityJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->introspectShadersJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->bufferGathererJob())); - QVERIFY(renderViewBuilder.syncRenderViewPreCommandUpdateJob()->dependencies().contains(testAspect.renderer()->textureGathererJob())); - - // Step 5 - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { - QCOMPARE(renderViewBuilderJob->dependencies().size(), 1); - QCOMPARE(renderViewBuilderJob->dependencies().constFirst().toStrongRef().data(), - renderViewBuilder.syncRenderViewPreCommandUpdateJob().data()); - } - - // Step 6 - QCOMPARE(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().size(), renderViewBuilder.renderViewCommandUpdaterJobs().size()); - for (const auto &renderViewBuilderJob : renderViewBuilder.renderViewCommandUpdaterJobs()) { - QVERIFY(renderViewBuilder.syncRenderViewPostCommandUpdateJob()->dependencies().contains(renderViewBuilderJob)); - } - } - } - - void checkRenderViewJobExecution() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); - QVERIFY(leafNode != nullptr); - - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - renderViewBuilder.renderViewJob()->run(); - - // THEN - QVERIFY(renderViewBuilder.renderViewJob()->renderView() != nullptr); - } - - void checkLightGatherExecution() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); - QVERIFY(leafNode != nullptr); - - // WHEN - renderer->lightGathererJob()->run(); - - // THEN - QCOMPARE(renderer->lightGathererJob()->lights().size(), 2); - QVERIFY(renderer->lightGathererJob()->takeEnvironmentLight() != nullptr); - } - - void checkRenderableEntitiesFilteringExecution() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); - QVERIFY(leafNode != nullptr); - - // WHEN - renderer->renderableEntityFilterJob()->run(); - - // THEN - QCOMPARE(renderer->renderableEntityFilterJob()->filteredEntities().size(), 1); - } - - void checkComputableEntitiesFilteringExecution() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); - QVERIFY(leafNode != nullptr); - - // WHEN - renderer->computableEntityFilterJob()->run(); - - // THEN - QCOMPARE(renderer->computableEntityFilterJob()->filteredEntities().size(), 1); - } - - void checkSyncRenderViewInitializationExecution() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::QLayerFilter *layerFilter = new Qt3DRender::QLayerFilter(clearBuffer); - Qt3DRender::QFrustumCulling *frustumCulling = new Qt3DRender::QFrustumCulling(layerFilter); - Qt3DRender::QTechniqueFilter *techniqueFilter = new Qt3DRender::QTechniqueFilter(frustumCulling); - Qt3DRender::QRenderPassFilter *renderPassFilter = new Qt3DRender::QRenderPassFilter(techniqueFilter); - Qt3DRender::QLayer *layer = new Qt3DRender::QLayer(); - - layerFilter->addLayer(layer); - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(renderPassFilter->id()); - QVERIFY(leafNode != nullptr); - - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - - // THEN - QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), false); - for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { - QVERIFY(materialGatherer->techniqueFilter() == nullptr); - QVERIFY(materialGatherer->renderPassFilter() == nullptr); - } - - // WHEN - renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncRenderViewPostInitializationJob()->run(); - - // THEN - QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true); - for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { - QVERIFY(materialGatherer->techniqueFilter() != nullptr); - QVERIFY(materialGatherer->renderPassFilter() != nullptr); - } - } - { - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - - // THEN - QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), false); - QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->hasLayerFilter(), false); - QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->layerFilters().size(), 0); - for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { - QVERIFY(materialGatherer->techniqueFilter() == nullptr); - QVERIFY(materialGatherer->renderPassFilter() == nullptr); - } - - // WHEN - renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncRenderViewPostInitializationJob()->run(); - - // THEN - QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true); - QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->hasLayerFilter(), true); - QCOMPARE(renderViewBuilder.filterEntityByLayerJob()->layerFilters().size(), 1); - for (const auto &materialGatherer : renderViewBuilder.materialGathererJobs()) { - QVERIFY(materialGatherer->techniqueFilter() != nullptr); - QVERIFY(materialGatherer->renderPassFilter() != nullptr); - } - } - } - - void checkSyncFrustumCullingExecution() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::QFrustumCulling *frustumCulling = new Qt3DRender::QFrustumCulling(clearBuffer); - Qt3DRender::QCameraSelector *cameraSelector = new Qt3DRender::QCameraSelector(frustumCulling); - Qt3DRender::QCamera *camera = new Qt3DRender::QCamera(); - cameraSelector->setCamera(camera); - - Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(cameraSelector->id()); - QVERIFY(leafNode != nullptr); - - // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - - // THEN - QCOMPARE(renderViewBuilder.frustumCullingJob()->viewProjection(), Matrix4x4()); - - // WHEN - renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncPreFrustumCullingJob()->run(); - - // THEN - QCOMPARE(convertToQMatrix4x4(renderViewBuilder.frustumCullingJob()->viewProjection()), camera->projectionMatrix() * camera->viewMatrix()); - } - - void checkRemoveEntitiesNotInSubset() - { - // GIVEN - Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); - Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); - Qt3DRender::QLayerFilter *layerFilter = new Qt3DRender::QLayerFilter(clearBuffer); - Qt3DRender::QLayer *layer = new Qt3DRender::QLayer(); - layerFilter->addLayer(layer); - Qt3DRender::TestAspect testAspect(buildEntityFilterTestScene(viewport, layer)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); - - // THEN - Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(layerFilter->id()); - QVERIFY(leafNode != nullptr); - - // WHEN - renderer->markDirty(Qt3DRender::Render::AbstractRenderer::AllDirty, nullptr); - - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); - renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); - renderViewBuilder.prepareJobs(); - renderViewBuilder.buildJobHierachy(); - - renderer->renderableEntityFilterJob()->run(); - renderer->cacheRenderableEntitiesJob()->run(); - - renderViewBuilder.renderViewJob()->run(); - renderViewBuilder.syncRenderViewPostInitializationJob()->run(); - renderViewBuilder.filterEntityByLayerJob()->run(); - - QVector renderableEntity = renderer->renderableEntityFilterJob()->filteredEntities(); - QVector filteredEntity = renderViewBuilder.filterEntityByLayerJob()->filteredEntities(); - - // THEN - QCOMPARE(renderableEntity.size(), 200); - QCOMPARE(filteredEntity.size(), 100); - - std::sort(renderableEntity.begin(), renderableEntity.end()); - - // WHEN - renderableEntity = Qt3DRender::Render::RenderViewBuilder::entitiesInSubset(renderableEntity, filteredEntity); - - // THEN - QCOMPARE(renderableEntity.size(), 100); - for (const auto entity : renderableEntity) { - QVERIFY(filteredEntity.contains(entity)); - } - } - -}; - -QTEST_MAIN(tst_RenderViewBuilder) - -#include "tst_renderviewbuilder.moc" diff --git a/tests/auto/render/renderviews/renderviews.pro b/tests/auto/render/renderviews/renderviews.pro deleted file mode 100644 index 046c00696..000000000 --- a/tests/auto/render/renderviews/renderviews.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app - -TARGET = tst_renderviews - -QT += 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_renderviews.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/renderviews/tst_renderviews.cpp b/tests/auto/render/renderviews/tst_renderviews.cpp deleted file mode 100644 index b434fe83a..000000000 --- a/tests/auto/render/renderviews/tst_renderviews.cpp +++ /dev/null @@ -1,552 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace Qt3DRender { - -namespace Render { - -namespace { - -void compareShaderParameterPacks(const ShaderParameterPack &t1, - const ShaderParameterPack &t2) -{ - const PackUniformHash hash1 = t1.uniforms(); - const PackUniformHash hash2 = t2.uniforms(); - - QCOMPARE(hash1.keys.size(), hash2.keys.size()); - - for (int i = 0, m = hash1.keys.size(); i < m; ++i) { - const int key = hash1.keys.at(i); - QCOMPARE(hash1.value(key), hash2.value(key)); - } -} - -} // anonymous - -class tst_RenderViews : public Qt3DCore::QBackendNodeTester -{ - Q_OBJECT - -private Q_SLOTS: - - void checkRenderViewSizeFitsWithAllocator() - { - QSKIP("Allocated Disabled"); - QVERIFY(sizeof(RenderView) <= 192); - QVERIFY(sizeof(RenderView::InnerData) <= 192); - } - - void checkRenderViewInitialState() - { - // GIVEN - RenderView renderView; - - // THEN - QCOMPARE(renderView.memoryBarrier(), QMemoryBarrier::None); - } - - void checkMemoryBarrierInitialization() - { - // GIVEN - RenderView renderView; - - // THEN - QCOMPARE(renderView.memoryBarrier(), QMemoryBarrier::None); - - // WHEN - const QMemoryBarrier::Operations barriers(QMemoryBarrier::BufferUpdate|QMemoryBarrier::ShaderImageAccess); - renderView.setMemoryBarrier(barriers); - - // THEN - QCOMPARE(renderView.memoryBarrier(), barriers); - } - - void checkSetRenderViewConfig() - { - TestRenderer renderer; - { - // GIVEN - const QMemoryBarrier::Operations barriers(QMemoryBarrier::AtomicCounter|QMemoryBarrier::ShaderStorage); - Qt3DRender::QMemoryBarrier frontendBarrier; - FrameGraphManager frameGraphManager; - MemoryBarrier backendBarrier; - RenderView renderView; - // setRenderViewConfigFromFrameGraphLeafNode assumes node has a manager - backendBarrier.setFrameGraphManager(&frameGraphManager); - backendBarrier.setRenderer(&renderer); - - // WHEN - frontendBarrier.setWaitOperations(barriers); - simulateInitializationSync(&frontendBarrier, &backendBarrier); - - // THEN - QCOMPARE(renderView.memoryBarrier(), QMemoryBarrier::None); - QCOMPARE(backendBarrier.waitOperations(), barriers); - - // WHEN - Qt3DRender::Render::setRenderViewConfigFromFrameGraphLeafNode(&renderView, &backendBarrier); - - // THEN - QCOMPARE(backendBarrier.waitOperations(), renderView.memoryBarrier()); - } - // TO DO: Complete tests for other framegraph node types - } - - void checkRenderCommandBackToFrontSorting() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - RenderView renderView; - QVector rawCommands; - QVector sortTypes; - - renderer.setNodeManagers(&nodeManagers); - renderView.setRenderer(&renderer); - - sortTypes.push_back(QSortPolicy::BackToFront); - - for (int i = 0; i < 200; ++i) { - RenderCommand c; - c.m_depth = float(i); - rawCommands.push_back(c); - } - - // WHEN - renderView.addSortType(sortTypes); - renderView.setCommands(rawCommands); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands.size(), sortedCommands.size()); - for (int j = 1; j < sortedCommands.size(); ++j) - QVERIFY(sortedCommands.at(j - 1).m_depth > sortedCommands.at(j).m_depth); - - // RenderCommands are deleted by RenderView dtor - renderer.shutdown(); - } - - void checkRenderCommandMaterialSorting() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - RenderView renderView; - QVector rawCommands; - QVector sortTypes; - - renderer.setNodeManagers(&nodeManagers); - renderView.setRenderer(&renderer); - - sortTypes.push_back(QSortPolicy::Material); - - GLShader *dnas[5] = { - reinterpret_cast(0x250), - reinterpret_cast(0x500), - reinterpret_cast(0x1000), - reinterpret_cast(0x1500), - reinterpret_cast(0x2000) - }; - - for (int i = 0; i < 20; ++i) { - RenderCommand c; - c.m_glShader = dnas[i % 5]; - rawCommands.push_back(c); - } - - // WHEN - renderView.addSortType(sortTypes); - renderView.setCommands(rawCommands); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands.size(), sortedCommands.size()); - GLShader *targetShader; - - for (int j = 0; j < sortedCommands.size(); ++j) { - - if (j % 4 == 0) { - targetShader = sortedCommands.at(j).m_glShader; - if (j > 0) - QVERIFY(targetShader != sortedCommands.at(j - 1).m_glShader); - } - QCOMPARE(targetShader, sortedCommands.at(j).m_glShader); - } - - // RenderCommands are deleted by RenderView dtor - renderer.shutdown(); - } - - void checkRenderViewUniformMinification_data() - { - QTest::addColumn>("shaders"); - QTest::addColumn>("rawParameters"); - QTest::addColumn>("expectedMinimizedParameters"); - - Qt3DCore::QNodeId fakeTextureNodeId = Qt3DCore::QNodeId::createId(); - - ShaderParameterPack pack1; - pack1.setUniform(1, UniformValue(883)); - pack1.setUniform(2, UniformValue(1584.0f)); - pack1.setTexture(3, 0, fakeTextureNodeId); - - QShaderProgram *shader1 = new QShaderProgram(); - QShaderProgram *shader2 = new QShaderProgram(); - - shader1->setShaderCode(QShaderProgram::Vertex, QByteArrayLiteral("1")); - shader2->setShaderCode(QShaderProgram::Vertex, QByteArrayLiteral("2")); - - ShaderParameterPack minifiedPack1; - - QTest::newRow("NoMinification") - << (QVector() << shader1 << shader2) - << (QVector() << pack1 << pack1) - << (QVector() << pack1 << pack1); - - QTest::newRow("SingleShaderMinified") - << (QVector() << shader1 << shader1 << shader1) - << (QVector() << pack1 << pack1 << pack1) - << (QVector() << pack1 << minifiedPack1 << minifiedPack1); - - QTest::newRow("MultipleShadersMinified") - << (QVector() << shader1 << shader1 << shader1 << shader2 << shader2 << shader2) - << (QVector() << pack1 << pack1 << pack1 << pack1 << pack1 << pack1) - << (QVector() << pack1 << minifiedPack1 << minifiedPack1 << pack1 << minifiedPack1 << minifiedPack1); - } - - void checkRenderViewUniformMinification() - { - QFETCH(QVector, shaders); - QFETCH(QVector, rawParameters); - QFETCH(QVector, expectedMinimizedParameters); - - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - renderer.setNodeManagers(&nodeManagers); - - GLShaderManager *shaderManager = renderer.glResourceManagers()->glShaderManager(); - for (int i = 0, m = shaders.size(); i < m; ++i) { - Shader* backend = new Shader(); - backend->setRenderer(&renderer); - simulateInitializationSync(shaders.at(i), backend); - shaderManager->createOrAdoptExisting(backend); - } - - RenderView renderView; - QVector rawCommands; - renderView.setRenderer(&renderer); - - for (int i = 0, m = shaders.size(); i < m; ++i) { - RenderCommand c; - c.m_shaderId = shaders.at(i)->id(); - c.m_glShader = shaderManager->lookupResource(c.m_shaderId); - c.m_parameterPack = rawParameters.at(i); - rawCommands.push_back(c); - } - - // WHEN - renderView.setCommands(rawCommands); - renderView.addSortType((QVector() << QSortPolicy::Uniform)); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands, sortedCommands); - - for (int i = 0, m = shaders.size(); i < m; ++i) { - const RenderCommand c = sortedCommands.at(i); - QCOMPARE(c.m_shaderId, shaders.at(i)->id()); - compareShaderParameterPacks(c.m_parameterPack, expectedMinimizedParameters.at(i)); - } - - renderer.shutdown(); - } - - - void checkRenderCommandFrontToBackSorting() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - RenderView renderView; - QVector rawCommands; - QVector sortTypes; - - renderer.setNodeManagers(&nodeManagers); - renderView.setRenderer(&renderer); - - sortTypes.push_back(QSortPolicy::FrontToBack); - - for (int i = 0; i < 200; ++i) { - RenderCommand c; - c.m_depth = float(i); - rawCommands.push_back(c); - } - - // WHEN - renderView.addSortType(sortTypes); - renderView.setCommands(rawCommands); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands.size(), sortedCommands.size()); - for (int j = 1; j < sortedCommands.size(); ++j) - QVERIFY(sortedCommands.at(j - 1).m_depth < sortedCommands.at(j).m_depth); - - // RenderCommands are deleted by RenderView dtor - renderer.shutdown(); - } - - void checkRenderCommandStateCostSorting() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - RenderView renderView; - QVector rawCommands; - QVector sortTypes; - - renderer.setNodeManagers(&nodeManagers); - renderView.setRenderer(&renderer); - - sortTypes.push_back(QSortPolicy::StateChangeCost); - - for (int i = 0; i < 200; ++i) { - RenderCommand c; - c.m_changeCost = i; - rawCommands.push_back(c); - } - - // WHEN - renderView.addSortType(sortTypes); - renderView.setCommands(rawCommands); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands.size(), sortedCommands.size()); - for (int j = 1; j < sortedCommands.size(); ++j) - QVERIFY(sortedCommands.at(j - 1).m_changeCost > sortedCommands.at(j).m_changeCost); - - // RenderCommands are deleted by RenderView dtor - renderer.shutdown(); - } - - void checkRenderCommandCombinedStateMaterialDepthSorting() - { - // GIVEN - Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - RenderView renderView; - QVector rawCommands; - QVector sortTypes; - - renderer.setNodeManagers(&nodeManagers); - renderView.setRenderer(&renderer); - - sortTypes.push_back(QSortPolicy::StateChangeCost); - sortTypes.push_back(QSortPolicy::Material); - sortTypes.push_back(QSortPolicy::BackToFront); - - GLShader *dna[5] = { - reinterpret_cast(0x250), - reinterpret_cast(0x500), - reinterpret_cast(0x1000), - reinterpret_cast(0x1500), - reinterpret_cast(0x2000) - }; - - float depth[3] = { - 10.0f, - 25.0f, - 30.0f - }; - - int stateChangeCost[2] = { - 100, - 200 - }; - - auto buildRC = [] (GLShader *dna, float depth, int changeCost) { - RenderCommand c; - c.m_glShader = dna; - c.m_depth = depth; - c.m_changeCost = changeCost; - return c; - }; - - RenderCommand c5 = buildRC(dna[3], depth[1], stateChangeCost[1]); - RenderCommand c3 = buildRC(dna[3], depth[0], stateChangeCost[1]); - RenderCommand c4 = buildRC(dna[2], depth[1], stateChangeCost[1]); - RenderCommand c8 = buildRC(dna[1], depth[1], stateChangeCost[1]); - RenderCommand c0 = buildRC(dna[0], depth[2], stateChangeCost[1]); - - RenderCommand c2 = buildRC(dna[2], depth[2], stateChangeCost[0]); - RenderCommand c9 = buildRC(dna[2], depth[0], stateChangeCost[0]); - RenderCommand c1 = buildRC(dna[1], depth[0], stateChangeCost[0]); - RenderCommand c7 = buildRC(dna[0], depth[2], stateChangeCost[0]); - RenderCommand c6 = buildRC(dna[0], depth[1], stateChangeCost[0]); - - rawCommands << c0 << c1 << c2 << c3 << c4 << c5 << c6 << c7 << c8 << c9; - - // WHEN - renderView.addSortType(sortTypes); - renderView.setCommands(rawCommands); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands.size(), sortedCommands.size()); - - // Ordered by higher state, higher shaderDNA and higher depth - QCOMPARE(c0, sortedCommands.at(4)); - QCOMPARE(c3, sortedCommands.at(1)); - QCOMPARE(c4, sortedCommands.at(2)); - QCOMPARE(c5, sortedCommands.at(0)); - QCOMPARE(c8, sortedCommands.at(3)); - - QCOMPARE(c1, sortedCommands.at(7)); - QCOMPARE(c2, sortedCommands.at(5)); - QCOMPARE(c6, sortedCommands.at(9)); - QCOMPARE(c7, sortedCommands.at(8)); - QCOMPARE(c9, sortedCommands.at(6)); - - // RenderCommands are deleted by RenderView dtor - renderer.shutdown(); - } - - void checkRenderCommandTextureSorting() - { - // GIVEN - RenderView renderView; - QVector sortTypes; - - sortTypes.push_back(QSortPolicy::Texture); - - - Qt3DCore::QNodeId tex1 = Qt3DCore::QNodeId::createId(); - Qt3DCore::QNodeId tex2 = Qt3DCore::QNodeId::createId(); - Qt3DCore::QNodeId tex3 = Qt3DCore::QNodeId::createId(); - Qt3DCore::QNodeId tex4 = Qt3DCore::QNodeId::createId(); - - RenderCommand a; - { - ShaderParameterPack pack; - pack.setTexture(0, 0, tex1); - pack.setTexture(1, 0, tex3); - pack.setTexture(2, 0, tex4); - pack.setTexture(3, 0, tex2); - a.m_parameterPack = pack; - } - RenderCommand b; - RenderCommand c; - { - ShaderParameterPack pack; - pack.setTexture(0, 0, tex1); - pack.setTexture(3, 0, tex2); - c.m_parameterPack = pack; - } - RenderCommand d; - { - ShaderParameterPack pack; - pack.setTexture(1, 0, tex3); - pack.setTexture(2, 0, tex4); - d.m_parameterPack = pack; - } - RenderCommand e; - { - ShaderParameterPack pack; - pack.setTexture(3, 0, tex2); - e.m_parameterPack = pack; - } - RenderCommand f; - { - ShaderParameterPack pack; - pack.setTexture(3, 0, tex2); - f.m_parameterPack = pack; - } - RenderCommand g; - { - ShaderParameterPack pack; - pack.setTexture(0, 0, tex1); - pack.setTexture(1, 0, tex3); - pack.setTexture(2, 0, tex4); - pack.setTexture(3, 0, tex2); - g.m_parameterPack = pack; - } - - // WHEN - QVector rawCommands = {a, b, c, d, e, f, g}; - renderView.addSortType(sortTypes); - renderView.setCommands(rawCommands); - renderView.sort(); - - // THEN - const QVector sortedCommands = renderView.commands(); - QCOMPARE(rawCommands.size(), sortedCommands.size()); - QCOMPARE(sortedCommands.at(0), a); - QCOMPARE(sortedCommands.at(1), g); - QCOMPARE(sortedCommands.at(2), d); - QCOMPARE(sortedCommands.at(3), c); - QCOMPARE(sortedCommands.at(4), e); - QCOMPARE(sortedCommands.at(5), f); - QCOMPARE(sortedCommands.at(6), b); - // RenderCommands are deleted by RenderView dtor - } -private: -}; - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -//APPLESS_ -QTEST_MAIN(Qt3DRender::Render::tst_RenderViews) - -#include "tst_renderviews.moc" diff --git a/tests/auto/render/renderviewutils/renderviewutils.pro b/tests/auto/render/renderviewutils/renderviewutils.pro deleted file mode 100644 index 90d8a2562..000000000 --- a/tests/auto/render/renderviewutils/renderviewutils.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app - -TARGET = tst_renderviewutils - -QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_renderviewutils.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/renderviewutils/tst_renderviewutils.cpp b/tests/auto/render/renderviewutils/tst_renderviewutils.cpp deleted file mode 100644 index 6d349f994..000000000 --- a/tests/auto/render/renderviewutils/tst_renderviewutils.cpp +++ /dev/null @@ -1,800 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "testrenderer.h" -#include "testpostmanarbiter.h" - -class tst_RenderViewUtils : public Qt3DCore::QBackendNodeTester -{ - Q_OBJECT -private Q_SLOTS: - void topLevelScalarValueNoUniforms(); - void topLevelScalarValue(); - void topLevelTextureValueNoUniforms(); - void topLevelTextureValue(); - void topLevelArrayValue(); - void nestedShaderDataValue(); - void topLevelStructValue_data(); - void topLevelStructValue(); - void topLevelDynamicProperties(); - void transformedProperties(); - void shouldNotifyDynamicPropertyChanges(); - -private: - void initBackendShaderData(Qt3DRender::Render::AbstractRenderer *renderer, - Qt3DRender::QShaderData *frontend, - Qt3DRender::Render::ShaderDataManager *manager) - { - // Create children first - for (QObject *c : frontend->children()) { - Qt3DRender::QShaderData *cShaderData = qobject_cast(c); - if (cShaderData) - initBackendShaderData(renderer, cShaderData, manager); - } - - // Create backend element for frontend one - Qt3DRender::Render::ShaderData *backend = manager->getOrCreateResource(frontend->id()); - // Init the backend element - backend->setRenderer(renderer); - simulateInitializationSync(frontend, backend); - } - - void initBackendTexture(Qt3DRender::QAbstractTexture *frontend, - Qt3DRender::Render::TextureManager *manager) - { - // Create backend element for frontend one - Qt3DRender::Render::Texture *backend = manager->getOrCreateResource(frontend->id()); - // Init the backend element - simulateInitialization(frontend, backend); - } -}; - -class ScalarShaderData : public Qt3DRender::QShaderData -{ - Q_OBJECT - Q_PROPERTY(float scalar READ scalar WRITE setScalar NOTIFY scalarChanged) - -public: - ScalarShaderData(Qt3DCore::QNode *parent = nullptr) - : Qt3DRender::QShaderData(parent) - , m_scalar(0.0f) - { - } - - void setScalar(float scalar) - { - if (scalar != m_scalar) { - m_scalar = scalar; - emit scalarChanged(); - } - } - - float scalar() const - { - return m_scalar; - } - - QHash buildUniformMap(const QString &blockName) - { - QHash uniforms; - - uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform()); - - return uniforms; - } - -Q_SIGNALS: - void scalarChanged(); - -private: - float m_scalar; -}; - -class TextureShaderData : public Qt3DRender::QShaderData -{ - Q_OBJECT - Q_PROPERTY(Qt3DRender::QAbstractTexture* texture READ texture WRITE setTexture NOTIFY textureChanged) - -public: - TextureShaderData() - : Qt3DRender::QShaderData() - , m_texture(nullptr) - { - } - - void setTexture(Qt3DRender::QAbstractTexture *texture) - { - if (texture != m_texture) { - m_texture = texture; - emit textureChanged(); - } - } - - Qt3DRender::QAbstractTexture *texture() const - { - return m_texture; - } - - QHash buildUniformMap(const QString &blockName) - { - QHash uniforms; - - uniforms.insert(blockName + QStringLiteral(".texture"), Qt3DRender::Render::ShaderUniform()); - - return uniforms; - } - -Q_SIGNALS: - void textureChanged(); - -private: - Qt3DRender::QAbstractTexture *m_texture; -}; - - -class ArrayShaderData : public Qt3DRender::QShaderData -{ - Q_OBJECT - Q_PROPERTY(QVariantList array READ array WRITE setArray NOTIFY arrayChanged) - -public: - ArrayShaderData() - : Qt3DRender::QShaderData() - { - } - - void setArray(const QVariantList &array) - { - if (array != m_array) { - m_array = array; - emit arrayChanged(); - } - } - - QVariantList array() const - { - return m_array; - } - - QHash buildUniformMap(const QString &blockName) - { - QHash uniforms; - - uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform()); - - return uniforms; - } - -Q_SIGNALS: - void arrayChanged(); - -private: - QVariantList m_array; -}; - -class StructShaderData : public Qt3DRender::QShaderData -{ - Q_OBJECT - Q_PROPERTY(float scalar READ scalar WRITE setScalar NOTIFY scalarChanged) - Q_PROPERTY(QVariantList array READ array WRITE setArray NOTIFY arrayChanged) - -public: - StructShaderData() - : Qt3DRender::QShaderData() - , m_scalar(0.0f) - { - } - - void setScalar(float scalar) - { - if (scalar != m_scalar) { - m_scalar = scalar; - emit scalarChanged(); - } - } - - float scalar() const - { - return m_scalar; - } - - void setArray(const QVariantList &array) - { - if (array != m_array) { - m_array = array; - emit arrayChanged(); - } - } - - QVariantList array() const - { - return m_array; - } - - virtual QHash buildUniformMap(const QString &blockName) - { - QHash uniforms; - - uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform()); - uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform()); - - return uniforms; - } - - virtual QHash buildUniformMapValues(const QString &blockName) - { - QHash uniforms; - - uniforms.insert(blockName + QStringLiteral(".scalar"), QVariant(scalar())); - uniforms.insert(blockName + QStringLiteral(".array[0]"), QVariant(array())); - - return uniforms; - } - -Q_SIGNALS: - void scalarChanged(); - void arrayChanged(); - -private: - float m_scalar; - QVariantList m_array; -}; - -class MultiLevelStructShaderData : public StructShaderData -{ - Q_OBJECT - Q_PROPERTY(Qt3DRender::QShaderData *inner READ inner WRITE setInner NOTIFY innerChanged) - -public: - MultiLevelStructShaderData() - : StructShaderData() - , m_inner(nullptr) - { - } - - void setInner(Qt3DRender::QShaderData *inner) - { - if (inner != m_inner) { - m_inner = inner; - emit innerChanged(); - } - } - - Qt3DRender::QShaderData *inner() const - { - return m_inner; - } - - QHash buildUniformMap(const QString &blockName) override - { - QHash innerUniforms; - - StructShaderData *innerData = nullptr; - if ((innerData = qobject_cast(m_inner)) != nullptr) - innerUniforms = innerData->buildUniformMap(QStringLiteral(".inner")); - - QHash uniforms = StructShaderData::buildUniformMap(blockName); - QHash::const_iterator it = innerUniforms.begin(); - const QHash::const_iterator end = innerUniforms.end(); - - while (it != end) { - uniforms.insert(blockName + it.key(), it.value()); - ++it; - } - return uniforms; - } - - QHash buildUniformMapValues(const QString &blockName) override - { - QHash innerUniformsValues; - - StructShaderData *innerData = nullptr; - if ((innerData = qobject_cast(m_inner)) != nullptr) - innerUniformsValues = innerData->buildUniformMapValues(QStringLiteral(".inner")); - - QHash uniformsValues = StructShaderData::buildUniformMapValues(blockName); - QHash::const_iterator it = innerUniformsValues.begin(); - const QHash::const_iterator end = innerUniformsValues.end(); - - while (it != end) { - uniformsValues.insert(blockName + it.key(), it.value()); - ++it; - } - - return uniformsValues; - } - -Q_SIGNALS: - void innerChanged(); - -private: - Qt3DRender::QShaderData *m_inner; -}; - -void tst_RenderViewUtils::topLevelScalarValueNoUniforms() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer shaderData(new ScalarShaderData()); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - shaderData->setScalar(883.0f); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEB - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("")); - - // THEN - // activeUniformNamesToValue should be empty as blockBuilder.uniforms is - QVERIFY(blockBuilder.activeUniformNamesToValue.isEmpty()); -} - -void tst_RenderViewUtils::topLevelScalarValue() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer shaderData(new ScalarShaderData()); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - shaderData->setScalar(883.0f); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms = shaderData->buildUniformMap(QStringLiteral("MyBlock")); - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); - - // THEN - QVERIFY(blockBuilder.uniforms.count() == 1); - QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); - - while (it != end) { - // THEN - QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); - QCOMPARE(it.value(), QVariant(shaderData->scalar())); - ++it; - } -} - -void tst_RenderViewUtils::topLevelTextureValueNoUniforms() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer shaderData(new TextureShaderData); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager); - QScopedPointer texture(new Qt3DRender::QTexture2D); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - shaderData->setTexture(texture.data()); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEB - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("")); - - // THEN - // activeUniformNamesToValue should be empty as blockBuilder.uniforms is - QVERIFY(blockBuilder.activeUniformNamesToValue.isEmpty()); -} - -void tst_RenderViewUtils::topLevelTextureValue() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer shaderData(new TextureShaderData); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager); - QScopedPointer texture(new Qt3DRender::QTexture2D); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - initBackendTexture(texture.data(), textureManager.data()); - shaderData->setTexture(texture.data()); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms = shaderData->buildUniformMap(QStringLiteral("MyBlock")); - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); - - // THEN - QVERIFY(blockBuilder.uniforms.count() == 1); - QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); - - while (it != end) { - // THEN - QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); - QCOMPARE(it.value(), QVariant::fromValue(shaderData->texture()->id())); - ++it; - } -} - -void tst_RenderViewUtils::topLevelArrayValue() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer shaderData(new ArrayShaderData()); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - QVariantList arrayValues = QVariantList() << 454 << 350 << 383 << 427 << 552; - shaderData->setArray(arrayValues); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms = shaderData->buildUniformMap(QStringLiteral("MyBlock")); - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); - - // THEN - QVERIFY(blockBuilder.uniforms.count() == 1); - QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); - - while (it != end) { - // THEN - QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); - QCOMPARE(it.value(), QVariant(arrayValues)); - ++it; - } -} - -void tst_RenderViewUtils::nestedShaderDataValue() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer arrayShaderData(new ArrayShaderData()); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - QScopedPointer shaderData1(new ScalarShaderData(arrayShaderData.data())); - QScopedPointer shaderData2(new ScalarShaderData(arrayShaderData.data())); - QScopedPointer shaderData3(new ScalarShaderData(arrayShaderData.data())); - - shaderData1->setScalar(883.0f); - shaderData2->setScalar(1200.0f); - shaderData3->setScalar(1340.0f); - QHash scalarValues; - scalarValues[QStringLiteral("MyBlock.array[0].scalar")] = shaderData1->scalar(); - scalarValues[QStringLiteral("MyBlock.array[1].scalar")] = shaderData2->scalar(); - scalarValues[QStringLiteral("MyBlock.array[2].scalar")] = shaderData3->scalar(); - - - const Qt3DCore::QNodeId id1 = shaderData1->id(); - const Qt3DCore::QNodeId id2 = shaderData2->id(); - const Qt3DCore::QNodeId id3 = shaderData3->id(); - - // WHEN - const QVariantList arrayValues = QVariantList() << QVariant::fromValue(id1) << QVariant::fromValue(id2) << QVariant::fromValue(id3); - arrayShaderData->setArray(arrayValues); - initBackendShaderData(&renderer, arrayShaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendArrayShaderData = manager->lookupResource(arrayShaderData->id()); - Qt3DRender::Render::ShaderData *backendShaderData1 = manager->lookupResource(id1); - Qt3DRender::Render::ShaderData *backendShaderData2 = manager->lookupResource(id2); - Qt3DRender::Render::ShaderData *backendShaderData3 = manager->lookupResource(id3); - QVERIFY(backendArrayShaderData != nullptr); - QVERIFY(backendShaderData1 != nullptr); - QVERIFY(backendShaderData2 != nullptr); - QVERIFY(backendShaderData3 != nullptr); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0].scalar"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[1].scalar"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[2].scalar"), Qt3DRender::Render::ShaderUniform()); - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendArrayShaderData, QStringLiteral("MyBlock")); - - // THEN - QVERIFY(blockBuilder.uniforms.count() == 3); - QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 3); - - // WHEN - auto it = blockBuilder.uniforms.cbegin(); - const auto end = blockBuilder.uniforms.cend(); - - while (it != end) { - // THEN - const int nameId = Qt3DRender::Render::StringToInt::lookupId(it.key()); - QVERIFY(blockBuilder.activeUniformNamesToValue.contains(nameId)); - QCOMPARE(blockBuilder.activeUniformNamesToValue[nameId], scalarValues.value(it.key())); - ++it; - } -} - -void tst_RenderViewUtils::topLevelStructValue_data() -{ - QTest::addColumn("shaderData"); - QTest::addColumn("blockName"); - - QVariantList arrayValues2 = QVariantList() << 180 << 220 << 250 << 270 << 300 << 350 << 550; - QVariantList arrayValues = QVariantList() << 454 << 350 << 383 << 427 << 552; - - MultiLevelStructShaderData *twoLevelsNestedShaderData = new MultiLevelStructShaderData(); - MultiLevelStructShaderData *singleLevelShaderData = new MultiLevelStructShaderData(); - StructShaderData *shaderData = new StructShaderData(); - - // Don't forget to set the parent so that initBackendShaderData - // properly initializes nested members - shaderData->setParent(singleLevelShaderData); - shaderData->setArray(arrayValues); - shaderData->setScalar(1584.0f); - - singleLevelShaderData->setParent(twoLevelsNestedShaderData); - singleLevelShaderData->setInner(shaderData); - singleLevelShaderData->setScalar(1200.0f); - singleLevelShaderData->setArray(arrayValues2); - - twoLevelsNestedShaderData->setInner(singleLevelShaderData); - twoLevelsNestedShaderData->setArray(arrayValues + arrayValues2); - twoLevelsNestedShaderData->setScalar(1340.0f); - - QTest::newRow("simple struct") << shaderData << QStringLiteral("Block"); - QTest::newRow("single level inner struct") << (StructShaderData *)singleLevelShaderData << QStringLiteral("Block"); - QTest::newRow("tow level inner struct") << (StructShaderData *)twoLevelsNestedShaderData << QStringLiteral("Block"); -} - -void tst_RenderViewUtils::topLevelStructValue() -{ - // GIVEN - TestRenderer renderer; - QFETCH(StructShaderData *, shaderData); - QFETCH(QString, blockName); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - initBackendShaderData(&renderer, shaderData, manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms = shaderData->buildUniformMap(blockName); - const QHash expectedValues = shaderData->buildUniformMapValues(blockName); - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, blockName); - - // THEN - QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), blockBuilder.uniforms.count()); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); - - while (it != end) { - // THEN - QVERIFY(blockBuilder.uniforms.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); - QVERIFY(expectedValues.contains(Qt3DRender::Render::StringToInt::lookupString(it.key()))); - QCOMPARE(it.value(), expectedValues.value(Qt3DRender::Render::StringToInt::lookupString(it.key()))); - ++it; - } -} - -void tst_RenderViewUtils::topLevelDynamicProperties() -{ - // GIVEN - TestRenderer renderer; - QScopedPointer shaderData(new Qt3DRender::QShaderData()); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - QScopedPointer texture(new Qt3DRender::QTexture2D); - QScopedPointer textureManager(new Qt3DRender::Render::TextureManager()); - - // WHEN - initBackendTexture(texture.data(), textureManager.data()); - shaderData->setProperty("scalar", 883.0f); - shaderData->setProperty("array", QVariantList() << 454 << 350 << 383 << 427 << 552); - shaderData->setProperty("texture", QVariant::fromValue(texture.data())); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - - // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; - blockBuilder.shaderDataManager = manager.data(); - blockBuilder.textureManager = textureManager.data(); - blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.scalar"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0]"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.texture"), Qt3DRender::Render::ShaderUniform()); - // build name-value map - blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); - - // THEN - QVERIFY(blockBuilder.uniforms.count() == 3); - QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 3); - - QCOMPARE(blockBuilder.activeUniformNamesToValue.value(Qt3DRender::Render::StringToInt::lookupId("MyBlock.scalar")), - shaderData->property("scalar")); - QCOMPARE(blockBuilder.activeUniformNamesToValue.value(Qt3DRender::Render::StringToInt::lookupId("MyBlock.array[0]")), - shaderData->property("array")); - QCOMPARE(blockBuilder.activeUniformNamesToValue.value(Qt3DRender::Render::StringToInt::lookupId("MyBlock.texture")), - QVariant::fromValue(texture->id())); -} - -void tst_RenderViewUtils::transformedProperties() -{ - // GIVEN - QScopedPointer shaderData(new Qt3DRender::QShaderData()); - QScopedPointer manager(new Qt3DRender::Render::ShaderDataManager()); - TestRenderer renderer; - - // WHEN - const Vector3D position = Vector3D(15.0f, -5.0f, 10.0f); - const QVector3D positionQt = convertToQVector3D(position); - Matrix4x4 worldMatrix; - { - QMatrix4x4 m; - m.translate(-3.0f, 2.0f, 7.5f); - worldMatrix = Matrix4x4(m); - } - Matrix4x4 viewMatrix; - { - QMatrix4x4 m; - m.translate(9.0f, 6.0f, 12.0f); - viewMatrix = Matrix4x4(m); - } - - shaderData->setProperty("position0", positionQt); - shaderData->setProperty("position1", positionQt); - shaderData->setProperty("position2", positionQt); - shaderData->setProperty("position3", positionQt); - shaderData->setProperty("position1Transformed", Qt3DRender::Render::ShaderData::ModelToEye); - shaderData->setProperty("position2Transformed", Qt3DRender::Render::ShaderData::ModelToWorld); - shaderData->setProperty("position3Transformed", Qt3DRender::Render::ShaderData::ModelToWorldDirection); - initBackendShaderData(&renderer, shaderData.data(), manager.data()); - - // THEN - Qt3DRender::Render::ShaderData *backendShaderData = manager->lookupResource(shaderData->id()); - QVERIFY(backendShaderData != nullptr); - QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position0")), Qt3DRender::Render::ShaderData::NoTransform); - QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position1")), Qt3DRender::Render::ShaderData::ModelToEye); - QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position2")), Qt3DRender::Render::ShaderData::ModelToWorld); - QCOMPARE(backendShaderData->propertyTransformType(QStringLiteral("position3")), Qt3DRender::Render::ShaderData::ModelToWorldDirection); - - // WHEN - backendShaderData->updateWorldTransform(worldMatrix); - const Vector3D position1Value = backendShaderData->getTransformedProperty(QStringLiteral("position1"), viewMatrix).value(); - const Vector3D position2Value = backendShaderData->getTransformedProperty(QStringLiteral("position2"), viewMatrix).value(); - const Vector3D position3Value = backendShaderData->getTransformedProperty(QStringLiteral("position3"), viewMatrix).value(); - const QVariant position0Value = backendShaderData->getTransformedProperty(QStringLiteral("position0"), viewMatrix); - - // THEN - QCOMPARE(position0Value, positionQt); - QCOMPARE(position1Value, viewMatrix * worldMatrix * position); - QCOMPARE(position2Value, worldMatrix * position); - QCOMPARE(position3Value, Vector3D((worldMatrix * Vector4D(position, 0.0f)))); -} - -void tst_RenderViewUtils::shouldNotifyDynamicPropertyChanges() -{ - // GIVEN - TestArbiter arbiter; - QScopedPointer shaderData(new Qt3DRender::QShaderData()); - arbiter.setArbiterOnNode(shaderData.data()); - - // WHEN - shaderData->setProperty("scalar", 883.0f); - - // THEN - QCOMPARE(arbiter.events.size(), 0); - QCOMPARE(arbiter.dirtyNodes.size(), 1); - QCOMPARE(arbiter.dirtyNodes.front(), shaderData.data()); - - arbiter.dirtyNodes.clear(); - - // WHEN - QScopedPointer texture(new Qt3DRender::QTexture2D); - shaderData->setProperty("texture", QVariant::fromValue(texture.data())); - - // THEN - QCOMPARE(arbiter.events.size(), 0); - QCOMPARE(arbiter.dirtyNodes.size(), 1); - QCOMPARE(arbiter.dirtyNodes.front(), shaderData.data()); -} - -QTEST_MAIN(tst_RenderViewUtils) - -#include "tst_renderviewutils.moc" diff --git a/tests/auto/render/technique/tst_technique.cpp b/tests/auto/render/technique/tst_technique.cpp index 5b6fdb4a4..b36d00fee 100644 --- a/tests/auto/render/technique/tst_technique.cpp +++ b/tests/auto/render/technique/tst_technique.cpp @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/auto/render/textures/textures.pro b/tests/auto/render/textures/textures.pro deleted file mode 100644 index 8a7553a54..000000000 --- a/tests/auto/render/textures/textures.pro +++ /dev/null @@ -1,12 +0,0 @@ -TEMPLATE = app - -TARGET = tst_textures - -QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib - -CONFIG += testcase - -SOURCES += tst_textures.cpp - -include(../../core/common/common.pri) -include(../commons/commons.pri) diff --git a/tests/auto/render/textures/tst_textures.cpp b/tests/auto/render/textures/tst_textures.cpp deleted file mode 100644 index 12d538772..000000000 --- a/tests/auto/render/textures/tst_textures.cpp +++ /dev/null @@ -1,821 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// TODO Remove in Qt6 -#include -QT_WARNING_DISABLE_DEPRECATED - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -/** - * @brief Dummy QTextureImageDataGenerator - */ -class TestImageDataGenerator : public Qt3DRender::QTextureImageDataGenerator -{ - int m_id; -public: - TestImageDataGenerator(int id) : m_id(id) {} - - Qt3DRender::QTextureImageDataPtr operator ()() override { - return Qt3DRender::QTextureImageDataPtr::create(); - } - - bool operator ==(const Qt3DRender::QTextureImageDataGenerator &other) const override { - const TestImageDataGenerator *otherFunctor = Qt3DRender::functor_cast(&other); - return (otherFunctor != nullptr && otherFunctor->m_id == m_id); - } - - QT3D_FUNCTOR(TestImageDataGenerator) -}; - -/** - * @brief Dummy QTextureGenerator - */ -class TestTextureGenerator : public Qt3DRender::QTextureGenerator -{ - int m_id; -public: - TestTextureGenerator(int id) : m_id(id) {} - - Qt3DRender::QTextureDataPtr operator ()() override { - return Qt3DRender::QTextureDataPtr::create(); - } - - bool operator ==(const Qt3DRender::QTextureGenerator &other) const override { - const TestTextureGenerator *otherFunctor = Qt3DRender::functor_cast(&other); - return (otherFunctor != nullptr && otherFunctor->m_id == m_id); - } - - QT3D_FUNCTOR(TestTextureGenerator) -}; - -typedef QSharedPointer TestTextureGeneratorPtr; - -class TestTexturePrivate : public Qt3DRender::QAbstractTexturePrivate -{ -public: - int genId; -}; - -/** - * @brief Test QTexture. Assign texture data functor if genId > 0. - */ -class TestTexture : public Qt3DRender::QAbstractTexture -{ -public: - TestTexture(int genId, Qt3DCore::QNode *p = nullptr) - : QAbstractTexture(*new TestTexturePrivate(), p) - { - d_func()->genId = genId; - if (genId > 0) - d_func()->setDataFunctor(TestTextureGeneratorPtr::create(genId)); - } -private: - Q_DECLARE_PRIVATE(TestTexture) -}; - -class TestSharedGLTexturePrivate : public Qt3DRender::QAbstractTexturePrivate -{ -}; - -class TestSharedGLTexture : public Qt3DRender::QAbstractTexture -{ -public: - TestSharedGLTexture(int textureId, Qt3DCore::QNode *p = nullptr) - : QAbstractTexture(*new TestSharedGLTexturePrivate(), p) - { - d_func()->m_sharedTextureId = textureId; - } - -private: - Q_DECLARE_PRIVATE(TestSharedGLTexture) -}; - - -/** - * @brief Test QTextureImage - */ -class TestTextureImage : public Qt3DRender::QAbstractTextureImage -{ -public: - TestTextureImage(int genId, Qt3DCore::QNode *p = nullptr) - : QAbstractTextureImage(p) - , m_genId(genId) - { - } - - void updateGenerator() - { - Qt3DRender::QAbstractTextureImage::notifyDataGeneratorChanged(); - } - - Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator() const - { - return Qt3DRender::QTextureImageDataGeneratorPtr(new TestImageDataGenerator(m_genId)); - } -protected: - int m_genId; -}; - -class EmptyTextureImage : public Qt3DRender::QAbstractTextureImage -{ -public: - EmptyTextureImage(Qt3DCore::QNode *p = nullptr) - : QAbstractTextureImage(p) - { - } - - Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator() const - { - return {}; - } -}; - -class tst_RenderTextures : public Qt3DCore::QBackendNodeTester -{ - Q_OBJECT - - Qt3DRender::QAbstractTexture *createQTexture(int genId, - const QVector &imgGenIds, - bool genMipMaps) - { - TestTexture *tex = new TestTexture(genId); - - for (int imgGen : imgGenIds) - tex->addTextureImage(new TestTextureImage(imgGen)); - tex->setGenerateMipMaps(genMipMaps); - - return tex; - } - - Qt3DRender::QAbstractTexture *createQTextureWithTextureId(int textureId) - { - return new TestSharedGLTexture(textureId); - } - - Qt3DRender::Render::Texture *createBackendTexture(Qt3DRender::QAbstractTexture *frontend, - Qt3DRender::Render::TextureManager *texMgr, - Qt3DRender::Render::TextureImageManager *texImgMgr, - Qt3DRender::Render::AbstractRenderer *renderer) - { - Qt3DRender::Render::Texture *backend = texMgr->getOrCreateResource(frontend->id()); - backend->setRenderer(renderer); - simulateInitializationSync(frontend, backend); - - // create texture images - for (const auto texImgFrontend : frontend->textureImages()) { - // make sure TextureImageManager has backend node for this QTextureImage - if (!texImgMgr->contains(texImgFrontend->id())) { - Qt3DRender::Render::TextureImage *texImgBackend = texImgMgr->getOrCreateResource(texImgFrontend->id()); - texImgBackend->setRenderer(renderer); - simulateInitializationSync(texImgFrontend, texImgBackend); - } - } - - return backend; - } - -private Q_SLOTS: - - void shouldCreateSameGLTextures() - { - QSKIP("Texture Sharing is now disabled"); - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - renderer.setNodeManagers(mgrs.data()); - - // GIVEN - Qt3DRender::QAbstractTexture *tex1a = createQTexture(-1, {1,2}, true); - Qt3DRender::QAbstractTexture *tex1b = createQTexture(-1, {1,2}, true); - - // WHEN - Qt3DRender::Render::Texture *bt1a = createBackendTexture(tex1a, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - Qt3DRender::Render::Texture *bt1b = createBackendTexture(tex1b, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - renderer.updateTexture(bt1a); - renderer.updateTexture(bt1b); - - // THEN - QCOMPARE(renderer.glResourceManagers()->glTextureManager()->lookupResource(bt1a->peerId()), - renderer.glResourceManagers()->glTextureManager()->lookupResource(bt1b->peerId())); - renderer.shutdown(); - } - - void shouldCreateDifferentGLTexturess() - { - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - renderer.setNodeManagers(mgrs.data()); - - // GIVEN - QVector textures; - textures << createQTexture(-1, {1,2}, true); - textures << createQTexture(-1, {1,2}, false); - textures << createQTexture(1, {1,2}, true); - textures << createQTexture(1, {1,2}, false); - textures << createQTexture(1, {1,2,3}, true); - textures << createQTexture(1, {1,2,3}, false); - - // WHEN - QVector backend; - for (auto *t : textures) { - Qt3DRender::Render::Texture *backendTexture = createBackendTexture(t, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - backend.push_back(backendTexture); - renderer.updateTexture(backendTexture); - } - - // THEN - - // no 2 textures must be the same - for (int i = 0; i < backend.size(); i++) - for (int k = i+1; k < backend.size(); k++) - QVERIFY(renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[i]->peerId()) != - renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[k]->peerId())); - - QVector glTextures; - for (Qt3DRender::Render::Texture *t : backend) - glTextures.push_back(renderer.glResourceManagers()->glTextureManager()->lookupResource(t->peerId())); - - // some texture generators must be the same - QVERIFY(glTextures[0]->textureGenerator().data() == nullptr); - QVERIFY(glTextures[1]->textureGenerator().data() == nullptr); - QCOMPARE(*(glTextures[2]->textureGenerator()), *(glTextures[3]->textureGenerator())); - - // some images must be the same - QCOMPARE(glTextures[0]->images(), glTextures[1]->images()); - QCOMPARE(glTextures[0]->images(), glTextures[2]->images()); - QCOMPARE(glTextures[0]->images(), glTextures[3]->images()); - QCOMPARE(glTextures[4]->images(), glTextures[5]->images()); - - QCOMPARE(glTextures[0]->properties(), glTextures[2]->properties()); - QCOMPARE(glTextures[1]->properties(), glTextures[3]->properties()); - QVERIFY(glTextures[0]->properties() != glTextures[1]->properties()); - - renderer.shutdown(); - } - - void shouldCreateDifferentGLTexturesWhenUsingSharedTextureIds() - { - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - renderer.setNodeManagers(mgrs.data()); - - Qt3DRender::Render::GLResourceManagers *glMgrs = renderer.glResourceManagers(); - - // both texture having the same sharedTextureId - { - // GIVEN - Qt3DRender::QAbstractTexture *tex1a = createQTextureWithTextureId(1); - Qt3DRender::QAbstractTexture *tex1b = createQTextureWithTextureId(1); - - // WHEN - Qt3DRender::Render::Texture *bt1 = createBackendTexture(tex1a, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - Qt3DRender::Render::Texture *bt2 = createBackendTexture(tex1b, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - // THEN - QCOMPARE(bt1->sharedTextureId(), 1); - QCOMPARE(bt2->sharedTextureId(), 1); - - // WHEN - renderer.updateTexture(bt1); - renderer.updateTexture(bt2); - - // THEN - Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); - Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); - QVERIFY(glt1 != glt2); - QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); - QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); - } - - // textures having a different sharedTextureId - { - // GIVEN - Qt3DRender::QAbstractTexture *tex1a = createQTextureWithTextureId(1); - Qt3DRender::QAbstractTexture *tex1b = createQTextureWithTextureId(2); - - // WHEN - Qt3DRender::Render::Texture *bt1 = createBackendTexture(tex1a, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - Qt3DRender::Render::Texture *bt2 = createBackendTexture(tex1b, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - // THEN - QCOMPARE(bt1->sharedTextureId(), 1); - QCOMPARE(bt2->sharedTextureId(), 2); - - // WHEN - renderer.updateTexture(bt1); - renderer.updateTexture(bt2); - - // THEN - Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); - Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); - QVERIFY(glt1 != glt2); - QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); - QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); - } - - renderer.shutdown(); - } - - void generatorsShouldCreateSameData() - { - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - renderer.setNodeManagers(mgrs.data()); - - // GIVEN - QVector textures; - textures << createQTexture(1, {1}, true); - textures << createQTexture(2, {1,2}, true); - textures << createQTexture(1, {1,2}, true); - - // WHEN - QVector backend; - for (auto *t : textures) { - Qt3DRender::Render::Texture *backendTexture = createBackendTexture(t, - mgrs->textureManager(), - mgrs->textureImageManager(), - &renderer); - backend.push_back(backendTexture); - renderer.updateTexture(backendTexture); - } - - Qt3DRender::QTextureImageDataGeneratorPtr idg1a = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[0]->peerId())->images()[0].generator; - Qt3DRender::QTextureImageDataGeneratorPtr idg1b = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->images()[0].generator; - Qt3DRender::QTextureImageDataGeneratorPtr idg2 = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->images()[1].generator; - Qt3DRender::QTextureGeneratorPtr tg1a = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[0]->peerId())->textureGenerator(); - Qt3DRender::QTextureGeneratorPtr tg1b = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[2]->peerId())->textureGenerator(); - Qt3DRender::QTextureGeneratorPtr tg2 = renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[1]->peerId())->textureGenerator(); - - // THEN - QVERIFY(idg1a); - QVERIFY(idg1b); - QVERIFY(idg2); - QVERIFY(tg1a); - QVERIFY(tg1b); - QVERIFY(tg2); - - QCOMPARE(*idg1a, *idg1b); - QVERIFY(!(*idg1a == *idg2)); - QCOMPARE(*tg1a, *tg1b); - QVERIFY(!(*tg1a == *tg2)); - - renderer.shutdown(); - } - - void checkTextureImageInitialState() - { - // GIVEN - Qt3DRender::Render::TextureImage img; - - // THEN - QCOMPARE(img.layer(), 0); - QCOMPARE(img.mipLevel(), 0); - QCOMPARE(img.isDirty(), false); - QCOMPARE(img.face(), Qt3DRender::QAbstractTexture::CubeMapPositiveX); - QVERIFY(img.dataGenerator().isNull()); - } - - void checkTextureImageCleanupState() - { - // GIVEN - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - TestTextureImage img(1); - img.setLayer(2); - img.setMipLevel(3); - - // WHEN - Qt3DRender::Render::TextureImage texImgBackend; - texImgBackend.setRenderer(&renderer); - simulateInitializationSync(&img, &texImgBackend); - texImgBackend.cleanup(); - - // THEN - QCOMPARE(texImgBackend.isDirty(), false); - QCOMPARE(texImgBackend.layer(), 0); - QCOMPARE(texImgBackend.mipLevel(), 0); - QCOMPARE(texImgBackend.face(), Qt3DRender::QAbstractTexture::CubeMapPositiveX); - QVERIFY(texImgBackend.dataGenerator().isNull()); - - renderer.shutdown(); - } - - void checkTextureImageInitializeFromPeer() - { - // GIVEN - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - TestTextureImage img(1); - - { - // WHEN - img.setLayer(2); - img.setMipLevel(3); - - Qt3DRender::Render::TextureImage texImgBackend; - texImgBackend.setRenderer(&renderer); - simulateInitializationSync(&img, &texImgBackend); - - // THEN - QCOMPARE(texImgBackend.isEnabled(), true); - QCOMPARE(texImgBackend.isDirty(), true); - QCOMPARE(texImgBackend.peerId(), img.id()); - QCOMPARE(texImgBackend.layer(), 2); - QCOMPARE(texImgBackend.mipLevel(), 3); - QCOMPARE(texImgBackend.face(), Qt3DRender::QAbstractTexture::CubeMapPositiveX); - QVERIFY(!texImgBackend.dataGenerator().isNull()); - } - - { - // WHEN - img.setEnabled(false); - - Qt3DRender::Render::TextureImage texImgBackend; - texImgBackend.setRenderer(&renderer); - simulateInitializationSync(&img, &texImgBackend); - - // THEN - QCOMPARE(texImgBackend.isEnabled(), false); - QCOMPARE(texImgBackend.peerId(), img.id()); - } - - renderer.shutdown(); - } - - void checkTextureImageSceneChangeEvents() - { - // GIVEN - Qt3DRender::Render::TextureImage backendImage; - TestTextureImage textureImage(1); - TestRenderer renderer; - backendImage.setRenderer(&renderer); - simulateInitializationSync(&textureImage, &backendImage); - - { - // WHEN - const bool newValue = false; - textureImage.setEnabled(newValue); - backendImage.syncFromFrontEnd(&textureImage, false); - - // THEN - QCOMPARE(backendImage.isEnabled(), newValue); - QVERIFY(backendImage.isDirty()); - QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - backendImage.unsetDirty(); - } - - { - // WHEN - const int newValue = 7; - textureImage.setLayer(newValue); - backendImage.syncFromFrontEnd(&textureImage, false); - - // THEN - QCOMPARE(backendImage.layer(), newValue); - QVERIFY(backendImage.isDirty()); - QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - backendImage.unsetDirty(); - } - - { - // WHEN - const int newValue = 3; - textureImage.setMipLevel(newValue); - backendImage.syncFromFrontEnd(&textureImage, false); - - - // THEN - QCOMPARE(backendImage.mipLevel(), newValue); - QVERIFY(backendImage.isDirty()); - QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - backendImage.unsetDirty(); - } - - { - // WHEN - const Qt3DRender::QAbstractTexture::CubeMapFace newValue = Qt3DRender::QAbstractTexture::CubeMapNegativeX; - textureImage.setFace(newValue); - backendImage.syncFromFrontEnd(&textureImage, false); - - // THEN - QCOMPARE(backendImage.face(), newValue); - QVERIFY(backendImage.isDirty()); - QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - backendImage.unsetDirty(); - } - - { - // WHEN - textureImage.updateGenerator(); - backendImage.syncFromFrontEnd(&textureImage, false); - - // THEN - QVERIFY(backendImage.isDirty()); - QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - backendImage.unsetDirty(); - - // WHEN - textureImage.updateGenerator(); - backendImage.syncFromFrontEnd(&textureImage, false); - - // THEN - QVERIFY(backendImage.isDirty()); - QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty); - renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty); - backendImage.unsetDirty(); - } - - renderer.shutdown(); - } - - void checkTextureImageProperlyReleaseGenerator() - { - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); - Qt3DRender::Render::TextureImageManager *texImgMgr = mgrs->textureImageManager(); - renderer.setNodeManagers(mgrs.data()); - - // GIVEN - Qt3DRender::QAbstractTexture* frontendTexture = createQTexture(1, {1}, true); - - Qt3DRender::Render::Texture *backendTexture = texMgr->getOrCreateResource(frontendTexture->id()); - backendTexture->setRenderer(&renderer); - simulateInitializationSync(frontendTexture, backendTexture); - - // THEN - QCOMPARE(backendTexture->textureImageIds().size(), 1); - QCOMPARE(frontendTexture->textureImages().size(), 1); - - // WHEN - TestTextureImage *texImgFrontend = static_cast(frontendTexture->textureImages().first()); - const Qt3DRender::QTextureImageDataGeneratorPtr frontendGenerator = texImgFrontend->dataGenerator(); - - // THEN - QVERIFY(!frontendGenerator.isNull()); - - // WHEN - Qt3DRender::Render::TextureImage *texImgBackend = texImgMgr->getOrCreateResource(texImgFrontend->id()); - texImgBackend->setRenderer(&renderer); - simulateInitializationSync(texImgFrontend, texImgBackend); - - // THEN - qDebug() << frontendGenerator << texImgBackend->dataGenerator(); - const Qt3DRender::QTextureImageDataGeneratorPtr backendGenerator = texImgFrontend->dataGenerator(); - QVERIFY(frontendGenerator != backendGenerator); - QVERIFY(*frontendGenerator == *backendGenerator); - - renderer.shutdown(); - } - - void checkTextureIsMarkedForDeletion() - { - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); - renderer.setNodeManagers(mgrs.data()); - - Qt3DRender::Render::TextureFunctor textureBackendNodeMapper(&renderer, - texMgr); - - // GIVEN - Qt3DRender::QAbstractTexture* frontendTexture = createQTexture(1, {1}, true); - - Qt3DRender::Render::Texture *backendTexture = static_cast(textureBackendNodeMapper.create(creationChange(frontendTexture))); - backendTexture->setRenderer(&renderer); - simulateInitializationSync(frontendTexture, backendTexture); - - // THEN - QVERIFY(backendTexture != nullptr); - QCOMPARE(texMgr->textureIdsToCleanup().size(), 0); - - QCOMPARE(texMgr->lookupResource(frontendTexture->id()), backendTexture); - - // WHEN - textureBackendNodeMapper.destroy(frontendTexture->id()); - - // THEN - QCOMPARE(texMgr->textureIdsToCleanup().size(), 1); - QCOMPARE(texMgr->textureIdsToCleanup().first(), frontendTexture->id()); - QVERIFY(texMgr->lookupResource(frontendTexture->id()) == nullptr); - - renderer.shutdown(); - } - - void checkTextureDestructionReconstructionWithinSameLoop() - { - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); - renderer.setNodeManagers(mgrs.data()); - - Qt3DRender::Render::TextureFunctor textureBackendNodeMapper(&renderer, - texMgr); - - // GIVEN - Qt3DRender::QAbstractTexture* frontendTexture = createQTexture(1, {1}, true); - - Qt3DRender::Render::Texture *backendTexture = static_cast(textureBackendNodeMapper.create(creationChange(frontendTexture))); - backendTexture->setRenderer(&renderer); - simulateInitializationSync(frontendTexture, backendTexture); - - // WHEN - textureBackendNodeMapper.destroy(frontendTexture->id()); - - // THEN - QCOMPARE(texMgr->textureIdsToCleanup().size(), 1); - QCOMPARE(texMgr->textureIdsToCleanup().first(), frontendTexture->id()); - QVERIFY(texMgr->lookupResource(frontendTexture->id()) == nullptr); - - // WHEN - backendTexture = static_cast(textureBackendNodeMapper.create(creationChange(frontendTexture))); - backendTexture->setRenderer(&renderer); - simulateInitializationSync(frontendTexture, backendTexture); - - // THEN - QVERIFY(backendTexture != nullptr); - QCOMPARE(texMgr->textureIdsToCleanup().size(), 0); - QCOMPARE(texMgr->lookupResource(frontendTexture->id()), backendTexture); - - renderer.shutdown(); - } - - void checkTextureImageDirtinessPropagatesToTextures() - { - // GIVEN - QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); - Qt3DRender::Render::TextureImageManager *texImgMgr = mgrs->textureImageManager(); - renderer.setNodeManagers(mgrs.data()); - - Qt3DRender::QTexture2D *texture1 = new Qt3DRender::QTexture2D(); - TestTextureImage *image1 = new TestTextureImage(1); - - Qt3DRender::QTexture2D *texture2 = new Qt3DRender::QTexture2D(); - TestTextureImage *image2 = new TestTextureImage(2); - - Qt3DRender::QTexture2D *texture3 = new Qt3DRender::QTexture2D(); - - texture1->addTextureImage(image1); - texture2->addTextureImage(image2); - texture3->addTextureImage(image1); - texture3->addTextureImage(image2); - - Qt3DRender::Render::Texture *backendTexture1 = texMgr->getOrCreateResource(texture1->id()); - Qt3DRender::Render::Texture *backendTexture2 = texMgr->getOrCreateResource(texture2->id()); - Qt3DRender::Render::Texture *backendTexture3 = texMgr->getOrCreateResource(texture3->id()); - Qt3DRender::Render::TextureImage *backendImage1 = texImgMgr->getOrCreateResource(image1->id()); - Qt3DRender::Render::TextureImage *backendImage2 = texImgMgr->getOrCreateResource(image2->id()); - - backendTexture1->setRenderer(&renderer); - backendTexture2->setRenderer(&renderer); - backendTexture3->setRenderer(&renderer); - backendImage1->setRenderer(&renderer); - backendImage2->setRenderer(&renderer); - - simulateInitializationSync(texture1, backendTexture1); - simulateInitializationSync(texture2, backendTexture2); - simulateInitializationSync(texture3, backendTexture3); - simulateInitializationSync(image1, backendImage1); - simulateInitializationSync(image2, backendImage2); - - // THEN - QCOMPARE(backendTexture1->textureImageIds().size(), 1); - QCOMPARE(backendTexture1->textureImageIds().first(), image1->id()); - QCOMPARE(backendTexture2->textureImageIds().size(), 1); - QCOMPARE(backendTexture2->textureImageIds().first(), image2->id()); - QCOMPARE(backendTexture3->textureImageIds().size(), 2); - QCOMPARE(backendTexture3->textureImageIds().first(), image1->id()); - QCOMPARE(backendTexture3->textureImageIds().last(), image2->id()); - - // WHEN - backendTexture1->unsetDirty(); - backendTexture2->unsetDirty(); - backendTexture3->unsetDirty(); - backendImage1->unsetDirty(); - backendImage2->unsetDirty(); - - // THEN - QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - - // WHEN - renderer.textureGathererJob()->run(); - - // THEN - QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - - // WHEN - // Make Image1 dirty - image1->updateGenerator(); - backendImage1->syncFromFrontEnd(image1, false); - - // THEN - QVERIFY(backendImage1->isDirty()); - QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - - // WHEN - renderer.textureGathererJob()->run(); - - // THEN - QVERIFY(backendTexture1->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); - QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture3->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); - - backendImage1->unsetDirty(); - backendTexture1->unsetDirty(); - backendTexture3->unsetDirty(); - - // WHEN - image2->updateGenerator(); - backendImage2->syncFromFrontEnd(image2, false); - - // THEN - QVERIFY(backendImage2->isDirty()); - QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture2->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture3->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - - // WHEN - renderer.textureGathererJob()->run(); - - QVERIFY(backendTexture1->dirtyFlags() == Qt3DRender::Render::Texture::NotDirty); - QVERIFY(backendTexture2->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); - QVERIFY(backendTexture3->dirtyFlags() & Qt3DRender::Render::Texture::DirtyImageGenerators); - - renderer.shutdown(); - } -}; - -QTEST_MAIN(tst_RenderTextures) - -#include "tst_textures.moc" diff --git a/tests/auto/render/trianglesextractor/tst_trianglesextractor.cpp b/tests/auto/render/trianglesextractor/tst_trianglesextractor.cpp index 287a17b84..24d7ff643 100644 --- a/tests/auto/render/trianglesextractor/tst_trianglesextractor.cpp +++ b/tests/auto/render/trianglesextractor/tst_trianglesextractor.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include diff --git a/tests/benchmarks/render/jobs/jobs.pro b/tests/benchmarks/render/jobs/jobs.pro index bfd0f1317..71b0ef409 100644 --- a/tests/benchmarks/render/jobs/jobs.pro +++ b/tests/benchmarks/render/jobs/jobs.pro @@ -7,3 +7,7 @@ QT += testlib core core-private 3dcore 3dcore-private 3drender 3drender-private SOURCES += tst_bench_jobs.cpp DEFINES += QT3D_RENDER_UNIT_TESTS +DEFINES += QT_BUILD_INTERNAL + +# Link Against OpenGL Renderer Plugin +include(../../../auto/render/opengl/opengl_render_plugin.pri) diff --git a/tests/benchmarks/render/jobs/tst_bench_jobs.cpp b/tests/benchmarks/render/jobs/tst_bench_jobs.cpp index b611f3cdc..87689e46c 100644 --- a/tests/benchmarks/render/jobs/tst_bench_jobs.cpp +++ b/tests/benchmarks/render/jobs/tst_bench_jobs.cpp @@ -41,7 +41,6 @@ #include #include #include -#include #include #include #include @@ -50,6 +49,7 @@ #include #include #include +#include #include #include diff --git a/tests/benchmarks/render/materialparametergathering/materialparametergathering.pro b/tests/benchmarks/render/materialparametergathering/materialparametergathering.pro index e227a08a0..a20372163 100644 --- a/tests/benchmarks/render/materialparametergathering/materialparametergathering.pro +++ b/tests/benchmarks/render/materialparametergathering/materialparametergathering.pro @@ -12,3 +12,6 @@ include(../../../auto/render/commons/commons.pri) # Needed to use the TestAspect DEFINES += QT_BUILD_INTERNAL + +# Link Against OpenGL Renderer Plugin +include(../../../auto/render/opengl/opengl_render_plugin.pri) diff --git a/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp b/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp index 210d82dcf..644c4d74c 100644 --- a/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp +++ b/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp @@ -37,7 +37,7 @@ #include #include #include -#include +#include #include #include #include -- cgit v1.2.3 From 01358191691cc81acb58afba6f82e800bc1b427c Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Mon, 12 Mar 2018 15:23:34 +0100 Subject: Move classes in OpenGL renderer plugin into an OpenGL namespace Change-Id: I5314da1df7fbfd1b6db4412e7bc71231525d9de2 Reviewed-by: Mike Krus --- .../renderers/opengl/debug/imguirenderer.cpp | 3 +- .../renderers/opengl/debug/imguirenderer_p.h | 13 ++-- .../opengl/graphicshelpers/graphicscontext.cpp | 4 +- .../opengl/graphicshelpers/graphicscontext_p.h | 12 ++-- .../opengl/graphicshelpers/graphicshelperes2.cpp | 9 ++- .../opengl/graphicshelpers/graphicshelperes2_p.h | 8 ++- .../opengl/graphicshelpers/graphicshelperes3.cpp | 8 ++- .../opengl/graphicshelpers/graphicshelperes3_1.cpp | 2 + .../opengl/graphicshelpers/graphicshelperes3_1_p.h | 2 + .../opengl/graphicshelpers/graphicshelperes3_2.cpp | 2 + .../opengl/graphicshelpers/graphicshelperes3_2_p.h | 8 ++- .../opengl/graphicshelpers/graphicshelperes3_p.h | 8 ++- .../opengl/graphicshelpers/graphicshelpergl2.cpp | 6 +- .../opengl/graphicshelpers/graphicshelpergl2_p.h | 8 ++- .../opengl/graphicshelpers/graphicshelpergl3_2.cpp | 16 +++-- .../opengl/graphicshelpers/graphicshelpergl3_2_p.h | 8 ++- .../opengl/graphicshelpers/graphicshelpergl3_3.cpp | 14 ++-- .../opengl/graphicshelpers/graphicshelpergl3_3_p.h | 8 ++- .../opengl/graphicshelpers/graphicshelpergl4.cpp | 14 ++-- .../opengl/graphicshelpers/graphicshelpergl4_p.h | 8 ++- .../graphicshelpers/graphicshelperinterface_p.h | 11 +-- .../graphicshelpers/imagesubmissioncontext.cpp | 4 +- .../graphicshelpers/imagesubmissioncontext_p.h | 12 ++-- .../opengl/graphicshelpers/qgraphicsutils_p.h | 10 ++- .../opengl/graphicshelpers/submissioncontext.cpp | 10 +-- .../opengl/graphicshelpers/submissioncontext_p.h | 22 +++--- .../graphicshelpers/texturesubmissioncontext.cpp | 3 + .../graphicshelpers/texturesubmissioncontext_p.h | 8 ++- src/plugins/renderers/opengl/io/glbuffer.cpp | 4 ++ src/plugins/renderers/opengl/io/glbuffer_p.h | 10 ++- .../opengl/jobs/filtercompatibletechniquejob.cpp | 2 + .../opengl/jobs/filtercompatibletechniquejob_p.h | 10 ++- .../opengl/jobs/materialparametergathererjob.cpp | 4 ++ .../opengl/jobs/materialparametergathererjob_p.h | 10 ++- .../renderers/opengl/jobs/renderviewbuilderjob.cpp | 4 ++ .../renderers/opengl/jobs/renderviewbuilderjob_p.h | 12 +++- .../opengl/jobs/renderviewcommandbuilderjob.cpp | 4 ++ .../opengl/jobs/renderviewcommandbuilderjob_p.h | 10 ++- .../opengl/jobs/renderviewcommandupdaterjob.cpp | 5 ++ .../opengl/jobs/renderviewcommandupdaterjob_p.h | 10 ++- .../opengl/jobs/renderviewinitializerjob.cpp | 2 + .../opengl/jobs/renderviewinitializerjob_p.h | 12 ++-- .../renderers/opengl/jobs/renderviewjobutils.cpp | 2 + .../renderers/opengl/jobs/renderviewjobutils_p.h | 19 ++--- src/plugins/renderers/opengl/main.cpp | 2 +- .../renderers/opengl/managers/gl_handle_types_p.h | 4 ++ .../opengl/managers/glresourcemanagers.cpp | 3 + .../opengl/managers/glresourcemanagers_p.h | 12 ++-- .../renderers/opengl/renderer/commandexecuter.cpp | 18 ++--- .../renderers/opengl/renderer/commandexecuter_p.h | 8 ++- src/plugins/renderers/opengl/renderer/glshader.cpp | 5 ++ src/plugins/renderers/opengl/renderer/glshader_p.h | 10 ++- src/plugins/renderers/opengl/renderer/logging.cpp | 4 ++ src/plugins/renderers/opengl/renderer/logging_p.h | 4 ++ .../opengl/renderer/openglvertexarrayobject.cpp | 2 + .../opengl/renderer/openglvertexarrayobject_p.h | 14 ++-- .../renderers/opengl/renderer/rendercommand.cpp | 2 + .../renderers/opengl/renderer/rendercommand_p.h | 10 ++- src/plugins/renderers/opengl/renderer/renderer.cpp | 19 ++--- src/plugins/renderers/opengl/renderer/renderer_p.h | 31 +++++---- .../renderers/opengl/renderer/renderercache_p.h | 10 ++- .../renderers/opengl/renderer/renderqueue.cpp | 4 ++ .../renderers/opengl/renderer/renderqueue_p.h | 10 ++- .../renderers/opengl/renderer/renderview.cpp | 2 + .../renderers/opengl/renderer/renderview_p.h | 14 ++-- .../opengl/renderer/renderviewbuilder.cpp | 9 ++- .../opengl/renderer/renderviewbuilder_p.h | 10 ++- .../opengl/renderer/shaderparameterpack.cpp | 2 + .../opengl/renderer/shaderparameterpack_p.h | 16 +++-- .../renderers/opengl/renderer/shadervariables_p.h | 18 +++-- .../renderers/opengl/textures/gltexture.cpp | 2 + .../renderers/opengl/textures/gltexture_p.h | 12 +++- .../renderers/opengl/textures/renderbuffer.cpp | 2 + .../renderers/opengl/textures/renderbuffer_p.h | 8 ++- src/render/framegraph/nopicking_p.h | 1 + src/render/frontend/qrenderaspect.cpp | 1 + src/render/materialsystem/shader.cpp | 6 ++ src/render/materialsystem/shader_p.h | 14 ++-- .../opengl/computecommand/tst_computecommand.cpp | 4 +- .../tst_filtercompatibletechniquejob.cpp | 10 +-- .../opengl/glshadermanager/tst_glshadermanager.cpp | 26 +++---- .../graphicshelpergl2/tst_graphicshelpergl2.cpp | 1 + .../tst_graphicshelpergl3_2.cpp | 1 + .../tst_graphicshelpergl3_3.cpp | 1 + .../graphicshelpergl4/tst_graphicshelpergl4.cpp | 1 + .../tst_materialparametergathererjob.cpp | 56 +++++++-------- .../opengl/qgraphicsutils/tst_qgraphicsutils.cpp | 76 ++++++++++---------- tests/auto/render/opengl/renderer/tst_renderer.cpp | 12 ++-- .../render/opengl/renderqueue/tst_renderqueue.cpp | 32 ++++----- .../renderviewbuilder/tst_renderviewbuilder.cpp | 49 ++++++------- .../render/opengl/renderviews/tst_renderviews.cpp | 20 +++--- .../opengl/renderviewutils/tst_renderviewutils.cpp | 80 +++++++++++----------- tests/auto/render/opengl/textures/tst_textures.cpp | 32 ++++----- tests/benchmarks/render/jobs/tst_bench_jobs.cpp | 22 +++--- .../tst_bench_materialparametergathering.cpp | 6 +- 95 files changed, 658 insertions(+), 421 deletions(-) diff --git a/src/plugins/renderers/opengl/debug/imguirenderer.cpp b/src/plugins/renderers/opengl/debug/imguirenderer.cpp index acc6e6775..e23476860 100644 --- a/src/plugins/renderers/opengl/debug/imguirenderer.cpp +++ b/src/plugins/renderers/opengl/debug/imguirenderer.cpp @@ -69,6 +69,7 @@ QT_BEGIN_NAMESPACE using namespace Qt3DRender; using namespace Render; using namespace Render::Debug; +using namespace Render::OpenGL; namespace { @@ -135,7 +136,7 @@ namespace { } } -ImGuiRenderer::ImGuiRenderer(Renderer *renderer) +ImGuiRenderer::ImGuiRenderer(Qt3DRender::Render::OpenGL::Renderer *renderer) : m_renderer(renderer) { ImGui::CreateContext(); diff --git a/src/plugins/renderers/opengl/debug/imguirenderer_p.h b/src/plugins/renderers/opengl/debug/imguirenderer_p.h index e574574be..f462bbd5b 100644 --- a/src/plugins/renderers/opengl/debug/imguirenderer_p.h +++ b/src/plugins/renderers/opengl/debug/imguirenderer_p.h @@ -72,9 +72,10 @@ class QServiceLocator; namespace Qt3DRender { namespace Render { - +namespace OpenGL { class RenderView; class Renderer; +} namespace Debug { @@ -83,21 +84,21 @@ namespace Debug { class ImGuiRenderer : public QObject { Q_OBJECT public: - ImGuiRenderer(Qt3DRender::Render::Renderer *renderer); + ImGuiRenderer(Qt3DRender::Render::OpenGL::Renderer *renderer); void processEvent(QEvent *event); - void renderDebugOverlay(const QVector &renderViews, const Render::RenderView *renderView, int jobsInLastFrame); + void renderDebugOverlay(const QVector &renderViews, const Render::OpenGL::RenderView *renderView, int jobsInLastFrame); void setCapabilities(const QString &capabilities); private: - bool newFrame(const RenderView *renderView); + bool newFrame(const Render::OpenGL::RenderView *renderView); void renderDrawList(ImDrawData *draw_data); void onMouseChange(QMouseEvent *event); void onWheel(QWheelEvent *event); void onKeyPressRelease(QKeyEvent *event); void showGLInfo(); - void showRenderDetails(const QVector &renderViews); + void showRenderDetails(const QVector &renderViews); bool createFontsTexture(); bool createDeviceObjects(); @@ -112,7 +113,7 @@ private: int m_attribLocationPosition = 0, m_attribLocationUV = 0, m_attribLocationColor = 0; unsigned int m_vboHandle = 0, m_vaoHandle = 0, m_elementsHandle = 0; - Renderer *m_renderer; + Render::OpenGL::Renderer *m_renderer; QOpenGLExtraFunctions *m_funcs = nullptr; QOpenGLShaderProgram *m_shader = nullptr; diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp index abe11fd4d..a4152449f 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp @@ -118,6 +118,7 @@ QOpenGLShader::ShaderType shaderType(Qt3DRender::QShaderProgram::ShaderType type namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { @@ -324,7 +325,7 @@ void GraphicsContext::loadShader(Shader *shaderNode, } shaderNode->unsetDirty(); // Ensure we will rebuilt material caches - shaderNode->markDirty(AbstractRenderer::AllDirty); + shaderNode->requestCacheRebuild(); } void GraphicsContext::activateDrawBuffers(const AttachmentPack &attachments) @@ -1022,6 +1023,7 @@ QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4x2, float, glUniformMatrix4x2fv) QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat3x4, float, glUniformMatrix3x4fv) QT3D_UNIFORM_TYPE_IMPL(UniformType::Mat4x3, float, glUniformMatrix4x3fv) +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender of namespace diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h index 07df3e9e4..5d122f450 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSCONTEXT_H -#define QT3DRENDER_RENDER_GRAPHICSCONTEXT_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSCONTEXT_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSCONTEXT_H // // W A R N I N G @@ -84,10 +84,13 @@ namespace Qt3DRender { namespace Render { -class GraphicsHelperInterface; class RenderTarget; class AttachmentPack; class ShaderManager; + +namespace OpenGL { + +class GraphicsHelperInterface; class GLShader; class GLShaderManager; @@ -256,9 +259,10 @@ QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4x2, float, glUniformMatrix4x2fv) QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat3x4, float, glUniformMatrix3x4fv) QT3D_UNIFORM_TYPE_PROTO(UniformType::Mat4x3, float, glUniformMatrix4x3fv) +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GRAPHICSCONTEXT_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSCONTEXT_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp index ba00325b1..3ae9ed932 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp @@ -38,12 +38,13 @@ ****************************************************************************/ #include "graphicshelperes2_p.h" -#include #include #include #include +#include #include + QT_BEGIN_NAMESPACE // ES 3.0+ @@ -65,6 +66,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { GraphicsHelperES2::GraphicsHelperES2() : m_funcs(0) @@ -293,7 +295,7 @@ void GraphicsHelperES2::vertexAttributePointer(GLenum shaderDataType, break; default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + qCWarning(Rendering) << "vertexAttribPointer: Unhandled type"; Q_UNREACHABLE(); } } @@ -387,7 +389,7 @@ void GraphicsHelperES2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, void GraphicsHelperES2::alphaTest(GLenum, GLenum) { - qCWarning(Render::Rendering) << Q_FUNC_INFO << "AlphaTest not available with OpenGL ES 2.0"; + qCWarning(Rendering) << Q_FUNC_INFO << "AlphaTest not available with OpenGL ES 2.0"; } void GraphicsHelperES2::depthTest(GLenum mode) @@ -1028,6 +1030,7 @@ void GraphicsHelperES2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, G m_ext->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h index 902bd5fb2..9f820c72b 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES2_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES2_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES2_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES2_H // // W A R N I N G @@ -61,6 +61,7 @@ class QOpenGLExtensions; namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsHelperES2 : public GraphicsHelperInterface { @@ -174,9 +175,10 @@ protected: QScopedPointer m_ext; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES2_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES2_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp index 6e299199f..97a256b9c 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp @@ -41,7 +41,7 @@ #include "graphicshelperes3_p.h" #include #include -#include +#include #include QT_BEGIN_NAMESPACE @@ -169,6 +169,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { GraphicsHelperES3::GraphicsHelperES3() { @@ -249,7 +250,7 @@ void GraphicsHelperES3::vertexAttributePointer(GLenum shaderDataType, break; default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + qCWarning(Rendering) << "vertexAttribPointer: Unhandled type"; Q_UNREACHABLE(); } } @@ -733,7 +734,7 @@ QVector GraphicsHelperES3::programUniformsAndLocations(GLuint pro m_extraFuncs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); uniform.m_rawByteSize = uniformByteSize(uniform); uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size + qCDebug(Rendering) << uniform.m_name << "size" << uniform.m_size << " offset" << uniform.m_offset << " rawSize" << uniform.m_rawByteSize; } @@ -762,6 +763,7 @@ QVector GraphicsHelperES3::programUniformBlocks(GLuint progr return blocks; } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp index dc042b0c6..692e0880b 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp @@ -150,6 +150,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { @@ -361,6 +362,7 @@ void GraphicsHelperES3_1::buildUniformBuffer(const QVariant &v, const ShaderUnif } } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h index 7eab61c60..408db0766 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h @@ -57,6 +57,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsHelperES3_1 : public GraphicsHelperES3 { @@ -79,6 +80,7 @@ public: void buildUniformBuffer(const QVariant &v, const ShaderUniform &description, QByteArray &buffer) override; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp index 9d0988410..65108800b 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp @@ -77,6 +77,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { GraphicsHelperES3_2::GraphicsHelperES3_2() { @@ -187,6 +188,7 @@ uint GraphicsHelperES3_2::uniformByteSize(const ShaderUniform &description) return rawByteSize; } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h index 9552e656a..7a70f6269 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES3_2_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES3_2_H // // W A R N I N G @@ -57,6 +57,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsHelperES3_2 : public GraphicsHelperES3_1 { @@ -76,9 +77,10 @@ public: }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_2_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES3_2_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h index c985ba24a..5c34a8abb 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERES3_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERES3_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES3_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES3_H // // W A R N I N G @@ -58,6 +58,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsHelperES3 : public GraphicsHelperES2 { @@ -100,9 +101,10 @@ protected: QOpenGLExtraFunctions *m_extraFuncs = nullptr; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERES3_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERES3_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp index 3afc29d2f..6989be743 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp @@ -43,12 +43,13 @@ #include #include #include -#include +#include QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { GraphicsHelperGL2::GraphicsHelperGL2() : m_funcs(nullptr) @@ -257,7 +258,7 @@ void GraphicsHelperGL2::vertexAttributePointer(GLenum shaderDataType, break; default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + qCWarning(Rendering) << "vertexAttribPointer: Unhandled type"; Q_UNREACHABLE(); } } @@ -927,6 +928,7 @@ void GraphicsHelperGL2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, G qWarning() << "Framebuffer blits are not supported by ES 2.0 (since ES 3.1)"; } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h index 35391471f..7eac312b8 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL2_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL2_H // // W A R N I N G @@ -62,6 +62,7 @@ class QOpenGLExtension_ARB_framebuffer_object; namespace Qt3DRender { namespace Render { +namespace OpenGL { class Q_AUTOTEST_EXPORT GraphicsHelperGL2 : public GraphicsHelperInterface { @@ -173,6 +174,7 @@ private: QOpenGLExtension_ARB_framebuffer_object *m_fboFuncs; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender @@ -180,4 +182,4 @@ QT_END_NAMESPACE #endif // !QT_OPENGL_ES_2 -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL2_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL2_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp index 17850cf00..cb0a62224 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp @@ -43,8 +43,8 @@ #include #include #include -#include #include +#include #include QT_BEGIN_NAMESPACE @@ -70,6 +70,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { GraphicsHelperGL3_2::GraphicsHelperGL3_2() : m_funcs(nullptr) @@ -216,9 +217,9 @@ QVector GraphicsHelperGL3_2::programUniformsAndLocations(GLuint p m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); uniform.m_rawByteSize = uniformByteSize(uniform); uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; + qCDebug(Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; } return uniforms; @@ -279,7 +280,7 @@ void GraphicsHelperGL3_2::vertexAttribDivisor(GLuint index, GLuint divisor) { Q_UNUSED(index); Q_UNUSED(divisor); - qCWarning(Render::Rendering) << "Vertex attribute divisor not available with OpenGL 3.2 core"; + qCWarning(Rendering) << "Vertex attribute divisor not available with OpenGL 3.2 core"; } void GraphicsHelperGL3_2::vertexAttributePointer(GLenum shaderDataType, @@ -319,7 +320,7 @@ void GraphicsHelperGL3_2::vertexAttributePointer(GLenum shaderDataType, break; default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + qCWarning(Rendering) << "vertexAttribPointer: Unhandled type"; Q_UNREACHABLE(); } } @@ -397,7 +398,7 @@ void GraphicsHelperGL3_2::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRG void GraphicsHelperGL3_2::alphaTest(GLenum, GLenum) { - qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; + qCWarning(Rendering) << "AlphaTest not available with OpenGL 3.2 core"; } void GraphicsHelperGL3_2::depthTest(GLenum mode) @@ -1237,6 +1238,7 @@ void GraphicsHelperGL3_2::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h index b6b2f7141..a7396dc87 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL3_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL3_H // // W A R N I N G @@ -63,6 +63,7 @@ class QOpenGLExtension_ARB_tessellation_shader; namespace Qt3DRender { namespace Render { +namespace OpenGL { class Q_AUTOTEST_EXPORT GraphicsHelperGL3_2 : public GraphicsHelperInterface { @@ -175,6 +176,7 @@ private: QScopedPointer m_tessFuncs; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender @@ -182,4 +184,4 @@ QT_END_NAMESPACE #endif // !QT_OPENGL_ES_2 -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL3_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL3_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp index 3d8e2acfc..f5a61aa4b 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp @@ -42,8 +42,8 @@ #ifndef QT_OPENGL_ES_2 #include #include -#include #include +#include #include # ifndef QT_OPENGL_3_2 @@ -69,6 +69,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { GraphicsHelperGL3_3::GraphicsHelperGL3_3() : m_funcs(nullptr) @@ -215,9 +216,9 @@ QVector GraphicsHelperGL3_3::programUniformsAndLocations(GLuint p m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); uniform.m_rawByteSize = uniformByteSize(uniform); uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; + qCDebug(Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; } return uniforms; @@ -316,7 +317,7 @@ void GraphicsHelperGL3_3::vertexAttributePointer(GLenum shaderDataType, break; default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + qCWarning(Rendering) << "vertexAttribPointer: Unhandled type"; } } @@ -393,7 +394,7 @@ void GraphicsHelperGL3_3::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRG void GraphicsHelperGL3_3::alphaTest(GLenum, GLenum) { - qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; + qCWarning(Rendering) << "AlphaTest not available with OpenGL 3.2 core"; } void GraphicsHelperGL3_3::depthTest(GLenum mode) @@ -1232,6 +1233,7 @@ void GraphicsHelperGL3_3::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h index 8d8525111..3b667420c 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL3_3_P_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL3_3_P_H // // W A R N I N G @@ -63,6 +63,7 @@ class QOpenGLExtension_ARB_tessellation_shader; namespace Qt3DRender { namespace Render { +namespace OpenGL { class Q_AUTOTEST_EXPORT GraphicsHelperGL3_3 : public GraphicsHelperInterface { @@ -175,6 +176,7 @@ private: QScopedPointer m_tessFuncs; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender @@ -182,4 +184,4 @@ QT_END_NAMESPACE #endif // !QT_OPENGL_ES_2 -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL3_3_P_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL3_3_P_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp index 775dd7935..96e055870 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp @@ -42,9 +42,9 @@ #ifndef QT_OPENGL_ES_2 #include #include -#include #include #include +#include # ifndef QT_OPENGL_4_3 # ifndef GL_PATCH_VERTICES @@ -118,6 +118,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { @@ -291,9 +292,9 @@ QVector GraphicsHelperGL4::programUniformsAndLocations(GLuint pro m_funcs->glGetActiveUniformsiv(programId, 1, (GLuint*)&i, GL_UNIFORM_MATRIX_STRIDE, &uniform.m_matrixStride); uniform.m_rawByteSize = uniformByteSize(uniform); uniforms.append(uniform); - qCDebug(Render::Rendering) << uniform.m_name << "size" << uniform.m_size - << " offset" << uniform.m_offset - << " rawSize" << uniform.m_rawByteSize; + qCDebug(Rendering) << uniform.m_name << "size" << uniform.m_size + << " offset" << uniform.m_offset + << " rawSize" << uniform.m_rawByteSize; } return uniforms; @@ -418,7 +419,7 @@ void GraphicsHelperGL4::vertexAttributePointer(GLenum shaderDataType, break; default: - qCWarning(Render::Rendering) << "vertexAttribPointer: Unhandled type"; + qCWarning(Rendering) << "vertexAttribPointer: Unhandled type"; Q_UNREACHABLE(); } } @@ -728,7 +729,7 @@ void GraphicsHelperGL4::blendFuncSeparatei(GLuint buf, GLenum sRGB, GLenum dRGB, void GraphicsHelperGL4::alphaTest(GLenum, GLenum) { - qCWarning(Render::Rendering) << "AlphaTest not available with OpenGL 3.2 core"; + qCWarning(Rendering) << "AlphaTest not available with OpenGL 3.2 core"; } void GraphicsHelperGL4::depthTest(GLenum mode) @@ -1434,6 +1435,7 @@ void GraphicsHelperGL4::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, G m_funcs->glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h index 02cb7e211..1fa390806 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL4_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL4_H // // W A R N I N G @@ -62,6 +62,7 @@ class QOpenGLFunctions_4_3_Core; namespace Qt3DRender { namespace Render { +namespace OpenGL { class Q_AUTOTEST_EXPORT GraphicsHelperGL4 : public GraphicsHelperInterface { @@ -172,6 +173,7 @@ private: QOpenGLFunctions_4_3_Core *m_funcs; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender @@ -179,4 +181,4 @@ QT_END_NAMESPACE #endif // !QT_OPENGL_ES_2 -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERGL4_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERGL4_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h index aa2b65c66..bbbf05ee0 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H -#define QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H +#ifndef QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERINTERFACE_H +#define QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERINTERFACE_H // // W A R N I N G @@ -64,6 +64,9 @@ namespace Qt3DRender { namespace Render { struct Attachment; + +namespace OpenGL { + class RenderBuffer; class GraphicsHelperInterface @@ -194,10 +197,10 @@ public: virtual UniformType uniformTypeFromGLType(GLenum glType) = 0; }; - +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GRAPHICSHELPERINTERFACE_H +#endif // QT3DRENDER_RENDER_OPENGL_GRAPHICSHELPERINTERFACE_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp index cd2b33fb4..c2316d81a 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp @@ -42,6 +42,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -58,6 +59,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsContext; class GLTexture; @@ -299,7 +301,7 @@ int ImageSubmissionContext::assignUnitForImage(Qt3DCore::QNodeId shaderImageId) return lowestScoredUnit; } - +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h index 6d39f469b..52a0152f8 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H -#define QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_IMAGESUBMISSIONCONTEXT_P_H +#define QT3DRENDER_RENDER_OPENGL_IMAGESUBMISSIONCONTEXT_P_H // // W A R N I N G @@ -58,9 +58,12 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +class ShaderImage; + +namespace OpenGL { + class GraphicsContext; class GLTexture; -class ShaderImage; class Q_AUTOTEST_EXPORT ImageSubmissionContext { @@ -87,9 +90,10 @@ private: GraphicsContext *m_ctx; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_IMAGESUBMISSIONCONTEXT_P_H +#endif // QT3DRENDER_RENDER_OPENGL_IMAGESUBMISSIONCONTEXT_P_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h b/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h index efc952ea5..a2a995811 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H -#define QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_QGRAPHICSUTILS_P_H +#define QT3DRENDER_RENDER_OPENGL_QGRAPHICSUTILS_P_H // // W A R N I N G @@ -67,6 +67,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + namespace { const int QMatrix2x2Type = qMetaTypeId(); @@ -401,10 +403,12 @@ public: }; +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_QGRAPHICSUTILS_P_H +#endif // QT3DRENDER_RENDER_OPENGL_QGRAPHICSUTILS_P_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp index 9501b0b52..e4b223185 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp @@ -97,6 +97,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { static QHash static_contexts; @@ -1407,7 +1408,7 @@ HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer) // b.setUsagePattern(static_cast(buffer->usage())); Q_ASSERT(b); if (!b->create(this)) - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer creation failed"; + qCWarning(Io) << Q_FUNC_INFO << "buffer creation failed"; return m_renderer->glResourceManagers()->glBufferManager()->lookupHandle(buffer->peerId()); } @@ -1428,7 +1429,7 @@ bool SubmissionContext::bindGLBuffer(GLBuffer *buffer, GLBuffer::Type type) void SubmissionContext::uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool releaseBuffer) { if (!bindGLBuffer(b, GLBuffer::ArrayBuffer)) // We're uploading, the type doesn't matter here - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer bind failed"; + qCWarning(Io) << Q_FUNC_INFO << "buffer bind failed"; // If the buffer is dirty (hence being called here) // there are two possible cases // * setData was called changing the whole data or functor (or the usage pattern) @@ -1471,13 +1472,13 @@ void SubmissionContext::uploadDataToGLBuffer(Buffer *buffer, GLBuffer *b, bool r b->release(this); m_boundArrayBuffer = nullptr; } - qCDebug(Render::Io) << "uploaded buffer size=" << buffer->data().size(); + qCDebug(Io) << "uploaded buffer size=" << buffer->data().size(); } QByteArray SubmissionContext::downloadDataFromGLBuffer(Buffer *buffer, GLBuffer *b) { if (!bindGLBuffer(b, GLBuffer::ArrayBuffer)) // We're downloading, the type doesn't matter here - qCWarning(Render::Io) << Q_FUNC_INFO << "buffer bind failed"; + qCWarning(Io) << Q_FUNC_INFO << "buffer bind failed"; QByteArray data = b->download(this, buffer->data().size()); return data; @@ -1568,6 +1569,7 @@ void SubmissionContext::blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId, } } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender of namespace diff --git a/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h index 16eca07ea..b663e47ec 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H -#define QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H +#ifndef QT3DRENDER_RENDER_OPENGL_SUBMISSIONCONTEXT_H +#define QT3DRENDER_RENDER_OPENGL_SUBMISSIONCONTEXT_H // // W A R N I N G @@ -70,18 +70,21 @@ namespace Qt3DRender { namespace Render { -class Renderer; -class GraphicsHelperInterface; -class RenderStateSet; class Material; -class GLTexture; -class RenderCommand; -class RenderTarget; class AttachmentPack; class Attribute; class Buffer; class ShaderManager; struct StateVariant; +class RenderTarget; +class RenderStateSet; + +namespace OpenGL { + +class Renderer; +class GraphicsHelperInterface; +class GLTexture; +class RenderCommand; typedef QPair NamedUniformLocation; @@ -226,9 +229,10 @@ private: void disableAttribute(const VAOVertexAttribute &attr); }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_SUBMISSIONCONTEXT_H +#endif // QT3DRENDER_RENDER_OPENGL_SUBMISSIONCONTEXT_H diff --git a/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp index 4f2ff80f5..4577d3d10 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp +++ b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp @@ -41,11 +41,13 @@ #include #include +#include QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { class TextureExtRendererLocker { @@ -219,6 +221,7 @@ void TextureSubmissionContext::decayTextureScores() m_activeTextures[u].score = qMax(m_activeTextures[u].score - 1, 0); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender of namespace diff --git a/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h index 3c84fe558..d80f6b9e3 100644 --- a/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h +++ b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_TEXTURESUBMISSIONCONTEXT_H -#define QT3DRENDER_RENDER_TEXTURESUBMISSIONCONTEXT_H +#ifndef QT3DRENDER_RENDER_OPENGL_TEXTURESUBMISSIONCONTEXT_H +#define QT3DRENDER_RENDER_OPENGL_TEXTURESUBMISSIONCONTEXT_H // // W A R N I N G @@ -61,6 +61,7 @@ class QOpenGLContext; namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsContext; class GLTexture; @@ -98,9 +99,10 @@ private: QVector m_activeTextures; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_TEXTURESUBMISSIONCONTEXT_H +#endif // QT3DRENDER_RENDER_OPENGL_TEXTURESUBMISSIONCONTEXT_H diff --git a/src/plugins/renderers/opengl/io/glbuffer.cpp b/src/plugins/renderers/opengl/io/glbuffer.cpp index 53fc50cb9..27f005f01 100644 --- a/src/plugins/renderers/opengl/io/glbuffer.cpp +++ b/src/plugins/renderers/opengl/io/glbuffer.cpp @@ -68,6 +68,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + // A UBO is created for each ShaderData Shader Pair // That means a UBO is unique to a shader/shaderdata @@ -162,6 +164,8 @@ void GLBuffer::bindBufferBase(GraphicsContext *ctx, int bindingPoint) ctx->bindBufferBase(m_lastTarget, bindingPoint, m_bufferId); } +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/io/glbuffer_p.h b/src/plugins/renderers/opengl/io/glbuffer_p.h index 731634b6b..6a2daa287 100644 --- a/src/plugins/renderers/opengl/io/glbuffer_p.h +++ b/src/plugins/renderers/opengl/io/glbuffer_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GLBUFFER_P_H -#define QT3DRENDER_RENDER_GLBUFFER_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_GLBUFFER_P_H +#define QT3DRENDER_RENDER_OPENGL_GLBUFFER_P_H // // W A R N I N G @@ -61,6 +61,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class GraphicsContext; class GLBuffer @@ -101,10 +103,12 @@ private: GLenum m_lastTarget; }; +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GLBUFFER_P_H +#endif // QT3DRENDER_RENDER_OPENGL_GLBUFFER_P_H diff --git a/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp index 95e8862ef..52fd99f52 100644 --- a/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp +++ b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp @@ -48,6 +48,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { FilterCompatibleTechniqueJob::FilterCompatibleTechniqueJob() : m_manager(nullptr) @@ -89,6 +90,7 @@ void FilterCompatibleTechniqueJob::run() } } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h index 9037baa46..7191e2933 100644 --- a/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h +++ b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H -#define QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H +#ifndef QT3DRENDER_RENDER_OPENGL_FILTERCOMPATIBLETECHNIQUEJOB_H +#define QT3DRENDER_RENDER_OPENGL_FILTERCOMPATIBLETECHNIQUEJOB_H // // W A R N I N G @@ -62,6 +62,9 @@ namespace Qt3DRender { namespace Render { class TechniqueManager; + +namespace OpenGL { + class Renderer; class Q_AUTOTEST_EXPORT FilterCompatibleTechniqueJob : public Qt3DCore::QAspectJob @@ -84,9 +87,10 @@ private: typedef QSharedPointer FilterCompatibleTechniqueJobPtr; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_FILTERCOMPATIBLETECHNIQUEJOB_H +#endif // QT3DRENDER_RENDER_OPENGL_FILTERCOMPATIBLETECHNIQUEJOB_H diff --git a/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp b/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp index e1f8aa403..1f51ceba3 100644 --- a/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp +++ b/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp @@ -50,6 +50,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + namespace { int materialParameterGathererCounter = 0; @@ -124,6 +126,8 @@ void MaterialParameterGathererJob::run() } } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h b/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h index 5975261af..139267d9a 100644 --- a/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h +++ b/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H -#define QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_MATERIALPARAMETERGATHERERJOB_P_H +#define QT3DRENDER_RENDER_OPENGL_MATERIALPARAMETERGATHERERJOB_P_H // // W A R N I N G @@ -66,6 +66,8 @@ namespace Render { class NodeManagers; class TechniqueFilter; class RenderPassFilter; + +namespace OpenGL { class Renderer; // TO be executed for each FrameGraph branch with a given RenderPassFilter/TechniqueFilter @@ -98,10 +100,12 @@ private: typedef QSharedPointer MaterialParameterGathererJobPtr; +} // OpenGL + } // Render } // Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H +#endif // QT3DRENDER_RENDER_OPENGL_MATERIALPARAMETERGATHERERJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp index 5bfa9ed6f..468ab9342 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp +++ b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp @@ -48,6 +48,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + namespace { int renderViewInstanceCounter = 0; } // anonymous @@ -75,6 +77,8 @@ void RenderViewCommandUpdaterJob::run() } } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h index 6a171d281..13e19daf7 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h +++ b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H -#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H // // W A R N I N G @@ -61,6 +61,10 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + +class RenderView; + class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob { public: @@ -87,10 +91,12 @@ private: typedef QSharedPointer RenderViewCommandBuilderJobPtr; +} // OpenGL + } // Render } // Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp index 00cfba558..d8a33b693 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp @@ -47,6 +47,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + namespace { int renderViewInstanceCounter = 0; } // anonymous @@ -74,6 +76,8 @@ void RenderViewCommandBuilderJob::run() } } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h index 6a171d281..e9f8bb10a 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H -#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H // // W A R N I N G @@ -61,6 +61,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob { public: @@ -87,10 +89,12 @@ private: typedef QSharedPointer RenderViewCommandBuilderJobPtr; +} // OpenGL + } // Render } // Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDBUILDERJOB_P_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp index 1b7cae229..79a115525 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp @@ -48,10 +48,13 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + namespace { int renderViewInstanceCounter = 0; } // anonymous + RenderViewCommandUpdaterJob::RenderViewCommandUpdaterJob() : Qt3DCore::QAspectJob() , m_offset(0) @@ -75,6 +78,8 @@ void RenderViewCommandUpdaterJob::run() } } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h index 88961d848..2fe5749ad 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h +++ b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H -#define QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDUPDATEJOB_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDUPDATEJOB_P_H // // W A R N I N G @@ -61,6 +61,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class RenderView; class Renderer; @@ -94,10 +96,12 @@ private: typedef QSharedPointer RenderViewCommandUpdaterJobPtr; +} // OpenGL + } // Render } // Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERVIEWCOMMANDUPDATEJOB_P_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDUPDATEJOB_P_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp index c1b97959f..6be1016f0 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp +++ b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp @@ -52,6 +52,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { // only accessed in ctor and dtor of RenderViewJob @@ -98,6 +99,7 @@ void RenderViewInitializerJob::run() #endif } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h index fb4e2c67c..2ebb5dc36 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h +++ b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H -#define QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWINITIALIZERJOB_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWINITIALIZERJOB_H // // W A R N I N G @@ -62,8 +62,11 @@ namespace Qt3DRender { namespace Render { -class Renderer; class FrameGraphNode; + +namespace OpenGL { + +class Renderer; class RenderView; class Q_AUTOTEST_EXPORT RenderViewInitializerJob : public Qt3DCore::QAspectJob @@ -99,9 +102,10 @@ private: typedef QSharedPointer RenderViewInitializerJobPtr; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERVIEWINITIALIZERJOB_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWINITIALIZERJOB_H diff --git a/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp b/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp index f869c5532..d4835054b 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp +++ b/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp @@ -76,6 +76,7 @@ using namespace Qt3DCore; namespace Qt3DRender { namespace Render { +namespace OpenGL { /*! \internal @@ -568,6 +569,7 @@ bool ParameterInfo::operator<(const int otherNameId) const Q_DECL_NOEXCEPT return nameId < otherNameId; } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h b/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h index a8bbd01b4..5b1413108 100644 --- a/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h +++ b/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDERVIEWJOBUTILS_P_H -#define QT3DRENDER_RENDERVIEWJOBUTILS_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWJOBUTILS_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWJOBUTILS_P_H // // W A R N I N G @@ -76,19 +76,21 @@ class Effect; class Entity; class Material; class RenderPass; -class RenderStateSet; class Technique; -class RenderView; class TechniqueFilter; class RenderPassFilter; -class Renderer; class NodeManagers; class ShaderDataManager; -struct ShaderUniform; class ShaderData; class TextureManager; class RenderStateManager; class RenderStateCollection; +class RenderStateSet; + +namespace OpenGL { +class Renderer; +class RenderView; +struct ShaderUniform; Q_AUTOTEST_EXPORT void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, const FrameGraphNode *fgLeaf); @@ -127,7 +129,7 @@ struct RenderPassParameterData RenderPass *pass; ParameterInfoList parameterInfo; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, RenderPassParameterData, Q_MOVABLE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, RenderPassParameterData, Q_MOVABLE_TYPE) using MaterialParameterGathererData = QHash>; @@ -180,9 +182,10 @@ struct Q_AUTOTEST_EXPORT UniformBlockValueBuilder Matrix4x4 viewMatrix; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDERVIEWJOBUTILS_P_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWJOBUTILS_P_H diff --git a/src/plugins/renderers/opengl/main.cpp b/src/plugins/renderers/opengl/main.cpp index 61e796788..a6cd9faf7 100644 --- a/src/plugins/renderers/opengl/main.cpp +++ b/src/plugins/renderers/opengl/main.cpp @@ -50,7 +50,7 @@ class OpenGLRendererPlugin : public Qt3DRender::Render::QRendererPlugin Qt3DRender::Render::AbstractRenderer *create(const QString &key, Qt3DRender::QRenderAspect::RenderType renderMode) override { Q_UNUSED(key) - return new Qt3DRender::Render::Renderer(renderMode); + return new Qt3DRender::Render::OpenGL::Renderer(renderMode); } }; diff --git a/src/plugins/renderers/opengl/managers/gl_handle_types_p.h b/src/plugins/renderers/opengl/managers/gl_handle_types_p.h index eb25bab7f..98af4d3b8 100644 --- a/src/plugins/renderers/opengl/managers/gl_handle_types_p.h +++ b/src/plugins/renderers/opengl/managers/gl_handle_types_p.h @@ -59,6 +59,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class GLBuffer; class GLTexture; class OpenGLVertexArrayObject; @@ -67,6 +69,8 @@ typedef Qt3DCore::QHandle HGLBuffer; typedef Qt3DCore::QHandle HVao; typedef Qt3DCore::QHandle HGLTexture; +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp b/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp index 67a7422aa..e8fd893ee 100644 --- a/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp +++ b/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp @@ -45,6 +45,7 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { GLResourceManagers::GLResourceManagers() : m_glBufferManager(new GLBufferManager()) @@ -64,6 +65,8 @@ GLResourceManagers::~GLResourceManagers() delete m_glBufferManager; } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h b/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h index 3597e6965..9472bc33f 100644 --- a/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h +++ b/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H -#define QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_GLRESOURCEMANAGERS_P_H +#define QT3DRENDER_RENDER_OPENGL_GLRESOURCEMANAGERS_P_H // // W A R N I N G @@ -66,6 +66,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class Q_AUTOTEST_EXPORT GLFenceManager : public QHash { }; @@ -124,12 +126,14 @@ private: VAOManager *m_vaoManager; }; +} // OpenGL + } // Render } // Qt3DRender -Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP) +Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGL::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP) QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GLRESOURCEMANAGERS_P_H +#endif // QT3DRENDER_RENDER_OPENGL_GLRESOURCEMANAGERS_P_H diff --git a/src/plugins/renderers/opengl/renderer/commandexecuter.cpp b/src/plugins/renderers/opengl/renderer/commandexecuter.cpp index 6498b44b8..03d5d5a7f 100644 --- a/src/plugins/renderers/opengl/renderer/commandexecuter.cpp +++ b/src/plugins/renderers/opengl/renderer/commandexecuter.cpp @@ -242,11 +242,11 @@ QJsonObject backendNodeToJSon(Handle handle, Manager *manager) return obj; } -QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) +QJsonObject parameterPackToJson(const Render::OpenGL::ShaderParameterPack &pack) { QJsonObject obj; - const Render::PackUniformHash &uniforms = pack.uniforms(); + const Render::OpenGL::PackUniformHash &uniforms = pack.uniforms(); QJsonArray uniformsArray; for (int i = 0, m = uniforms.keys.size(); i < m; ++i) { QJsonObject uniformObj; @@ -261,7 +261,7 @@ QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) obj.insert(QLatin1String("uniforms"), uniformsArray); QJsonArray texturesArray; - const QVector &textures = pack.textures(); + const QVector &textures = pack.textures(); for (const auto & texture : textures) { QJsonObject textureObj; textureObj.insert(QLatin1String("name"), Render::StringToInt::lookupString(texture.glslNameId)); @@ -270,7 +270,7 @@ QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) } obj.insert(QLatin1String("textures"), texturesArray); - const QVector &ubos = pack.uniformBuffers(); + const QVector &ubos = pack.uniformBuffers(); QJsonArray ubosArray; for (const auto &ubo : ubos) { QJsonObject uboObj; @@ -281,7 +281,7 @@ QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) } obj.insert(QLatin1String("ubos"), ubosArray); - const QVector &ssbos = pack.shaderStorageBuffers(); + const QVector &ssbos = pack.shaderStorageBuffers(); QJsonArray ssbosArray; for (const auto &ssbo : ssbos) { QJsonObject ssboObj; @@ -296,13 +296,13 @@ QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack) } // anonymous -CommandExecuter::CommandExecuter(Render::Renderer *renderer) +CommandExecuter::CommandExecuter(Render::OpenGL::Renderer *renderer) : m_renderer(renderer) { } // Render thread -void CommandExecuter::performAsynchronousCommandExecution(const QVector &views) +void CommandExecuter::performAsynchronousCommandExecution(const QVector &views) { QMutexLocker lock(&m_pendingCommandsMutex); const QVector shellCommands = std::move(m_pendingCommands); @@ -334,7 +334,7 @@ void CommandExecuter::performAsynchronousCommandExecution(const QVectorviewport())); viewObj.insert(QLatin1String("surfaceSize"), typeToJsonValue(v->surfaceSize())); @@ -346,7 +346,7 @@ void CommandExecuter::performAsynchronousCommandExecution(const QVectorclearStencilValue()); QJsonArray renderCommandsArray; - for (const Render::RenderCommand &c : v->commands()) { + for (Render::OpenGL::RenderCommand &c : v->commands()) { QJsonObject commandObj; Render::NodeManagers *nodeManagers = m_renderer->nodeManagers(); commandObj.insert(QLatin1String("shader"), typeToJsonValue(QVariant::fromValue(c.m_shaderId))); diff --git a/src/plugins/renderers/opengl/renderer/commandexecuter_p.h b/src/plugins/renderers/opengl/renderer/commandexecuter_p.h index 2d90bf4d6..9aea9fc2f 100644 --- a/src/plugins/renderers/opengl/renderer/commandexecuter_p.h +++ b/src/plugins/renderers/opengl/renderer/commandexecuter_p.h @@ -65,8 +65,10 @@ class AsynchronousCommandReply; namespace Qt3DRender { namespace Render { +namespace OpenGL { class Renderer; class RenderView; +} // OpenGL } // Render namespace Debug { @@ -74,14 +76,14 @@ namespace Debug { class CommandExecuter { public: - explicit CommandExecuter(Render::Renderer *renderer); + explicit CommandExecuter(Render::OpenGL::Renderer *renderer); - void performAsynchronousCommandExecution(const QVector &views); + void performAsynchronousCommandExecution(const QVector &views); QVariant executeCommand(const QStringList &args); private: - Render::Renderer *m_renderer; + Render::OpenGL::Renderer *m_renderer; QVector m_pendingCommands; QMutex m_pendingCommandsMutex; }; diff --git a/src/plugins/renderers/opengl/renderer/glshader.cpp b/src/plugins/renderers/opengl/renderer/glshader.cpp index 02fa2de6d..5e92d84c2 100644 --- a/src/plugins/renderers/opengl/renderer/glshader.cpp +++ b/src/plugins/renderers/opengl/renderer/glshader.cpp @@ -41,6 +41,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -48,6 +49,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + GLShader::GLShader() : m_isLoaded(false) , m_graphicsContext(nullptr) @@ -309,6 +312,8 @@ void GLShader::initializeShaderStorageBlocks(const QVector & } } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/glshader_p.h b/src/plugins/renderers/opengl/renderer/glshader_p.h index 18293ac54..6bd5400af 100644 --- a/src/plugins/renderers/opengl/renderer/glshader_p.h +++ b/src/plugins/renderers/opengl/renderer/glshader_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GLSHADER_P_H -#define QT3DRENDER_RENDER_GLSHADER_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_GLSHADER_P_H +#define QT3DRENDER_RENDER_OPENGL_GLSHADER_P_H // // W A R N I N G @@ -66,6 +66,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class Q_AUTOTEST_EXPORT GLShader { public: @@ -151,10 +153,12 @@ private: QMetaObject::Connection m_contextConnection; }; +} // OpenGL + } // Render } // Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GLSHADER_P_H +#endif // QT3DRENDER_RENDER_OPENGL_GLSHADER_P_H diff --git a/src/plugins/renderers/opengl/renderer/logging.cpp b/src/plugins/renderers/opengl/renderer/logging.cpp index ab7437eba..0d6ef1211 100644 --- a/src/plugins/renderers/opengl/renderer/logging.cpp +++ b/src/plugins/renderers/opengl/renderer/logging.cpp @@ -45,6 +45,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + Q_LOGGING_CATEGORY(Backend, "Qt3D.Renderer.OpenGL.Backend", QtWarningMsg) Q_LOGGING_CATEGORY(Frontend, "Qt3D.Renderer.OpenGL.Frontend", QtWarningMsg) Q_LOGGING_CATEGORY(Io, "Qt3D.Renderer.OpenGL.IO", QtWarningMsg) @@ -58,6 +60,8 @@ Q_LOGGING_CATEGORY(Shaders, "Qt3D.Renderer.OpenGL.Shaders", QtWarningMsg) Q_LOGGING_CATEGORY(RenderStates, "Qt3D.Renderer.OpenGL.RenderStates", QtWarningMsg) Q_LOGGING_CATEGORY(VSyncAdvanceService, "Qt3D.Renderer.OpenGL.VsyncAdvanceService", QtWarningMsg) +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/logging_p.h b/src/plugins/renderers/opengl/renderer/logging_p.h index 8a550e22f..69c125195 100644 --- a/src/plugins/renderers/opengl/renderer/logging_p.h +++ b/src/plugins/renderers/opengl/renderer/logging_p.h @@ -59,6 +59,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + Q_DECLARE_LOGGING_CATEGORY(Backend) Q_DECLARE_LOGGING_CATEGORY(Frontend) Q_DECLARE_LOGGING_CATEGORY(Io) @@ -72,6 +74,8 @@ Q_DECLARE_LOGGING_CATEGORY(Shaders) Q_DECLARE_LOGGING_CATEGORY(RenderStates) Q_DECLARE_LOGGING_CATEGORY(VSyncAdvanceService) +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp index 19ae4fa55..b43815f98 100644 --- a/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp +++ b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp @@ -47,6 +47,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { OpenGLVertexArrayObject::OpenGLVertexArrayObject() : m_ctx(nullptr) @@ -159,6 +160,7 @@ void OpenGLVertexArrayObject::saveVertexAttribute(const SubmissionContext::VAOVe } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h index 99cf51ee8..ff58b3074 100644 --- a/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h +++ b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef OPENGLVERTEXARRAYOBJECT_H -#define OPENGLVERTEXARRAYOBJECT_H +#ifndef QT3DRENDER_RENDER_OPENGL_OPENGLVERTEXARRAYOBJECT_H +#define QT3DRENDER_RENDER_OPENGL_OPENGLVERTEXARRAYOBJECT_H // // W A R N I N G @@ -60,11 +60,14 @@ namespace Qt3DRender { namespace Render { class GeometryManager; -class GLShaderManager; typedef QPair VAOIdentifier; -class Q_AUTOTEST_EXPORT OpenGLVertexArrayObject +namespace OpenGL { + +class GLShaderManager; + +class Q_AUTOTEST_EXPORT OpenGLVertexArrayObject { public: OpenGLVertexArrayObject(); @@ -103,9 +106,10 @@ private: SubmissionContext::VAOIndexAttribute m_indexAttribute; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // OPENGLVERTEXARRAYOBJECT_H +#endif // QT3DRENDER_RENDER_OPENGL_OPENGLVERTEXARRAYOBJECT_H diff --git a/src/plugins/renderers/opengl/renderer/rendercommand.cpp b/src/plugins/renderers/opengl/renderer/rendercommand.cpp index c6d42fde1..d4da1a41b 100644 --- a/src/plugins/renderers/opengl/renderer/rendercommand.cpp +++ b/src/plugins/renderers/opengl/renderer/rendercommand.cpp @@ -43,6 +43,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { RenderCommand::RenderCommand() : m_glShader(nullptr) @@ -85,6 +86,7 @@ bool operator==(const RenderCommand &a, const RenderCommand &b) noexcept a.m_isValid == b.m_isValid && a.m_computeCommand == b.m_computeCommand); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/rendercommand_p.h b/src/plugins/renderers/opengl/renderer/rendercommand_p.h index 600c52959..123ff232b 100644 --- a/src/plugins/renderers/opengl/renderer/rendercommand_p.h +++ b/src/plugins/renderers/opengl/renderer/rendercommand_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERCOMMAND_H -#define QT3DRENDER_RENDER_RENDERCOMMAND_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERCOMMAND_H +#define QT3DRENDER_RENDER_OPENGL_RENDERCOMMAND_H // // W A R N I N G @@ -72,6 +72,9 @@ namespace Render { class RenderStateSet; using RenderStateSetPtr = QSharedPointer; + +namespace OpenGL { + class GLShader; class Q_AUTOTEST_EXPORT RenderCommand @@ -172,6 +175,7 @@ struct EntityRenderCommandData using EntityRenderCommandDataPtr = QSharedPointer; +} // namespace OpenGL } // namespace Render @@ -179,4 +183,4 @@ using EntityRenderCommandDataPtr = QSharedPointer; QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERCOMMAND_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERCOMMAND_H diff --git a/src/plugins/renderers/opengl/renderer/renderer.cpp b/src/plugins/renderers/opengl/renderer/renderer.cpp index 2b9a34059..151483348 100644 --- a/src/plugins/renderers/opengl/renderer/renderer.cpp +++ b/src/plugins/renderers/opengl/renderer/renderer.cpp @@ -134,6 +134,7 @@ using namespace Qt3DCore; namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { @@ -209,7 +210,6 @@ private: } // anonymous - /*! \internal @@ -261,7 +261,7 @@ Renderer::Renderer(QRenderAspect::RenderType type) , m_updateSkinningPaletteJob(Render::UpdateSkinningPaletteJobPtr::create()) , m_updateLevelOfDetailJob(Render::UpdateLevelOfDetailJobPtr::create()) , m_updateMeshTriangleListJob(Render::UpdateMeshTriangleListJobPtr::create()) - , m_filterCompatibleTechniqueJob(Render::FilterCompatibleTechniqueJobPtr::create()) + , m_filterCompatibleTechniqueJob(FilterCompatibleTechniqueJobPtr::create()) , m_updateEntityLayersJob(Render::UpdateEntityLayersJobPtr::create()) , m_lightGathererJob(Render::LightGathererPtr::create()) , m_renderableEntityFilterJob(Render::RenderableEntityFilterPtr::create()) @@ -516,7 +516,8 @@ void Renderer::initialize() ctx->setFormat(sf); } - // Create OpenGL context + // Create OpenGL context<<<<<<< HEAD + if (ctx->create()) qCDebug(Backend) << "OpenGL context created with actual format" << ctx->format(); else @@ -794,18 +795,17 @@ void Renderer::doRender(bool swapBuffers) // RenderQueue is complete (but that means it may be of size 0) if (canSubmit && (queueIsComplete && !queueIsEmpty)) { - const QVector renderViews = m_renderQueue->nextFrameQueue(); + const QVector renderViews = m_renderQueue->nextFrameQueue(); QTaskLogger submissionStatsPart1(m_services->systemInformation(), {JobTypes::FrameSubmissionPart1, 0}, QTaskLogger::Submission); QTaskLogger submissionStatsPart2(m_services->systemInformation(), {JobTypes::FrameSubmissionPart2, 0}, QTaskLogger::Submission); - if (canRender()) { { // Scoped to destroy surfaceLock QSurface *surface = nullptr; - for (const Render::RenderView *rv: renderViews) { + for (const RenderView *rv: renderViews) { surface = rv->surface(); if (surface) break; @@ -902,7 +902,7 @@ void Renderer::doRender(bool swapBuffers) // Called by RenderViewJobs // When the frameQueue is complete and we are using a renderThread // we allow the render thread to proceed -void Renderer::enqueueRenderView(Render::RenderView *renderView, int submitOrder) +void Renderer::enqueueRenderView(RenderView *renderView, int submitOrder) { QMutexLocker locker(m_renderQueue->mutex()); // Prevent out of order execution // We cannot use a lock free primitive here because: @@ -1539,7 +1539,7 @@ void Renderer::downloadGLBuffers() // Happens in RenderThread context when all RenderViewJobs are done // Returns the id of the last bound FBO -Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector &renderViews) +Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector &renderViews) { QElapsedTimer timer; quint64 queueElapsed = 0; @@ -1555,7 +1555,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVectorboundFrameBufferObject(); QSurface *surface = nullptr; QSurface *previousSurface = nullptr; - for (const Render::RenderView *rv: renderViews) { + for (const RenderView *rv: renderViews) { previousSurface = rv->surface(); if (previousSurface) break; @@ -2453,6 +2453,7 @@ QVector Renderer::createRenderBufferJobs() const return dirtyBuffersJobs; } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/renderer_p.h b/src/plugins/renderers/opengl/renderer/renderer_p.h index bb05694fb..f24e77152 100644 --- a/src/plugins/renderers/opengl/renderer/renderer_p.h +++ b/src/plugins/renderers/opengl/renderer/renderer_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERER_H -#define QT3DRENDER_RENDER_RENDERER_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERER_H +#define QT3DRENDER_RENDER_OPENGL_RENDERER_H // // W A R N I N G @@ -139,15 +139,11 @@ class FrameProfiler; } class CameraLens; -class SubmissionContext; class FrameGraphNode; class Material; class Technique; class Shader; class Entity; -class RenderCommand; -class RenderQueue; -class RenderView; class Effect; class RenderPass; class RenderThread; @@ -155,16 +151,11 @@ class RenderStateSet; class VSyncFrameAdvanceService; class PickEventFilter; class NodeManagers; -class GLResourceManagers; -class GLShader; class ResourceAccessor; class UpdateLevelOfDetailJob; typedef QSharedPointer UpdateLevelOfDetailJobPtr; -using SynchronizerJobPtr = GenericLambdaJobPtr>; -using SynchronizerPostFramePtr = GenericLambdaJobAndPostFramePtr, std::function>; - template class FilterEntityByComponentJob; template @@ -172,10 +163,23 @@ using FilterEntityByComponentJobPtr = QSharedPointer; using RenderableEntityFilterPtr = FilterEntityByComponentJobPtr; +using SynchronizerJobPtr = GenericLambdaJobPtr>; +using SynchronizerPostFramePtr = GenericLambdaJobAndPostFramePtr, std::function>; + namespace Debug { class ImGuiRenderer; } +namespace OpenGL { + +class CommandThread; +class SubmissionContext; +class RenderCommand; +class RenderQueue; +class RenderView; +class GLShader; +class GLResourceManagers; + class Q_AUTOTEST_EXPORT Renderer : public AbstractRenderer { public: @@ -320,7 +324,7 @@ public: QSurface *surface; }; - ViewSubmissionResultData submitRenderViews(const QVector &renderViews); + ViewSubmissionResultData submitRenderViews(const QVector &renderViews); RendererCache *cache() { return &m_cache; } void setScreen(QScreen *scr) override; @@ -471,9 +475,10 @@ private: int m_jobsInLastFrame; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERER_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERER_H diff --git a/src/plugins/renderers/opengl/renderer/renderercache_p.h b/src/plugins/renderers/opengl/renderer/renderercache_p.h index 70a5ef43c..6b3946002 100644 --- a/src/plugins/renderers/opengl/renderer/renderercache_p.h +++ b/src/plugins/renderers/opengl/renderer/renderercache_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERERCACHE_P_H -#define QT3DRENDER_RENDER_RENDERERCACHE_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERERCACHE_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERERCACHE_P_H // // W A R N I N G @@ -64,6 +64,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + struct RendererCache { struct LeafNodeData @@ -88,10 +90,12 @@ private: QMutex m_mutex; }; +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERERCACHE_P_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERERCACHE_P_H diff --git a/src/plugins/renderers/opengl/renderer/renderqueue.cpp b/src/plugins/renderers/opengl/renderer/renderqueue.cpp index 9ba66952f..15b89da30 100644 --- a/src/plugins/renderers/opengl/renderer/renderqueue.cpp +++ b/src/plugins/renderers/opengl/renderer/renderqueue.cpp @@ -47,6 +47,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + RenderQueue::RenderQueue() : m_noRender(false) , m_wasReset(true) @@ -126,6 +128,8 @@ bool RenderQueue::isFrameQueueComplete() const || (m_targetRenderViewCount > 0 && m_targetRenderViewCount == m_currentRenderViewCount)); } +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/renderqueue_p.h b/src/plugins/renderers/opengl/renderer/renderqueue_p.h index e565115f2..0dcf7b8ee 100644 --- a/src/plugins/renderers/opengl/renderer/renderqueue_p.h +++ b/src/plugins/renderers/opengl/renderer/renderqueue_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERQUEUE_H -#define QT3DRENDER_RENDER_RENDERQUEUE_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERQUEUE_H +#define QT3DRENDER_RENDER_OPENGL_RENDERQUEUE_H // // W A R N I N G @@ -61,6 +61,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class RenderView; class Q_AUTOTEST_EXPORT RenderQueue @@ -93,10 +95,12 @@ private: QMutex m_mutex; }; +} // namespace OpenGL + } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERQUEUE_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERQUEUE_H diff --git a/src/plugins/renderers/opengl/renderer/renderview.cpp b/src/plugins/renderers/opengl/renderer/renderview.cpp index c6a6ddbbb..f18f1a06a 100644 --- a/src/plugins/renderers/opengl/renderer/renderview.cpp +++ b/src/plugins/renderers/opengl/renderer/renderview.cpp @@ -85,6 +85,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { @@ -1232,6 +1233,7 @@ void RenderView::setIsDownloadBuffersEnable(bool isDownloadBuffersEnable) m_isDownloadBuffersEnable = isDownloadBuffersEnable; } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/renderview_p.h b/src/plugins/renderers/opengl/renderer/renderview_p.h index 78c40d80c..a835c17f0 100644 --- a/src/plugins/renderers/opengl/renderer/renderview_p.h +++ b/src/plugins/renderers/opengl/renderer/renderview_p.h @@ -38,8 +38,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERVIEW_H -#define QT3DRENDER_RENDER_RENDERVIEW_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEW_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEW_H // // W A R N I N G @@ -86,15 +86,18 @@ class QRenderPass; namespace Render { -class Renderer; class NodeManagers; -class RenderCommand; class RenderPassFilter; class TechniqueFilter; class ViewportNode; class Effect; class RenderPass; +namespace OpenGL { + +class Renderer; +class RenderCommand; + typedef QPair ActivePropertyContent; typedef QPair ActiveProperty; @@ -389,9 +392,10 @@ private: const QString &structName) const; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERVIEW_H +#endif // QT3DRENDER_RENDER_OPENGL_ENDERVIEW_H diff --git a/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp b/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp index 4034af146..1e16209c6 100644 --- a/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp +++ b/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp @@ -46,6 +46,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { // In some cases having less jobs is better (especially on fast cpus where // splitting just adds more overhead). Ideally, we should try to set the value @@ -554,7 +555,7 @@ void RenderViewBuilder::prepareJobs() m_renderViewCommandBuilderJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto renderViewCommandBuilder = Render::RenderViewCommandBuilderJobPtr::create(); + auto renderViewCommandBuilder = Render::OpenGL::RenderViewCommandBuilderJobPtr::create(); m_renderViewCommandBuilderJobs.push_back(renderViewCommandBuilder); } m_syncRenderViewPreCommandBuildingJob = SynchronizerJobPtr::create(SyncPreCommandBuilding(m_renderViewJob, @@ -572,7 +573,7 @@ void RenderViewBuilder::prepareJobs() // Estimate the number of jobs to create based on the number of entities m_renderViewCommandUpdaterJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto renderViewCommandUpdater = Render::RenderViewCommandUpdaterJobPtr::create(); + auto renderViewCommandUpdater = Render::OpenGL::RenderViewCommandUpdaterJobPtr::create(); renderViewCommandUpdater->setRenderer(m_renderer); m_renderViewCommandUpdaterJobs.push_back(renderViewCommandUpdater); } @@ -584,7 +585,7 @@ void RenderViewBuilder::prepareJobs() const int lastRemaingElements = materialHandles.size() % RenderViewBuilder::m_optimalParallelJobCount; m_materialGathererJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount); for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) { - auto materialGatherer = Render::MaterialParameterGathererJobPtr::create(); + auto materialGatherer = MaterialParameterGathererJobPtr::create(); materialGatherer->setNodeManagers(m_renderer->nodeManagers()); if (i == RenderViewBuilder::m_optimalParallelJobCount - 1) materialGatherer->setHandles(materialHandles.mid(i * elementsPerJob, elementsPerJob + lastRemaingElements)); @@ -796,6 +797,8 @@ QVector RenderViewBuilder::entitiesInSubset(const QVector &e return intersection; } +} // OpenGL + } // Render } // Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h b/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h index 71719abee..98202670e 100644 --- a/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h +++ b/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERVIEWBUILDER_H -#define QT3DRENDER_RENDER_RENDERVIEWBUILDER_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWBUILDER_H +#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWBUILDER_H // // W A R N I N G @@ -70,6 +70,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + class Renderer; using SynchronizerJobPtr = GenericLambdaJobPtr>; @@ -139,10 +141,12 @@ private: static const int m_optimalParallelJobCount; }; +} // OpenGL + } // Render } // Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERVIEWBUILDER_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWBUILDER_H diff --git a/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp b/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp index e3cc7baf7..8c509f804 100644 --- a/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp +++ b/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp @@ -54,6 +54,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { ShaderParameterPack::~ShaderParameterPack() { @@ -106,6 +107,7 @@ void ShaderParameterPack::setSubmissionUniform(const ShaderUniform &uniform) m_submissionUniforms.push_back(uniform); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h b/src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h index 045081afd..d658d223b 100644 --- a/src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h +++ b/src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_SHADERPARAMETERPACK_P_H -#define QT3DRENDER_RENDER_SHADERPARAMETERPACK_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_SHADERPARAMETERPACK_P_H +#define QT3DRENDER_RENDER_OPENGL_SHADERPARAMETERPACK_P_H // // W A R N I N G @@ -70,6 +70,7 @@ class QFrameAllocator; namespace Qt3DRender { namespace Render { +namespace OpenGL { class GraphicsContext; @@ -79,14 +80,14 @@ struct BlockToUBO { bool m_needsUpdate; QHash m_updatedProperties; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, BlockToUBO, Q_MOVABLE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, BlockToUBO, Q_MOVABLE_TYPE) struct BlockToSSBO { int m_blockIndex; int m_bindingIndex; Qt3DCore::QNodeId m_bufferID; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, BlockToSSBO, Q_PRIMITIVE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, BlockToSSBO, Q_PRIMITIVE_TYPE) struct PackUniformHash @@ -209,13 +210,14 @@ private: friend class RenderView; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderParameterPack::NamedResource, Q_PRIMITIVE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, ShaderParameterPack::NamedResource, Q_PRIMITIVE_TYPE) +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -Q_DECLARE_METATYPE(Qt3DRender::Render::ShaderParameterPack) +Q_DECLARE_METATYPE(Qt3DRender::Render::OpenGL::ShaderParameterPack) -#endif // QT3DRENDER_RENDER_SHADERPARAMETERPACK_P_H +#endif // QT3DRENDER_RENDER_OPENGL_SHADERPARAMETERPACK_P_H diff --git a/src/plugins/renderers/opengl/renderer/shadervariables_p.h b/src/plugins/renderers/opengl/renderer/shadervariables_p.h index 98b98ae5c..94ea9b7e0 100644 --- a/src/plugins/renderers/opengl/renderer/shadervariables_p.h +++ b/src/plugins/renderers/opengl/renderer/shadervariables_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_SHADERVARIABLES_P_H -#define QT3DRENDER_RENDER_SHADERVARIABLES_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_SHADERVARIABLES_P_H +#define QT3DRENDER_RENDER_OPENGL_SHADERVARIABLES_P_H // // W A R N I N G @@ -60,6 +60,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + struct ShaderAttribute { ShaderAttribute() @@ -75,7 +77,7 @@ struct ShaderAttribute int m_size; int m_location; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderAttribute, Q_MOVABLE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, ShaderAttribute, Q_MOVABLE_TYPE) struct Q_AUTOTEST_EXPORT ShaderUniform { @@ -103,7 +105,7 @@ struct Q_AUTOTEST_EXPORT ShaderUniform uint m_rawByteSize; // contains byte size (size / type / strides) // size, offset and strides are in bytes }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderUniform, Q_MOVABLE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, ShaderUniform, Q_MOVABLE_TYPE) struct Q_AUTOTEST_EXPORT ShaderUniformBlock { @@ -122,7 +124,7 @@ struct Q_AUTOTEST_EXPORT ShaderUniformBlock int m_activeUniformsCount; int m_size; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderUniformBlock, Q_MOVABLE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, ShaderUniformBlock, Q_MOVABLE_TYPE) struct Q_AUTOTEST_EXPORT ShaderStorageBlock { @@ -141,7 +143,9 @@ struct Q_AUTOTEST_EXPORT ShaderStorageBlock int m_size; int m_activeVariablesCount; }; -QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderStorageBlock, Q_MOVABLE_TYPE) +QT3D_DECLARE_TYPEINFO_3(Qt3DRender, Render, OpenGL, ShaderStorageBlock, Q_MOVABLE_TYPE) + +} // namespace OpenGL } // namespace Render @@ -149,4 +153,4 @@ QT3D_DECLARE_TYPEINFO_2(Qt3DRender, Render, ShaderStorageBlock, Q_MOVABLE_TYPE) QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_SHADERVARIABLES_P_H +#endif // QT3DRENDER_RENDER_OPENGL_SHADERVARIABLES_P_H diff --git a/src/plugins/renderers/opengl/textures/gltexture.cpp b/src/plugins/renderers/opengl/textures/gltexture.cpp index c79961d78..11b43e085 100644 --- a/src/plugins/renderers/opengl/textures/gltexture.cpp +++ b/src/plugins/renderers/opengl/textures/gltexture.cpp @@ -66,6 +66,7 @@ using namespace Qt3DCore; namespace Qt3DRender { namespace Render { +namespace OpenGL { namespace { @@ -766,6 +767,7 @@ void GLTexture::introspectPropertiesFromSharedTextureId() gl->glBindTexture(m_properties.target, 0); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/textures/gltexture_p.h b/src/plugins/renderers/opengl/textures/gltexture_p.h index ca851712d..576ef5001 100644 --- a/src/plugins/renderers/opengl/textures/gltexture_p.h +++ b/src/plugins/renderers/opengl/textures/gltexture_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_GLTEXTURE_H -#define QT3DRENDER_RENDER_GLTEXTURE_H +#ifndef QT3DRENDER_RENDER_OPENGL_GLTEXTURE_H +#define QT3DRENDER_RENDER_OPENGL_GLTEXTURE_H // // W A R N I N G @@ -69,9 +69,14 @@ class QOpenGLTexture; namespace Qt3DRender { namespace Render { +template +class APITextureManager; + class TextureImageManager; class TextureDataManager; class TextureImageDataManager; + +namespace OpenGL { class RenderBuffer; /** @@ -258,9 +263,10 @@ private: bool m_wasTextureRecreated; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_GLTEXTURE_H +#endif // QT3DRENDER_RENDER_OPENGL_GLTEXTURE_H diff --git a/src/plugins/renderers/opengl/textures/renderbuffer.cpp b/src/plugins/renderers/opengl/textures/renderbuffer.cpp index bc5050f73..330e29472 100644 --- a/src/plugins/renderers/opengl/textures/renderbuffer.cpp +++ b/src/plugins/renderers/opengl/textures/renderbuffer.cpp @@ -45,6 +45,7 @@ QT_BEGIN_NAMESPACE namespace Qt3DRender { namespace Render { +namespace OpenGL { RenderBuffer::RenderBuffer(int width, int height, QAbstractTexture::TextureFormat format) : m_size(width, height), @@ -106,6 +107,7 @@ void RenderBuffer::release() m_context->functions()->glBindRenderbuffer(GL_RENDERBUFFER, 0); } +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender diff --git a/src/plugins/renderers/opengl/textures/renderbuffer_p.h b/src/plugins/renderers/opengl/textures/renderbuffer_p.h index 7dc62492a..16fc90e67 100644 --- a/src/plugins/renderers/opengl/textures/renderbuffer_p.h +++ b/src/plugins/renderers/opengl/textures/renderbuffer_p.h @@ -37,8 +37,8 @@ ** ****************************************************************************/ -#ifndef QT3DRENDER_RENDER_RENDERBUFFER_P_H -#define QT3DRENDER_RENDER_RENDERBUFFER_P_H +#ifndef QT3DRENDER_RENDER_OPENGL_RENDERBUFFER_P_H +#define QT3DRENDER_RENDER_OPENGL_RENDERBUFFER_P_H // // W A R N I N G @@ -59,6 +59,7 @@ class QOpenGLContext; namespace Qt3DRender { namespace Render { +namespace OpenGL { class Q_AUTOTEST_EXPORT RenderBuffer { @@ -82,9 +83,10 @@ private: QOpenGLContext *m_context; }; +} // namespace OpenGL } // namespace Render } // namespace Qt3DRender QT_END_NAMESPACE -#endif // QT3DRENDER_RENDER_RENDERBUFFER_P_H +#endif // QT3DRENDER_RENDER_OPENGL_RENDERBUFFER_P_H diff --git a/src/render/framegraph/nopicking_p.h b/src/render/framegraph/nopicking_p.h index 4ecf6e33b..f72090ef6 100644 --- a/src/render/framegraph/nopicking_p.h +++ b/src/render/framegraph/nopicking_p.h @@ -39,6 +39,7 @@ #ifndef QT3DRENDER_RENDER_NOPICKING_P_H #define QT3DRENDER_RENDER_NOPICKING_P_H + // // W A R N I N G // ------------- diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index da5abe4ac..f043b9894 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -705,6 +705,7 @@ Render::AbstractRenderer *QRenderAspectPrivate::loadRendererPlugin() if (renderer) return renderer; } + qFatal("Unable to load a renderer plugin"); return nullptr; } diff --git a/src/render/materialsystem/shader.cpp b/src/render/materialsystem/shader.cpp index f3570f78d..94e30a2c0 100644 --- a/src/render/materialsystem/shader.cpp +++ b/src/render/materialsystem/shader.cpp @@ -166,6 +166,12 @@ void Shader::initializeFromReference(const Shader &other) setLog(other.log()); } +// Called by renderer plugin when loading a GL Shader plugins +void Shader::requestCacheRebuild() +{ + markDirty(AbstractRenderer::MaterialDirty); +} + void Shader::setLog(const QString &log) { m_log = log; diff --git a/src/render/materialsystem/shader_p.h b/src/render/materialsystem/shader_p.h index 0814989ea..5eccc7510 100644 --- a/src/render/materialsystem/shader_p.h +++ b/src/render/materialsystem/shader_p.h @@ -114,20 +114,22 @@ public: inline bool requiresFrontendSync() const { return m_requiresFrontendSync; } inline void unsetRequiresFrontendSync() { m_requiresFrontendSync = false; } + // Set by Renderer plugin + void setLog(const QString &log); + void setStatus(QShaderProgram::Status status); + void initializeFromReference(const Shader &other); + + void requestCacheRebuild(); + private: QVector m_shaderCode; QString m_log; - QShaderProgram::Status m_status; bool m_requiresFrontendSync; + QShaderProgram::Status m_status; QShaderProgram::Format m_format; bool m_dirty; - void initializeFromReference(const Shader &other); - void setLog(const QString &log); - void setStatus(QShaderProgram::Status status); - - friend class GraphicsContext; }; #ifndef QT_NO_DEBUG_STREAM diff --git a/tests/auto/render/opengl/computecommand/tst_computecommand.cpp b/tests/auto/render/opengl/computecommand/tst_computecommand.cpp index 80cbfb090..3caf11c8f 100644 --- a/tests/auto/render/opengl/computecommand/tst_computecommand.cpp +++ b/tests/auto/render/opengl/computecommand/tst_computecommand.cpp @@ -44,11 +44,11 @@ // tst_Renderer is a friend class of Renderer -class tst_Renderer : public Qt3DRender::Render::Renderer +class tst_Renderer : public Qt3DRender::Render::OpenGL::Renderer { public: tst_Renderer() - : Qt3DRender::Render::Renderer(Qt3DRender::QRenderAspect::Synchronous) + : Qt3DRender::Render::OpenGL::Renderer(Qt3DRender::QRenderAspect::Synchronous) {} ~tst_Renderer() { diff --git a/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp b/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp index 8b9390340..e5c34f804 100644 --- a/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp +++ b/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp @@ -116,9 +116,9 @@ public: renderer()->submissionContext()->beginDrawing(m_window.data()); } - Render::Renderer *renderer() const + Render::OpenGL::Renderer *renderer() const { - return static_cast(d_func()->m_renderer); + return static_cast(d_func()->m_renderer); } void onRegistered() { QRenderAspect::onRegistered(); } @@ -196,7 +196,7 @@ private Q_SLOTS: void checkInitialState() { // GIVEN - Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; + Qt3DRender::Render::OpenGL::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; // THEN QVERIFY(backendFilterCompatibleTechniqueJob.manager() == nullptr); @@ -204,7 +204,7 @@ private Q_SLOTS: // WHEN Qt3DRender::Render::TechniqueManager techniqueManager; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); backendFilterCompatibleTechniqueJob.setManager(&techniqueManager); backendFilterCompatibleTechniqueJob.setRenderer(&renderer); @@ -218,7 +218,7 @@ private Q_SLOTS: void checkRunRendererRunning() { // GIVEN - Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; + Qt3DRender::Render::OpenGL::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob; Qt3DRender::TestAspect testAspect(buildTestScene()); const bool unableToCreateContext = !testAspect.contextCreationSuccessful(); diff --git a/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp b/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp index 83420af3b..6a5bc87ea 100644 --- a/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp +++ b/tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp @@ -46,7 +46,7 @@ private Q_SLOTS: void tst_GLShaderManager::adopt() { // GIVEN - Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::Render::OpenGL::GLShaderManager cache; Qt3DRender::QShaderProgram frontendShader1; Qt3DRender::QShaderProgram frontendShader2; TestRenderer renderer; @@ -64,7 +64,7 @@ void tst_GLShaderManager::adopt() QVERIFY(backendShaderNode1.peerId() != backendShaderNode2.peerId()); // WHEN - Qt3DRender::Render::GLShader *glShader1 = cache.createOrAdoptExisting(&backendShaderNode1); + Qt3DRender::Render::OpenGL::GLShader *glShader1 = cache.createOrAdoptExisting(&backendShaderNode1); // THEN QVERIFY(glShader1 != nullptr); @@ -73,7 +73,7 @@ void tst_GLShaderManager::adopt() QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId()); // WHEN - Qt3DRender::Render::GLShader *glShader2 = cache.createOrAdoptExisting(&backendShaderNode2); + Qt3DRender::Render::OpenGL::GLShader *glShader2 = cache.createOrAdoptExisting(&backendShaderNode2); // THEN QCOMPARE(glShader1, glShader2); @@ -87,7 +87,7 @@ void tst_GLShaderManager::adopt() void tst_GLShaderManager::lookupResource() { // GIVEN - Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::Render::OpenGL::GLShaderManager cache; Qt3DRender::QShaderProgram frontendShader1; Qt3DRender::QShaderProgram frontendShader2; TestRenderer renderer; @@ -104,8 +104,8 @@ void tst_GLShaderManager::lookupResource() cache.createOrAdoptExisting(&backendShaderNode2); // THEN - Qt3DRender::Render::GLShader *glShader1 = cache.lookupResource(backendShaderNode1.peerId()); - Qt3DRender::Render::GLShader *glShader2 = cache.lookupResource(backendShaderNode2.peerId()); + Qt3DRender::Render::OpenGL::GLShader *glShader1 = cache.lookupResource(backendShaderNode1.peerId()); + Qt3DRender::Render::OpenGL::GLShader *glShader2 = cache.lookupResource(backendShaderNode2.peerId()); QVERIFY(glShader1 != nullptr); QCOMPARE(glShader1, glShader2); const QVector shaderNodeIds = cache.shaderIdsForProgram(glShader1); @@ -117,7 +117,7 @@ void tst_GLShaderManager::lookupResource() void tst_GLShaderManager::abandon() { // GIVEN - Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::Render::OpenGL::GLShaderManager cache; Qt3DRender::QShaderProgram frontendShader1; Qt3DRender::QShaderProgram frontendShader2; TestRenderer renderer; @@ -132,7 +132,7 @@ void tst_GLShaderManager::abandon() cache.createOrAdoptExisting(&backendShaderNode2); // WHEN - Qt3DRender::Render::GLShader *glShader = cache.lookupResource(backendShaderNode1.peerId()); + Qt3DRender::Render::OpenGL::GLShader *glShader = cache.lookupResource(backendShaderNode1.peerId()); cache.abandon(glShader, &backendShaderNode1); // THEN @@ -147,7 +147,7 @@ void tst_GLShaderManager::abandon() // THEN shaderNodeIds = cache.shaderIdsForProgram(glShader); QCOMPARE(shaderNodeIds.size(), 0); - const QVector releasedShaders = cache.takeAbandonned(); + const QVector releasedShaders = cache.takeAbandonned(); QCOMPARE(releasedShaders.size(), 1); QCOMPARE(releasedShaders.first(), glShader); } @@ -155,7 +155,7 @@ void tst_GLShaderManager::abandon() void tst_GLShaderManager::insertAfterRemoval() { // GIVEN - Qt3DRender::Render::GLShaderManager cache; + Qt3DRender::Render::OpenGL::GLShaderManager cache; Qt3DRender::QShaderProgram frontendShader; TestRenderer renderer; Qt3DRender::Render::Shader backendShaderNode; @@ -165,8 +165,8 @@ void tst_GLShaderManager::insertAfterRemoval() simulateInitialization(&frontendShader, &backendShaderNode); // WHEN - Qt3DRender::Render::GLShader *apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); - const Qt3DRender::Render::GLShader *originalApiShader = apiShader1; + Qt3DRender::Render::OpenGL::GLShader *apiShader1 = cache.createOrAdoptExisting(&backendShaderNode); + const Qt3DRender::Render::OpenGL::GLShader *originalApiShader = apiShader1; // THEN auto apiShader2 = cache.lookupResource(frontendShader.id()); @@ -179,7 +179,7 @@ void tst_GLShaderManager::insertAfterRemoval() cache.abandon(apiShader1, &backendShaderNode); // THEN - Qt3DRender::Render::GLShader *apiShaderEmpty = cache.lookupResource(frontendShader.id()); + Qt3DRender::Render::OpenGL::GLShader *apiShaderEmpty = cache.lookupResource(frontendShader.id()); QVERIFY(apiShaderEmpty == nullptr); // WHEN diff --git a/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp b/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp index 0a43a3040..5a1d22283 100644 --- a/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp +++ b/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp @@ -47,6 +47,7 @@ QT_BEGIN_NAMESPACE using namespace Qt3DRender; using namespace Qt3DRender::Render; +using namespace Qt3DRender::Render::OpenGL; namespace { diff --git a/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp b/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp index a4a59d7c4..08c30dc15 100644 --- a/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp +++ b/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp @@ -43,6 +43,7 @@ using namespace Qt3DRender; using namespace Qt3DRender::Render; +using namespace Qt3DRender::Render::OpenGL; namespace { diff --git a/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp b/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp index 3e4a052ba..b463e6236 100644 --- a/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp +++ b/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp @@ -42,6 +42,7 @@ using namespace Qt3DRender; using namespace Qt3DRender::Render; +using namespace Qt3DRender::Render::OpenGL; namespace { diff --git a/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp b/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp index 31024e1db..8f86f38ce 100644 --- a/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp +++ b/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp @@ -43,6 +43,7 @@ using namespace Qt3DRender; using namespace Qt3DRender::Render; +using namespace Qt3DRender::Render::OpenGL; namespace { diff --git a/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp b/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp index e6b78c47b..efd2c6603 100644 --- a/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp +++ b/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp @@ -107,9 +107,9 @@ public: d_func()->m_renderer->initialize(); } - Render::MaterialParameterGathererJobPtr materialGathererJob() const + Render::OpenGL::MaterialParameterGathererJobPtr materialGathererJob() const { - Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); + Render::OpenGL::MaterialParameterGathererJobPtr job = Render::OpenGL::MaterialParameterGathererJobPtr::create(); job->setNodeManagers(nodeManagers()); return job; } @@ -232,7 +232,7 @@ private Q_SLOTS: // GIVEN Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph()); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -252,7 +252,7 @@ private Q_SLOTS: TestMaterial material; Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph(), &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -274,7 +274,7 @@ private Q_SLOTS: material.setEnabled(false); Qt3DCore::QEntity *sceneRoot = buildScene(viewportFrameGraph(), &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -306,7 +306,7 @@ private Q_SLOTS: Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -346,7 +346,7 @@ private Q_SLOTS: Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -382,7 +382,7 @@ private Q_SLOTS: Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -416,7 +416,7 @@ private Q_SLOTS: Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -456,7 +456,7 @@ private Q_SLOTS: Qt3DCore::QEntity *sceneRoot = buildScene(frameGraphFilter, &material); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); @@ -509,7 +509,7 @@ private Q_SLOTS: material.es2Pass()->addParameter(passParam); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); @@ -526,10 +526,10 @@ private Q_SLOTS: // THEN -> RenderPassFilter wins QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); QCOMPARE(passParameterData.size(), 1); - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + const Qt3DRender::Render::OpenGL::RenderPassParameterData data = passParameterData.first(); QCOMPARE(data.parameterInfo.size(), 1); QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(renderPassParameter->id())); @@ -565,7 +565,7 @@ private Q_SLOTS: material.es2Pass()->addParameter(passParam); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); @@ -582,10 +582,10 @@ private Q_SLOTS: // THEN -> TechniqueFilter wins QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); QCOMPARE(passParameterData.size(), 1); - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + const Qt3DRender::Render::OpenGL::RenderPassParameterData data = passParameterData.first(); QCOMPARE(data.parameterInfo.size(), 1); QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(techniqueFilterParameter->id())); @@ -620,7 +620,7 @@ private Q_SLOTS: material.es2Pass()->addParameter(passParam); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); @@ -637,10 +637,10 @@ private Q_SLOTS: // THEN -> TechniqueFilter wins QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); QCOMPARE(passParameterData.size(), 1); - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + const Qt3DRender::Render::OpenGL::RenderPassParameterData data = passParameterData.first(); QCOMPARE(data.parameterInfo.size(), 1); QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(materialParameter->id())); @@ -674,7 +674,7 @@ private Q_SLOTS: material.es2Pass()->addParameter(passParam); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); @@ -691,10 +691,10 @@ private Q_SLOTS: // THEN -> TechniqueFilter wins QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); QCOMPARE(passParameterData.size(), 1); - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + const Qt3DRender::Render::OpenGL::RenderPassParameterData data = passParameterData.first(); QCOMPARE(data.parameterInfo.size(), 1); QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(effectParameter->id())); @@ -724,7 +724,7 @@ private Q_SLOTS: material.es2Pass()->addParameter(passParam); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); @@ -741,10 +741,10 @@ private Q_SLOTS: // THEN -> TechniqueFilter wins QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); QCOMPARE(passParameterData.size(), 1); - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + const Qt3DRender::Render::OpenGL::RenderPassParameterData data = passParameterData.first(); QCOMPARE(data.parameterInfo.size(), 1); QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(techniqueParam->id())); @@ -768,7 +768,7 @@ private Q_SLOTS: material.es2Pass()->addParameter(passParam); Qt3DRender::TestAspect testAspect(sceneRoot); - Qt3DRender::Render::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatherer = testAspect.materialGathererJob(); testAspect.initializeRenderer(); QCOMPARE(testAspect.nodeManagers()->materialManager()->activeHandles().size(), 1); @@ -785,10 +785,10 @@ private Q_SLOTS: // THEN -> TechniqueFilter wins QCOMPARE(gatherer->materialToPassAndParameter().size(), 1); - const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); + const QVector passParameterData = gatherer->materialToPassAndParameter().begin().value(); QCOMPARE(passParameterData.size(), 1); - const Qt3DRender::Render::RenderPassParameterData data = passParameterData.first(); + const Qt3DRender::Render::OpenGL::RenderPassParameterData data = passParameterData.first(); QCOMPARE(data.parameterInfo.size(), 1); QCOMPARE(data.parameterInfo.first().handle, testAspect.nodeManagers()->parameterManager()->lookupHandle(passParam->id())); diff --git a/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp b/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp index 2e0dd0f96..bd4772045 100644 --- a/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp +++ b/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp @@ -44,14 +44,14 @@ private slots: void tst_QGraphicsUtils::fillScalarInDataArray() { - Qt3DRender::Render::ShaderUniform description; + Qt3DRender::Render::OpenGL::ShaderUniform description; description.m_size = 1; description.m_offset = 0; description.m_arrayStride = 10; QVector4D testVector(8.0f, 8.0f, 3.0f, 1.0f); - const GLfloat *vectorData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(testVector, 1, 4); + const GLfloat *vectorData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(testVector, 1, 4); for (int i = 0; i < 4; i++) { if (i == 0) @@ -68,7 +68,7 @@ void tst_QGraphicsUtils::fillScalarInDataArray() char *innerData = data.data(); // Checked that we are not overflowing - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 2); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 2); for (int i = 0; i < 4; ++i) { if (i < 2) QVERIFY(vectorData[i] == ((GLfloat*)innerData)[i]); @@ -77,7 +77,7 @@ void tst_QGraphicsUtils::fillScalarInDataArray() } // Check that all values are copied - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); for (int i = 0; i < 4; ++i) QVERIFY(vectorData[i] == ((GLfloat*)innerData)[i]); @@ -86,7 +86,7 @@ void tst_QGraphicsUtils::fillScalarInDataArray() data = QByteArray(description.m_size * 8 * sizeof(GLfloat), 0); innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); for (int i = 0; i < 8; ++i) { if (i < 4) QVERIFY(((GLfloat*)innerData)[i] == 0.0f); @@ -102,9 +102,9 @@ void tst_QGraphicsUtils::fillArray() QVector4D testVector3(4.0f, 5.0f, 4.0f, 2.0f); QVariantList variantList = QVariantList() << testVector << testVector2 << testVector3; - const GLfloat *vectorData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant(variantList), 3, 4); + const GLfloat *vectorData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(QVariant(variantList), 3, 4); - Qt3DRender::Render::ShaderUniform description; + Qt3DRender::Render::OpenGL::ShaderUniform description; description.m_size = 3; description.m_offset = 16; @@ -112,7 +112,7 @@ void tst_QGraphicsUtils::fillArray() QByteArray data(description.m_size * (4 + description.m_arrayStride) * sizeof(GLfloat) + description.m_offset, 0); char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, vectorData, description, 4); int offset = description.m_offset / sizeof(GLfloat); int stride = description.m_arrayStride / sizeof(GLfloat); @@ -144,25 +144,25 @@ void tst_QGraphicsUtils::fillScalarWithOffsets() QVector4D color(4.0f, 5.0f, 4.0f, 1.0f); float intensity = 1.0f; - Qt3DRender::Render::ShaderUniform posUniform; + Qt3DRender::Render::OpenGL::ShaderUniform posUniform; posUniform.m_size = 1; posUniform.m_arrayStride = 0; posUniform.m_matrixStride = 0; posUniform.m_offset = 0; - Qt3DRender::Render::ShaderUniform dirUniform; + Qt3DRender::Render::OpenGL::ShaderUniform dirUniform; dirUniform.m_size = 1; dirUniform.m_arrayStride = 0; dirUniform.m_matrixStride = 0; dirUniform.m_offset = 16; - Qt3DRender::Render::ShaderUniform colUniform; + Qt3DRender::Render::OpenGL::ShaderUniform colUniform; colUniform.m_size = 1; colUniform.m_arrayStride = 0; colUniform.m_matrixStride = 0; colUniform.m_offset = 32; - Qt3DRender::Render::ShaderUniform intUniform; + Qt3DRender::Render::OpenGL::ShaderUniform intUniform; intUniform.m_size = 1; intUniform.m_arrayStride = 0; intUniform.m_matrixStride = 0; @@ -171,18 +171,18 @@ void tst_QGraphicsUtils::fillScalarWithOffsets() QVector data(16); void *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(position, 1, 3), - posUniform, 3); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(direction, 1, 3), - dirUniform, 3); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(color, 1, 4), - colUniform, 4); - Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData, - Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(intensity, 1, 1), - intUniform, 1); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(position, 1, 3), + posUniform, 3); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(direction, 1, 3), + dirUniform, 3); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(color, 1, 4), + colUniform, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData, + Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(intensity, 1, 1), + intUniform, 1); GLfloat *floatData = (GLfloat*)innerData; @@ -214,9 +214,9 @@ void tst_QGraphicsUtils::fillMatrix4x4() QMatrix4x4 mat(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f, 16.0f); // column major - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(mat, 1, 16); + const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(mat, 1, 16); - Qt3DRender::Render::ShaderUniform description; + Qt3DRender::Render::OpenGL::ShaderUniform description; description.m_size = 1; description.m_offset = 0; @@ -226,7 +226,7 @@ void tst_QGraphicsUtils::fillMatrix4x4() QByteArray data(description.m_size * 16 * sizeof(GLfloat), 0); char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); // Check for no offset/no stride for (int i = 0; i < 16; ++i) QVERIFY((((GLfloat *)innerData)[i]) == matData[i]); @@ -234,7 +234,7 @@ void tst_QGraphicsUtils::fillMatrix4x4() description.m_offset = 12; data = QByteArray((description.m_size * 16 + description.m_offset) * sizeof(GLfloat), 0); innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); // Check with 12 offset/no stride for (int i = 0; i < 16; ++i) QVERIFY((((GLfloat *)innerData)[3 + i]) == matData[i]); @@ -242,7 +242,7 @@ void tst_QGraphicsUtils::fillMatrix4x4() description.m_matrixStride = 16; data = QByteArray((description.m_size * 16 + 4 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 4); // Check with 10 offset/ 16 stride int offset = description.m_offset / sizeof(GLfloat); int matrixStride = description.m_matrixStride / sizeof(GLfloat); @@ -259,9 +259,9 @@ void tst_QGraphicsUtils::fillMatrix3x4() QMatrix3x4 mat; mat.fill(6.0f); - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); + const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); - Qt3DRender::Render::ShaderUniform description; + Qt3DRender::Render::OpenGL::ShaderUniform description; description.m_size = 1; description.m_offset = 16; @@ -270,7 +270,7 @@ void tst_QGraphicsUtils::fillMatrix3x4() QByteArray data((description.m_size * 12 + 3 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 3, 4); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 3, 4); // Check with 16 offset/ 12 stride int offset = description.m_offset / sizeof(GLfloat); int matrixStride = description.m_matrixStride / sizeof(GLfloat); @@ -287,9 +287,9 @@ void tst_QGraphicsUtils::fillMatrix4x3() QMatrix4x3 mat; mat.fill(6.0f); - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); + const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(mat), 1, 12); - Qt3DRender::Render::ShaderUniform description; + Qt3DRender::Render::OpenGL::ShaderUniform description; description.m_size = 1; description.m_offset = 16; @@ -298,7 +298,7 @@ void tst_QGraphicsUtils::fillMatrix4x3() QByteArray data((description.m_size * 12 + 4 * description.m_matrixStride + description.m_offset) * sizeof(GLfloat), 0); char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); // Check with 16 offset/ 16 stride int offset = description.m_offset / sizeof(GLfloat); int matrixStride = description.m_matrixStride / sizeof(GLfloat); @@ -321,9 +321,9 @@ void tst_QGraphicsUtils::fillMatrixArray() QVariantList matrices = QVariantList() << QVariant::fromValue(mat1) << QVariant::fromValue(mat2) << QVariant::fromValue(mat3); - const GLfloat *matData = Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(matrices), 3, 12); + const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant(QVariant::fromValue(matrices), 3, 12); - Qt3DRender::Render::ShaderUniform description; + Qt3DRender::Render::OpenGL::ShaderUniform description; description.m_size = 3; description.m_offset = 12; @@ -332,7 +332,7 @@ void tst_QGraphicsUtils::fillMatrixArray() QByteArray data((description.m_size * (12 + 4 * description.m_matrixStride + description.m_arrayStride) + description.m_offset) * sizeof(GLfloat), 0); char *innerData = data.data(); - Qt3DRender::Render::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); + Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataMatrixArray(innerData, matData, description, 4, 3); // Check with 12 offset/ 4 array stride / 16 matrix stride int offset = description.m_offset / sizeof(GLfloat); int matrixStride = description.m_matrixStride / sizeof(GLfloat); diff --git a/tests/auto/render/opengl/renderer/tst_renderer.cpp b/tests/auto/render/opengl/renderer/tst_renderer.cpp index 6aed6ed5f..db7a37af1 100644 --- a/tests/auto/render/opengl/renderer/tst_renderer.cpp +++ b/tests/auto/render/opengl/renderer/tst_renderer.cpp @@ -50,7 +50,7 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); Qt3DRender::Render::OffscreenSurfaceHelper offscreenHelper(&renderer); Qt3DRender::Render::RenderSettings settings; // owned by FG manager @@ -107,8 +107,8 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); - Qt3DRender::Render::RenderQueue *renderQueue = renderer.renderQueue(); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::RenderQueue *renderQueue = renderer.renderQueue(); Qt3DRender::Render::OffscreenSurfaceHelper offscreenHelper(&renderer); Qt3DRender::Render::RenderSettings settings; // owned by FG manager @@ -129,16 +129,16 @@ private Q_SLOTS: // NOTE: FilterCompatibleTechniqueJob and ShaderGathererJob cannot run because the context // is not initialized in this test - const int renderViewBuilderMaterialCacheJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + const int renderViewBuilderMaterialCacheJobCount = 1 + Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount(); // syncMaterialGathererJob // n * materialGathererJob const int layerCacheJobCount = 2; // filterEntityByLayerJob, // syncFilterEntityByLayerJob - const int singleRenderViewCommandRebuildJobCount = 1 + Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + const int singleRenderViewCommandRebuildJobCount = 1 + Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount(); - const int singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount(); + const int singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount(); // RenderViewBuilder renderViewJob, // syncRenderViewInitializationJob, // syncFrustumCullingJob, diff --git a/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp b/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp index 2be089495..728648a3c 100644 --- a/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp +++ b/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp @@ -53,7 +53,7 @@ private Q_SLOTS: void tst_RenderQueue::setRenderViewCount() { // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; + Qt3DRender::Render::OpenGL::RenderQueue renderQueue; // THEN QCOMPARE(renderQueue.wasReset(), true); @@ -70,7 +70,7 @@ void tst_RenderQueue::setRenderViewCount() void tst_RenderQueue::circleQueues() { // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; + Qt3DRender::Render::OpenGL::RenderQueue renderQueue; renderQueue.setTargetRenderViewCount(7); // WHEN @@ -85,9 +85,9 @@ void tst_RenderQueue::circleQueues() QCOMPARE(renderQueue.currentRenderViewCount(), 0); // WHEN - QList renderViews; + QList renderViews; for (int i = 0; i < 7; i++) { - renderViews << new Qt3DRender::Render::RenderView(); + renderViews << new Qt3DRender::Render::OpenGL::RenderView(); renderQueue.queueRenderView(renderViews.at(i), i); } @@ -99,19 +99,19 @@ void tst_RenderQueue::circleQueues() void tst_RenderQueue::checkOrder() { // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; + Qt3DRender::Render::OpenGL::RenderQueue renderQueue; renderQueue.setTargetRenderViewCount(7); - QVector renderViews(7); + QVector renderViews(7); // WHEN for (int i = 0; i < 7; ++i) { int processingOrder = (i % 2 == 0) ? (6 - i) : i; - renderViews[processingOrder] = new Qt3DRender::Render::RenderView(); + renderViews[processingOrder] = new Qt3DRender::Render::OpenGL::RenderView(); renderQueue.queueRenderView(renderViews[processingOrder], processingOrder); } // THEN - QVector frame = renderQueue.nextFrameQueue(); + QVector frame = renderQueue.nextFrameQueue(); for (int i = 0; i < 7; ++i) { QVERIFY(frame[i] == renderViews[i]); } @@ -120,14 +120,14 @@ void tst_RenderQueue::checkOrder() void tst_RenderQueue::checkTimeToSubmit() { // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; + Qt3DRender::Render::OpenGL::RenderQueue renderQueue; renderQueue.setTargetRenderViewCount(7); - QVector renderViews(7); + QVector renderViews(7); // WHEN for (int i = 0; i < 7; i++) { int processingOrder = (i % 2 == 0) ? (6 - i) : i; - renderViews[processingOrder] = new Qt3DRender::Render::RenderView(); + renderViews[processingOrder] = new Qt3DRender::Render::OpenGL::RenderView(); renderQueue.queueRenderView(renderViews[processingOrder], processingOrder); // THEN @@ -144,7 +144,7 @@ class SimpleWorker : public QThread public: QSemaphore m_waitSubmit; QSemaphore m_waitQueue; - Qt3DRender::Render::RenderQueue *m_renderQueues; + Qt3DRender::Render::OpenGL::RenderQueue *m_renderQueues; public Q_SLOTS: @@ -160,7 +160,7 @@ public Q_SLOTS: // THEN QCOMPARE(m_renderQueues->currentRenderViewCount(), j); // WHEN - m_renderQueues->queueRenderView(new Qt3DRender::Render::RenderView(), j); + m_renderQueues->queueRenderView(new Qt3DRender::Render::OpenGL::RenderView(), j); // THEN QVERIFY(m_renderQueues->targetRenderViewCount() == 7); QCOMPARE(m_renderQueues->currentRenderViewCount(), j + 1); @@ -178,7 +178,7 @@ public Q_SLOTS: void tst_RenderQueue::concurrentQueueAccess() { // GIVEN - Qt3DRender::Render::RenderQueue *renderQueue = new Qt3DRender::Render::RenderQueue; + Qt3DRender::Render::OpenGL::RenderQueue *renderQueue = new Qt3DRender::Render::OpenGL::RenderQueue; SimpleWorker *jobsThread = new SimpleWorker(); renderQueue->setTargetRenderViewCount(7); @@ -212,7 +212,7 @@ void tst_RenderQueue::concurrentQueueAccess() void tst_RenderQueue::resetQueue() { // GIVEN - Qt3DRender::Render::RenderQueue renderQueue; + Qt3DRender::Render::OpenGL::RenderQueue renderQueue; for (int j = 0; j < 5; j++) { // WHEN @@ -222,7 +222,7 @@ void tst_RenderQueue::resetQueue() QVERIFY(renderQueue.currentRenderViewCount() == 0); // WHEN - QVector renderViews(5); + QVector renderViews(5); for (int i = 0; i < 5; ++i) { renderQueue.queueRenderView(renderViews.at(i), i); } diff --git a/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp b/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp index 6dc463589..fe534e243 100644 --- a/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp +++ b/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp @@ -96,14 +96,14 @@ public: return d_func()->m_renderer->nodeManagers(); } - Render::Renderer *renderer() const + Render::OpenGL::Renderer *renderer() const { - return static_cast(d_func()->m_renderer); + return static_cast(d_func()->m_renderer); } - Render::MaterialParameterGathererJobPtr materialGathererJob() const + Render::OpenGL::MaterialParameterGathererJobPtr materialGathererJob() const { - Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); + Render::OpenGL::MaterialParameterGathererJobPtr job = Render::OpenGL::MaterialParameterGathererJobPtr::create(); job->setNodeManagers(nodeManagers()); return job; } @@ -216,7 +216,7 @@ private Q_SLOTS: { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); // THEN QCOMPARE(renderViewBuilder.renderViewIndex(), 0); @@ -247,14 +247,14 @@ private Q_SLOTS: QVERIFY(renderViewBuilder.filterEntityByLayerJob().isNull()); QVERIFY(renderViewBuilder.syncFilterEntityByLayerJob().isNull()); - QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.renderViewCommandUpdaterJobs().size(), Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount()); QCOMPARE(renderViewBuilder.materialGathererJobs().size(), 0); - QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 8 + 1 * Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount()); } { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); renderViewBuilder.prepareJobs(); @@ -264,22 +264,22 @@ private Q_SLOTS: QVERIFY(!renderViewBuilder.syncFilterEntityByLayerJob().isNull()); // mark jobs dirty and recheck - QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount()); } { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.setMaterialGathererCacheNeedsToBeRebuilt(true); renderViewBuilder.prepareJobs(); // THEN QCOMPARE(renderViewBuilder.materialGathererCacheNeedsToBeRebuilt(), true); - QCOMPARE(renderViewBuilder.materialGathererJobs().size(), Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.materialGathererJobs().size(), Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount()); QVERIFY(!renderViewBuilder.syncMaterialGathererJob().isNull()); // mark jobs dirty and recheck - QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 9 + 2 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount()); + QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 9 + 2 * Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount()); } } @@ -296,7 +296,7 @@ private Q_SLOTS: { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.prepareJobs(); renderViewBuilder.buildJobHierachy(); @@ -357,7 +357,7 @@ private Q_SLOTS: } { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); renderViewBuilder.setMaterialGathererCacheNeedsToBeRebuilt(true); renderViewBuilder.prepareJobs(); @@ -441,7 +441,7 @@ private Q_SLOTS: QVERIFY(leafNode != nullptr); // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.prepareJobs(); renderViewBuilder.buildJobHierachy(); renderViewBuilder.renderViewJob()->run(); @@ -456,7 +456,7 @@ private Q_SLOTS: Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer(); // THEN Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); @@ -476,7 +476,7 @@ private Q_SLOTS: Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer(); // THEN Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); @@ -495,7 +495,7 @@ private Q_SLOTS: Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport(); Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport); Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer(); // THEN Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id()); @@ -528,7 +528,7 @@ private Q_SLOTS: { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.prepareJobs(); renderViewBuilder.buildJobHierachy(); @@ -552,7 +552,7 @@ private Q_SLOTS: } { // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); renderViewBuilder.prepareJobs(); renderViewBuilder.buildJobHierachy(); @@ -598,7 +598,7 @@ private Q_SLOTS: QVERIFY(leafNode != nullptr); // WHEN - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); renderViewBuilder.prepareJobs(); renderViewBuilder.buildJobHierachy(); @@ -622,7 +622,7 @@ private Q_SLOTS: Qt3DRender::QLayer *layer = new Qt3DRender::QLayer(); layerFilter->addLayer(layer); Qt3DRender::TestAspect testAspect(buildEntityFilterTestScene(viewport, layer)); - Qt3DRender::Render::Renderer *renderer = testAspect.renderer(); + Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer(); // THEN Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(layerFilter->id()); @@ -631,7 +631,8 @@ private Q_SLOTS: // WHEN renderer->markDirty(Qt3DRender::Render::AbstractRenderer::AllDirty, nullptr); - Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer()); + renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true); renderViewBuilder.prepareJobs(); renderViewBuilder.buildJobHierachy(); @@ -653,7 +654,7 @@ private Q_SLOTS: std::sort(renderableEntity.begin(), renderableEntity.end()); // WHEN - renderableEntity = Qt3DRender::Render::RenderViewBuilder::entitiesInSubset(renderableEntity, filteredEntity); + renderableEntity = Qt3DRender::Render::OpenGL::RenderViewBuilder::entitiesInSubset(renderableEntity, filteredEntity); // THEN QCOMPARE(renderableEntity.size(), 100); diff --git a/tests/auto/render/opengl/renderviews/tst_renderviews.cpp b/tests/auto/render/opengl/renderviews/tst_renderviews.cpp index d30b8ddca..0b1e22909 100644 --- a/tests/auto/render/opengl/renderviews/tst_renderviews.cpp +++ b/tests/auto/render/opengl/renderviews/tst_renderviews.cpp @@ -48,6 +48,8 @@ namespace Qt3DRender { namespace Render { +namespace OpenGL { + namespace { void compareShaderParameterPacks(const ShaderParameterPack &t1, @@ -127,7 +129,7 @@ private Q_SLOTS: QCOMPARE(backendBarrier.waitOperations(), barriers); // WHEN - Qt3DRender::Render::setRenderViewConfigFromFrameGraphLeafNode(&renderView, &backendBarrier); + Qt3DRender::Render::OpenGL::setRenderViewConfigFromFrameGraphLeafNode(&renderView, &backendBarrier); // THEN QCOMPARE(backendBarrier.waitOperations(), renderView.memoryBarrier()); @@ -139,7 +141,7 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; @@ -174,7 +176,7 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; @@ -266,7 +268,7 @@ private Q_SLOTS: QFETCH(QVector, expectedMinimizedParameters); Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); renderer.setNodeManagers(&nodeManagers); GLShaderManager *shaderManager = renderer.glResourceManagers()->glShaderManager(); @@ -312,7 +314,7 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; @@ -347,7 +349,7 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; @@ -382,7 +384,7 @@ private Q_SLOTS: { // GIVEN Qt3DRender::Render::NodeManagers nodeManagers; - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); RenderView renderView; QVector rawCommands; QVector sortTypes; @@ -542,6 +544,8 @@ private Q_SLOTS: private: }; +} // OpenGL + } // Render } // Qt3DRender @@ -549,6 +553,6 @@ private: QT_END_NAMESPACE //APPLESS_ -QTEST_MAIN(Qt3DRender::Render::tst_RenderViews) +QTEST_MAIN(Qt3DRender::Render::OpenGL::tst_RenderViews) #include "tst_renderviews.moc" diff --git a/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp b/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp index 8a345d840..6b714b9e1 100644 --- a/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp +++ b/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp @@ -108,11 +108,11 @@ public: return m_scalar; } - QHash buildUniformMap(const QString &blockName) + QHash buildUniformMap(const QString &blockName) { - QHash uniforms; + QHash uniforms; - uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform()); + uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::OpenGL::ShaderUniform()); return uniforms; } @@ -149,11 +149,11 @@ public: return m_texture; } - QHash buildUniformMap(const QString &blockName) + QHash buildUniformMap(const QString &blockName) { - QHash uniforms; + QHash uniforms; - uniforms.insert(blockName + QStringLiteral(".texture"), Qt3DRender::Render::ShaderUniform()); + uniforms.insert(blockName + QStringLiteral(".texture"), Qt3DRender::Render::OpenGL::ShaderUniform()); return uniforms; } @@ -190,11 +190,11 @@ public: return m_array; } - QHash buildUniformMap(const QString &blockName) + QHash buildUniformMap(const QString &blockName) { - QHash uniforms; + QHash uniforms; - uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform()); + uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::OpenGL::ShaderUniform()); return uniforms; } @@ -245,12 +245,12 @@ public: return m_array; } - virtual QHash buildUniformMap(const QString &blockName) + virtual QHash buildUniformMap(const QString &blockName) { - QHash uniforms; + QHash uniforms; - uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform()); - uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform()); + uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::OpenGL::ShaderUniform()); + uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::OpenGL::ShaderUniform()); return uniforms; } @@ -299,17 +299,17 @@ public: return m_inner; } - QHash buildUniformMap(const QString &blockName) override + QHash buildUniformMap(const QString &blockName) override { - QHash innerUniforms; + QHash innerUniforms; StructShaderData *innerData = nullptr; if ((innerData = qobject_cast(m_inner)) != nullptr) innerUniforms = innerData->buildUniformMap(QStringLiteral(".inner")); - QHash uniforms = StructShaderData::buildUniformMap(blockName); - QHash::const_iterator it = innerUniforms.begin(); - const QHash::const_iterator end = innerUniforms.end(); + QHash uniforms = StructShaderData::buildUniformMap(blockName); + QHash::const_iterator it = innerUniforms.begin(); + const QHash::const_iterator end = innerUniforms.end(); while (it != end) { uniforms.insert(blockName + it.key(), it.value()); @@ -362,7 +362,7 @@ void tst_RenderViewUtils::topLevelScalarValueNoUniforms() QVERIFY(backendShaderData != nullptr); // WHEB - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; @@ -391,7 +391,7 @@ void tst_RenderViewUtils::topLevelScalarValue() QVERIFY(backendShaderData != nullptr); // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; @@ -404,8 +404,8 @@ void tst_RenderViewUtils::topLevelScalarValue() QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); while (it != end) { // THEN @@ -433,7 +433,7 @@ void tst_RenderViewUtils::topLevelTextureValueNoUniforms() QVERIFY(backendShaderData != nullptr); // WHEB - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; @@ -464,7 +464,7 @@ void tst_RenderViewUtils::topLevelTextureValue() QVERIFY(backendShaderData != nullptr); // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; @@ -477,8 +477,8 @@ void tst_RenderViewUtils::topLevelTextureValue() QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); while (it != end) { // THEN @@ -506,7 +506,7 @@ void tst_RenderViewUtils::topLevelArrayValue() QVERIFY(backendShaderData != nullptr); // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; @@ -519,8 +519,8 @@ void tst_RenderViewUtils::topLevelArrayValue() QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), 1); // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); while (it != end) { // THEN @@ -571,13 +571,13 @@ void tst_RenderViewUtils::nestedShaderDataValue() QVERIFY(backendShaderData3 != nullptr); // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0].scalar"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[1].scalar"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[2].scalar"), Qt3DRender::Render::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0].scalar"), Qt3DRender::Render::OpenGL::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[1].scalar"), Qt3DRender::Render::OpenGL::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[2].scalar"), Qt3DRender::Render::OpenGL::ShaderUniform()); // build name-value map blockBuilder.buildActiveUniformNameValueMapStructHelper(backendArrayShaderData, QStringLiteral("MyBlock")); @@ -647,7 +647,7 @@ void tst_RenderViewUtils::topLevelStructValue() QVERIFY(backendShaderData != nullptr); // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; @@ -660,8 +660,8 @@ void tst_RenderViewUtils::topLevelStructValue() QCOMPARE(blockBuilder.activeUniformNamesToValue.count(), blockBuilder.uniforms.count()); // WHEN - Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); - const Qt3DRender::Render::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); + Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator it = blockBuilder.activeUniformNamesToValue.begin(); + const Qt3DRender::Render::OpenGL::UniformBlockValueBuilderHash::const_iterator end = blockBuilder.activeUniformNamesToValue.end(); while (it != end) { // THEN @@ -693,13 +693,13 @@ void tst_RenderViewUtils::topLevelDynamicProperties() QVERIFY(backendShaderData != nullptr); // WHEN - Qt3DRender::Render::UniformBlockValueBuilder blockBuilder; + Qt3DRender::Render::OpenGL::UniformBlockValueBuilder blockBuilder; blockBuilder.shaderDataManager = manager.data(); blockBuilder.textureManager = textureManager.data(); blockBuilder.updatedPropertiesOnly = false; - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.scalar"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0]"), Qt3DRender::Render::ShaderUniform()); - blockBuilder.uniforms.insert(QStringLiteral("MyBlock.texture"), Qt3DRender::Render::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.scalar"), Qt3DRender::Render::OpenGL::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.array[0]"), Qt3DRender::Render::OpenGL::ShaderUniform()); + blockBuilder.uniforms.insert(QStringLiteral("MyBlock.texture"), Qt3DRender::Render::OpenGL::ShaderUniform()); // build name-value map blockBuilder.buildActiveUniformNameValueMapStructHelper(backendShaderData, QStringLiteral("MyBlock")); diff --git a/tests/auto/render/opengl/textures/tst_textures.cpp b/tests/auto/render/opengl/textures/tst_textures.cpp index 984d49a3e..5343a6fde 100644 --- a/tests/auto/render/opengl/textures/tst_textures.cpp +++ b/tests/auto/render/opengl/textures/tst_textures.cpp @@ -222,7 +222,7 @@ private Q_SLOTS: { QSKIP("Texture Sharing is now disabled"); QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); renderer.setNodeManagers(mgrs.data()); // GIVEN @@ -250,7 +250,7 @@ private Q_SLOTS: void shouldCreateDifferentGLTexturess() { QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); renderer.setNodeManagers(mgrs.data()); // GIVEN @@ -281,7 +281,7 @@ private Q_SLOTS: QVERIFY(renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[i]->peerId()) != renderer.glResourceManagers()->glTextureManager()->lookupResource(backend[k]->peerId())); - QVector glTextures; + QVector glTextures; for (Qt3DRender::Render::Texture *t : backend) glTextures.push_back(renderer.glResourceManagers()->glTextureManager()->lookupResource(t->peerId())); @@ -306,10 +306,10 @@ private Q_SLOTS: void shouldCreateDifferentGLTexturesWhenUsingSharedTextureIds() { QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); renderer.setNodeManagers(mgrs.data()); - Qt3DRender::Render::GLResourceManagers *glMgrs = renderer.glResourceManagers(); + Qt3DRender::Render::OpenGL::GLResourceManagers *glMgrs = renderer.glResourceManagers(); // both texture having the same sharedTextureId { @@ -335,8 +335,8 @@ private Q_SLOTS: renderer.updateTexture(bt2); // THEN - Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); - Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); + Qt3DRender::Render::OpenGL::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); + Qt3DRender::Render::OpenGL::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); QVERIFY(glt1 != glt2); QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); @@ -366,8 +366,8 @@ private Q_SLOTS: renderer.updateTexture(bt2); // THEN - Qt3DRender::Render::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); - Qt3DRender::Render::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); + Qt3DRender::Render::OpenGL::GLTexture *glt1 = glMgrs->glTextureManager()->lookupResource(bt1->peerId()); + Qt3DRender::Render::OpenGL::GLTexture *glt2 = glMgrs->glTextureManager()->lookupResource(bt2->peerId()); QVERIFY(glt1 != glt2); QCOMPARE(glt1->sharedTextureId(), bt1->sharedTextureId()); QCOMPARE(glt2->sharedTextureId(), bt2->sharedTextureId()); @@ -379,7 +379,7 @@ private Q_SLOTS: void generatorsShouldCreateSameData() { QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); renderer.setNodeManagers(mgrs.data()); // GIVEN @@ -438,7 +438,7 @@ private Q_SLOTS: void checkTextureImageCleanupState() { // GIVEN - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); TestTextureImage img(1); img.setLayer(2); img.setMipLevel(3); @@ -462,7 +462,7 @@ private Q_SLOTS: void checkTextureImageInitializeFromPeer() { // GIVEN - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); TestTextureImage img(1); { @@ -594,7 +594,7 @@ private Q_SLOTS: void checkTextureImageProperlyReleaseGenerator() { QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); Qt3DRender::Render::TextureImageManager *texImgMgr = mgrs->textureImageManager(); renderer.setNodeManagers(mgrs.data()); @@ -634,7 +634,7 @@ private Q_SLOTS: void checkTextureIsMarkedForDeletion() { QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); renderer.setNodeManagers(mgrs.data()); @@ -668,7 +668,7 @@ private Q_SLOTS: void checkTextureDestructionReconstructionWithinSameLoop() { QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); renderer.setNodeManagers(mgrs.data()); @@ -707,7 +707,7 @@ private Q_SLOTS: { // GIVEN QScopedPointer mgrs(new Qt3DRender::Render::NodeManagers()); - Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); + Qt3DRender::Render::OpenGL::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous); Qt3DRender::Render::TextureManager *texMgr = mgrs->textureManager(); Qt3DRender::Render::TextureImageManager *texImgMgr = mgrs->textureImageManager(); renderer.setNodeManagers(mgrs.data()); diff --git a/tests/benchmarks/render/jobs/tst_bench_jobs.cpp b/tests/benchmarks/render/jobs/tst_bench_jobs.cpp index 87689e46c..85b5e8c89 100644 --- a/tests/benchmarks/render/jobs/tst_bench_jobs.cpp +++ b/tests/benchmarks/render/jobs/tst_bench_jobs.cpp @@ -87,32 +87,32 @@ namespace Qt3DRender { QVector worldTransformJob() { - static_cast(d_func()->m_renderer)->m_worldTransformJob->setRoot(d_func()->m_renderer->sceneRoot()); - return QVector() << static_cast(d_func()->m_renderer)->m_worldTransformJob; + static_cast(d_func()->m_renderer)->m_worldTransformJob->setRoot(d_func()->m_renderer->sceneRoot()); + return QVector() << static_cast(d_func()->m_renderer)->m_worldTransformJob; } QVector updateBoundingJob() { - static_cast(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob->setManager(d_func()->m_renderer->nodeManagers()->renderNodesManager()); - return QVector() << static_cast(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob; + static_cast(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob->setManager(d_func()->m_renderer->nodeManagers()->renderNodesManager()); + return QVector() << static_cast(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob; } QVector calculateBoundingVolumeJob() { - static_cast(d_func()->m_renderer)->m_calculateBoundingVolumeJob->setRoot(d_func()->m_renderer->sceneRoot()); - return QVector() << static_cast(d_func()->m_renderer)->m_calculateBoundingVolumeJob; + static_cast(d_func()->m_renderer)->m_calculateBoundingVolumeJob->setRoot(d_func()->m_renderer->sceneRoot()); + return QVector() << static_cast(d_func()->m_renderer)->m_calculateBoundingVolumeJob; } QVector framePreparationJob() { - static_cast(d_func()->m_renderer)->m_updateShaderDataTransformJob->setManagers(d_func()->m_renderer->nodeManagers()); - return QVector() << static_cast(d_func()->m_renderer)->m_updateShaderDataTransformJob; + static_cast(d_func()->m_renderer)->m_updateShaderDataTransformJob->setManagers(d_func()->m_renderer->nodeManagers()); + return QVector() << static_cast(d_func()->m_renderer)->m_updateShaderDataTransformJob; } QVector frameCleanupJob() { - static_cast(d_func()->m_renderer)->m_cleanupJob->setRoot(d_func()->m_renderer->sceneRoot()); - return QVector() << static_cast(d_func()->m_renderer)->m_cleanupJob; + static_cast(d_func()->m_renderer)->m_cleanupJob->setRoot(d_func()->m_renderer->sceneRoot()); + return QVector() << static_cast(d_func()->m_renderer)->m_cleanupJob; } QVector renderBinJobs() @@ -140,7 +140,7 @@ namespace Qt3DRender { for (const auto &node: nodes) d_func()->createBackendNode(node); - static_cast(d_func()->m_renderer)->m_renderSceneRoot = + static_cast(d_func()->m_renderer)->m_renderSceneRoot = d_func()->m_renderer->nodeManagers() ->lookupResource(root->id()); } diff --git a/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp b/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp index 644c4d74c..340bfdda4 100644 --- a/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp +++ b/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp @@ -90,9 +90,9 @@ public: return d_func()->m_renderer->nodeManagers(); } - Render::MaterialParameterGathererJobPtr materialGathererJob() const + Render::OpenGL::MaterialParameterGathererJobPtr materialGathererJob() const { - Render::MaterialParameterGathererJobPtr job = Render::MaterialParameterGathererJobPtr::create(); + Render::OpenGL::MaterialParameterGathererJobPtr job = Render::OpenGL::MaterialParameterGathererJobPtr::create(); job->setNodeManagers(nodeManagers()); return job; } @@ -136,7 +136,7 @@ private Q_SLOTS: QScopedPointer aspect(new Qt3DRender::TestAspect(buildTestScene(2000))); // WHEN - Qt3DRender::Render::MaterialParameterGathererJobPtr gatheringJob = aspect->materialGathererJob(); + Qt3DRender::Render::OpenGL::MaterialParameterGathererJobPtr gatheringJob = aspect->materialGathererJob(); gatheringJob->setHandles(aspect->nodeManagers()->materialManager()->activeHandles()); QBENCHMARK { -- cgit v1.2.3 From cd87206dfd6bf0eb93519f9c7cf347dea424278e Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Tue, 13 Mar 2018 09:46:42 +0100 Subject: Use QT3D_RENDERER env var to load different renderer plugins Change-Id: Ib66ebc77f4926b2ea1e956762ec0f286162a95e6 Reviewed-by: Paul Lemire --- src/render/frontend/qrenderaspect.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/render/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp index f043b9894..fc366b891 100644 --- a/src/render/frontend/qrenderaspect.cpp +++ b/src/render/frontend/qrenderaspect.cpp @@ -699,13 +699,19 @@ Render::AbstractRenderer *QRenderAspectPrivate::loadRendererPlugin() // Note: for now we load the first renderer plugin that is successfully loaded // In the future we might want to offer the user a way to hint at which renderer // plugin would best be loaded + + const QByteArray envTarget = qgetenv("QT3D_RENDERER"); + const QString targetKey = !envTarget.isEmpty() ? QString::fromLatin1(envTarget) : QStringLiteral("opengl"); const QStringList keys = Render::QRendererPluginFactory::keys(); for (const QString &key : keys) { + if (key != targetKey) + continue; Render::AbstractRenderer *renderer = Render::QRendererPluginFactory::create(key, m_renderType); if (renderer) return renderer; } - qFatal("Unable to load a renderer plugin"); + const QByteArray targetKeyName = targetKey.toLatin1(); + qFatal("Unable to find renderer plugin for %s", targetKeyName.constData()); return nullptr; } -- cgit v1.2.3 From 64457740e0da484c79826e6b8286851e6aa8df1f Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Mon, 3 Feb 2020 17:11:26 +0000 Subject: Move frame profile to GL plugin It's only used there and depends on OpenGL Change-Id: If3d93fd0b12a6f41a751beb12b89d6763107de1b Reviewed-by: Paul Lemire --- .../renderers/opengl/renderer/frameprofiler_p.h | 272 +++++++++++++++++++++ src/plugins/renderers/opengl/renderer/renderer.cpp | 2 +- src/plugins/renderers/opengl/renderer/renderer.pri | 4 +- src/render/backend/frameprofiler_p.h | 272 --------------------- src/render/backend/render-backend.pri | 1 - 5 files changed, 276 insertions(+), 275 deletions(-) create mode 100644 src/plugins/renderers/opengl/renderer/frameprofiler_p.h delete mode 100644 src/render/backend/frameprofiler_p.h diff --git a/src/plugins/renderers/opengl/renderer/frameprofiler_p.h b/src/plugins/renderers/opengl/renderer/frameprofiler_p.h new file mode 100644 index 000000000..59c9b68b6 --- /dev/null +++ b/src/plugins/renderers/opengl/renderer/frameprofiler_p.h @@ -0,0 +1,272 @@ +/**************************************************************************** +** +** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT3DRENDER_RENDER_FRAMEPROFILER_P_H +#define QT3DRENDER_RENDER_FRAMEPROFILER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +#if !defined(QT_NO_OPENGL) && !defined(QT_OPENGL_ES_2) +#define QT3D_SUPPORTS_GL_MONITOR +#endif + +namespace Qt3DCore { +class QSystemInformationService; +} + +namespace Qt3DRender { + +namespace Render { + +namespace Profiling { + +enum RecordingType +{ + DrawArray = 512, + DrawElement, + DispatchCompute, + StateUpdate, + UniformUpdate, + ShaderUpdate, + TextureUpload, + BufferUpload, + ShaderUpload, + ClearBuffer, + VAOUpdate, + VAOUpload, + RenderTargetUpdate +}; + +class FrameTimeRecorder +{ +public: + FrameTimeRecorder(Qt3DCore::QSystemInformationService *service) + : m_service(service) + { + } + + ~FrameTimeRecorder() + { + } + + void init(int eventCount) + { +#ifdef QT3D_SUPPORTS_GL_MONITOR + if (m_monitor.isCreated()) { + m_remainingEvents = m_monitor.sampleCount(); + reset(); + } else { + m_monitor.setSampleCount(eventCount * 2); + m_monitor.create(); + m_remainingEvents = eventCount; + } +#else + m_remainingEvents = eventCount; +#endif + } + + void startRecordEvent() + { +#ifdef QT3D_SUPPORTS_GL_MONITOR + m_monitor.recordSample(); +#endif + --m_remainingEvents; + } + + void recordEvent(RecordingType type) + { +#ifdef QT3D_SUPPORTS_GL_MONITOR + m_monitor.recordSample(); +#endif + --m_remainingEvents; + + GLRecording rec; + rec.type = type; + rec.startTime = Qt3DCore::QSystemInformationServicePrivate::get(m_service)->m_jobsStatTimer.nsecsElapsed(); + m_recordings.push_back(rec); + } + + void reset() + { +#ifdef QT3D_SUPPORTS_GL_MONITOR + m_monitor.reset(); +#endif + m_recordings.clear(); + } + + inline bool canStillRecord() { return m_remainingEvents > 0; } + + bool tryWriteResults() + { +#ifdef QT3D_SUPPORTS_GL_MONITOR + if (m_monitor.isResultAvailable()) { + const QVector samples = m_monitor.waitForSamples(); + Q_ASSERT(samples.count() >= 2 * m_recordings.count()); + + Qt3DCore::QSystemInformationServicePrivate *dservice = Qt3DCore::QSystemInformationServicePrivate::get(m_service); + + int j = 0; + for (int i = 0, m = m_recordings.size(); i < m; ++i) { + const GLRecording rec = m_recordings.at(i); + Qt3DCore::QSystemInformationServicePrivate::JobRunStats glRecordingStat; + + glRecordingStat.jobId.typeAndInstance[0] = rec.type; + glRecordingStat.jobId.typeAndInstance[1] = 0; + glRecordingStat.threadId = FrameTimeRecorder::GLThreadID; + glRecordingStat.startTime = rec.startTime; + glRecordingStat.endTime = rec.startTime + (samples.at(j + 1) - (samples.at(j))); + + dservice->addSubmissionLogStatsEntry(glRecordingStat); + j += 2; + } + return true; + } +#endif + return false; + } + +private: + struct GLRecording + { + RecordingType type; + qint64 startTime; + }; + + static const int GLThreadID = 0x454; + + Qt3DCore::QSystemInformationService *m_service; +#ifdef QT3D_SUPPORTS_GL_MONITOR + QOpenGLTimeMonitor m_monitor; +#endif + QVector m_recordings; + int m_remainingEvents = 0; +}; + +class FrameProfiler +{ +public: + FrameProfiler(Qt3DCore::QSystemInformationService *service) + : m_service(service) + , m_currentRecorder(nullptr) + {} + + ~FrameProfiler() + { + qDeleteAll(m_recorders); + } + + void startRecordEvent() + { + if (m_currentRecorder == nullptr) { + if (!m_availableRecorders.empty()) { + m_currentRecorder = m_availableRecorders.takeFirst(); + } else { + m_recorders.push_back(new FrameTimeRecorder(m_service)); + m_currentRecorder = m_recorders.last(); + } + // We record events 10 by 10 + m_currentRecorder->init(10); + } + m_currentRecorder->startRecordEvent(); + } + + void recordEvent(RecordingType type) + { + m_currentRecorder->recordEvent(type); + if (!m_currentRecorder->canStillRecord()) { + m_busyRecorders.push_back(m_currentRecorder); + m_currentRecorder = nullptr; + } + } + + void writeResults() + { + for (int i = m_busyRecorders.size() - 1; i >= 0; --i) { + FrameTimeRecorder *recorder = m_busyRecorders.at(i); + if (recorder->tryWriteResults()) { + m_availableRecorders.push_back(m_busyRecorders.takeAt(i)); + } + } + } + +private: + Qt3DCore::QSystemInformationService *m_service; + QVector m_recorders; + QVector m_availableRecorders; + QVector m_busyRecorders; + FrameTimeRecorder *m_currentRecorder; +}; + + +class GLTimeRecorder +{ +public: + explicit GLTimeRecorder(RecordingType type, FrameProfiler *profiler) + : m_type(type) + , m_frameProfiler(profiler) + { + if (m_frameProfiler) + m_frameProfiler->startRecordEvent(); + } + + ~GLTimeRecorder() + { + if (m_frameProfiler) + m_frameProfiler->recordEvent(m_type); + } + +private: + RecordingType m_type; + FrameProfiler *m_frameProfiler; +}; + +} // Profiling + +} // Render + +} // Qt3DRender + +QT_END_NAMESPACE + +#endif // QT3DRENDER_RENDER_FRAMEPROFILER_P_H diff --git a/src/plugins/renderers/opengl/renderer/renderer.cpp b/src/plugins/renderers/opengl/renderer/renderer.cpp index 151483348..d01f22847 100644 --- a/src/plugins/renderers/opengl/renderer/renderer.cpp +++ b/src/plugins/renderers/opengl/renderer/renderer.cpp @@ -123,7 +123,7 @@ #include #include -#include +#include "frameprofiler_p.h" QT_BEGIN_NAMESPACE diff --git a/src/plugins/renderers/opengl/renderer/renderer.pri b/src/plugins/renderers/opengl/renderer/renderer.pri index 0f68aa481..3e3f83c86 100644 --- a/src/plugins/renderers/opengl/renderer/renderer.pri +++ b/src/plugins/renderers/opengl/renderer/renderer.pri @@ -25,4 +25,6 @@ HEADERS += \ $$PWD/glshader_p.h \ $$PWD/glfence_p.h \ $$PWD/logging_p.h \ - $$PWD/commandexecuter_p.h + $$PWD/commandexecuter_p.h \ + $$PWD/frameprofiler_p.h + diff --git a/src/render/backend/frameprofiler_p.h b/src/render/backend/frameprofiler_p.h deleted file mode 100644 index 59c9b68b6..000000000 --- a/src/render/backend/frameprofiler_p.h +++ /dev/null @@ -1,272 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the Qt3D module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:GPL-EXCEPT$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT3DRENDER_RENDER_FRAMEPROFILER_P_H -#define QT3DRENDER_RENDER_FRAMEPROFILER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -#if !defined(QT_NO_OPENGL) && !defined(QT_OPENGL_ES_2) -#define QT3D_SUPPORTS_GL_MONITOR -#endif - -namespace Qt3DCore { -class QSystemInformationService; -} - -namespace Qt3DRender { - -namespace Render { - -namespace Profiling { - -enum RecordingType -{ - DrawArray = 512, - DrawElement, - DispatchCompute, - StateUpdate, - UniformUpdate, - ShaderUpdate, - TextureUpload, - BufferUpload, - ShaderUpload, - ClearBuffer, - VAOUpdate, - VAOUpload, - RenderTargetUpdate -}; - -class FrameTimeRecorder -{ -public: - FrameTimeRecorder(Qt3DCore::QSystemInformationService *service) - : m_service(service) - { - } - - ~FrameTimeRecorder() - { - } - - void init(int eventCount) - { -#ifdef QT3D_SUPPORTS_GL_MONITOR - if (m_monitor.isCreated()) { - m_remainingEvents = m_monitor.sampleCount(); - reset(); - } else { - m_monitor.setSampleCount(eventCount * 2); - m_monitor.create(); - m_remainingEvents = eventCount; - } -#else - m_remainingEvents = eventCount; -#endif - } - - void startRecordEvent() - { -#ifdef QT3D_SUPPORTS_GL_MONITOR - m_monitor.recordSample(); -#endif - --m_remainingEvents; - } - - void recordEvent(RecordingType type) - { -#ifdef QT3D_SUPPORTS_GL_MONITOR - m_monitor.recordSample(); -#endif - --m_remainingEvents; - - GLRecording rec; - rec.type = type; - rec.startTime = Qt3DCore::QSystemInformationServicePrivate::get(m_service)->m_jobsStatTimer.nsecsElapsed(); - m_recordings.push_back(rec); - } - - void reset() - { -#ifdef QT3D_SUPPORTS_GL_MONITOR - m_monitor.reset(); -#endif - m_recordings.clear(); - } - - inline bool canStillRecord() { return m_remainingEvents > 0; } - - bool tryWriteResults() - { -#ifdef QT3D_SUPPORTS_GL_MONITOR - if (m_monitor.isResultAvailable()) { - const QVector samples = m_monitor.waitForSamples(); - Q_ASSERT(samples.count() >= 2 * m_recordings.count()); - - Qt3DCore::QSystemInformationServicePrivate *dservice = Qt3DCore::QSystemInformationServicePrivate::get(m_service); - - int j = 0; - for (int i = 0, m = m_recordings.size(); i < m; ++i) { - const GLRecording rec = m_recordings.at(i); - Qt3DCore::QSystemInformationServicePrivate::JobRunStats glRecordingStat; - - glRecordingStat.jobId.typeAndInstance[0] = rec.type; - glRecordingStat.jobId.typeAndInstance[1] = 0; - glRecordingStat.threadId = FrameTimeRecorder::GLThreadID; - glRecordingStat.startTime = rec.startTime; - glRecordingStat.endTime = rec.startTime + (samples.at(j + 1) - (samples.at(j))); - - dservice->addSubmissionLogStatsEntry(glRecordingStat); - j += 2; - } - return true; - } -#endif - return false; - } - -private: - struct GLRecording - { - RecordingType type; - qint64 startTime; - }; - - static const int GLThreadID = 0x454; - - Qt3DCore::QSystemInformationService *m_service; -#ifdef QT3D_SUPPORTS_GL_MONITOR - QOpenGLTimeMonitor m_monitor; -#endif - QVector m_recordings; - int m_remainingEvents = 0; -}; - -class FrameProfiler -{ -public: - FrameProfiler(Qt3DCore::QSystemInformationService *service) - : m_service(service) - , m_currentRecorder(nullptr) - {} - - ~FrameProfiler() - { - qDeleteAll(m_recorders); - } - - void startRecordEvent() - { - if (m_currentRecorder == nullptr) { - if (!m_availableRecorders.empty()) { - m_currentRecorder = m_availableRecorders.takeFirst(); - } else { - m_recorders.push_back(new FrameTimeRecorder(m_service)); - m_currentRecorder = m_recorders.last(); - } - // We record events 10 by 10 - m_currentRecorder->init(10); - } - m_currentRecorder->startRecordEvent(); - } - - void recordEvent(RecordingType type) - { - m_currentRecorder->recordEvent(type); - if (!m_currentRecorder->canStillRecord()) { - m_busyRecorders.push_back(m_currentRecorder); - m_currentRecorder = nullptr; - } - } - - void writeResults() - { - for (int i = m_busyRecorders.size() - 1; i >= 0; --i) { - FrameTimeRecorder *recorder = m_busyRecorders.at(i); - if (recorder->tryWriteResults()) { - m_availableRecorders.push_back(m_busyRecorders.takeAt(i)); - } - } - } - -private: - Qt3DCore::QSystemInformationService *m_service; - QVector m_recorders; - QVector m_availableRecorders; - QVector m_busyRecorders; - FrameTimeRecorder *m_currentRecorder; -}; - - -class GLTimeRecorder -{ -public: - explicit GLTimeRecorder(RecordingType type, FrameProfiler *profiler) - : m_type(type) - , m_frameProfiler(profiler) - { - if (m_frameProfiler) - m_frameProfiler->startRecordEvent(); - } - - ~GLTimeRecorder() - { - if (m_frameProfiler) - m_frameProfiler->recordEvent(m_type); - } - -private: - RecordingType m_type; - FrameProfiler *m_frameProfiler; -}; - -} // Profiling - -} // Render - -} // Qt3DRender - -QT_END_NAMESPACE - -#endif // QT3DRENDER_RENDER_FRAMEPROFILER_P_H diff --git a/src/render/backend/render-backend.pri b/src/render/backend/render-backend.pri index 2815ee0ab..4e46aa65b 100644 --- a/src/render/backend/render-backend.pri +++ b/src/render/backend/render-backend.pri @@ -31,7 +31,6 @@ HEADERS += \ $$PWD/backendnode_p.h \ $$PWD/rendertargetoutput_p.h \ $$PWD/uniform_p.h \ - $$PWD/frameprofiler_p.h \ $$PWD/offscreensurfacehelper_p.h \ $$PWD/resourceaccessor_p.h \ $$PWD/visitorutils_p.h \ -- cgit v1.2.3 From 0159963cf5072e05d068fd7a9b58085ac70021c1 Mon Sep 17 00:00:00 2001 From: Mike Krus Date: Mon, 3 Feb 2020 16:39:14 +0000 Subject: Remove QtGui module path from OpenGL related paths Many are moving to opengl module in qt6, will make merging easier. Change-Id: I0ad08510e6999a5d887d9197fe2cb0dc21919fb9 Reviewed-by: Paul Lemire --- examples/qt3d/audio-visualizer-qml/main.cpp | 2 +- src/animation/backend/gltfimporter.cpp | 2 +- src/extras/defaults/qt3dwindow.cpp | 2 +- src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp | 2 +- src/plugins/renderers/opengl/textures/renderbuffer.cpp | 4 ++-- src/quick3d/imports/scene3d/scene3drenderer.cpp | 4 ++-- src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp | 4 ++-- src/quick3d/quick3dextras/qt3dquickwindow.cpp | 2 +- src/render/backend/abstractrenderer_p.h | 2 +- src/render/geometry/gltfskeletonloader.cpp | 2 +- src/render/texture/qtextureimagedata.h | 2 +- tests/auto/extras/qcuboidgeometry/tst_qcuboidgeometry.cpp | 2 +- tests/auto/extras/qtorusgeometry/tst_qtorusgeometry.cpp | 2 +- tests/auto/render/qgraphicsapifilter/tst_qgraphicsapifilter.cpp | 2 +- 14 files changed, 17 insertions(+), 17 deletions(-) diff --git a/examples/qt3d/audio-visualizer-qml/main.cpp b/examples/qt3d/audio-visualizer-qml/main.cpp index c3fe2c009..5759dfe71 100644 --- a/examples/qt3d/audio-visualizer-qml/main.cpp +++ b/examples/qt3d/audio-visualizer-qml/main.cpp @@ -50,7 +50,7 @@ #include "touchsettings.h" #include -#include +#include #include #include #include diff --git a/src/animation/backend/gltfimporter.cpp b/src/animation/backend/gltfimporter.cpp index a5127efd0..f7907b3c2 100644 --- a/src/animation/backend/gltfimporter.cpp +++ b/src/animation/backend/gltfimporter.cpp @@ -42,7 +42,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/extras/defaults/qt3dwindow.cpp b/src/extras/defaults/qt3dwindow.cpp index 04b8554f1..f555308a6 100644 --- a/src/extras/defaults/qt3dwindow.cpp +++ b/src/extras/defaults/qt3dwindow.cpp @@ -60,7 +60,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp b/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp index 8adb70f96..2c8bb14c3 100644 --- a/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp +++ b/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp @@ -44,7 +44,7 @@ #include #include -#include +#include #include #include diff --git a/src/plugins/renderers/opengl/textures/renderbuffer.cpp b/src/plugins/renderers/opengl/textures/renderbuffer.cpp index 330e29472..05d6bd1fa 100644 --- a/src/plugins/renderers/opengl/textures/renderbuffer.cpp +++ b/src/plugins/renderers/opengl/textures/renderbuffer.cpp @@ -38,8 +38,8 @@ ****************************************************************************/ #include "renderbuffer_p.h" -#include -#include +#include +#include QT_BEGIN_NAMESPACE diff --git a/src/quick3d/imports/scene3d/scene3drenderer.cpp b/src/quick3d/imports/scene3d/scene3drenderer.cpp index fafeeedf4..71cf6c240 100644 --- a/src/quick3d/imports/scene3d/scene3drenderer.cpp +++ b/src/quick3d/imports/scene3d/scene3drenderer.cpp @@ -42,8 +42,8 @@ #include #include #include -#include -#include +#include +#include #include #include diff --git a/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp b/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp index cfe39e8c7..b7dd03810 100644 --- a/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp +++ b/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp @@ -39,8 +39,8 @@ #include "scene3dsgmaterialshader_p.h" -#include -#include +#include +#include #include #include diff --git a/src/quick3d/quick3dextras/qt3dquickwindow.cpp b/src/quick3d/quick3dextras/qt3dquickwindow.cpp index 043aca8b9..dfe245936 100644 --- a/src/quick3d/quick3dextras/qt3dquickwindow.cpp +++ b/src/quick3d/quick3dextras/qt3dquickwindow.cpp @@ -60,7 +60,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/render/backend/abstractrenderer_p.h b/src/render/backend/abstractrenderer_p.h index 3febf691e..4e25d627f 100644 --- a/src/render/backend/abstractrenderer_p.h +++ b/src/render/backend/abstractrenderer_p.h @@ -58,7 +58,7 @@ #include #include -#include +#include QT_BEGIN_NAMESPACE diff --git a/src/render/geometry/gltfskeletonloader.cpp b/src/render/geometry/gltfskeletonloader.cpp index 07789cd84..d5d344ce1 100644 --- a/src/render/geometry/gltfskeletonloader.cpp +++ b/src/render/geometry/gltfskeletonloader.cpp @@ -36,7 +36,7 @@ #include "gltfskeletonloader_p.h" -#include +#include #include #include #include diff --git a/src/render/texture/qtextureimagedata.h b/src/render/texture/qtextureimagedata.h index 68ceebabc..5bc71480e 100644 --- a/src/render/texture/qtextureimagedata.h +++ b/src/render/texture/qtextureimagedata.h @@ -40,7 +40,7 @@ #ifndef QT3DRENDER_TEXTUREIMAGEDATA_H #define QT3DRENDER_TEXTUREIMAGEDATA_H -#include +#include #include #include #include diff --git a/tests/auto/extras/qcuboidgeometry/tst_qcuboidgeometry.cpp b/tests/auto/extras/qcuboidgeometry/tst_qcuboidgeometry.cpp index 973a1d613..838e5dea9 100644 --- a/tests/auto/extras/qcuboidgeometry/tst_qcuboidgeometry.cpp +++ b/tests/auto/extras/qcuboidgeometry/tst_qcuboidgeometry.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/tests/auto/extras/qtorusgeometry/tst_qtorusgeometry.cpp b/tests/auto/extras/qtorusgeometry/tst_qtorusgeometry.cpp index 28fe76ae9..bf5651c9c 100644 --- a/tests/auto/extras/qtorusgeometry/tst_qtorusgeometry.cpp +++ b/tests/auto/extras/qtorusgeometry/tst_qtorusgeometry.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/tests/auto/render/qgraphicsapifilter/tst_qgraphicsapifilter.cpp b/tests/auto/render/qgraphicsapifilter/tst_qgraphicsapifilter.cpp index bbc5219f8..ea14c27bb 100644 --- a/tests/auto/render/qgraphicsapifilter/tst_qgraphicsapifilter.cpp +++ b/tests/auto/render/qgraphicsapifilter/tst_qgraphicsapifilter.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include -- cgit v1.2.3 From a054e92ba05a32d13b91908597618b43709c5f68 Mon Sep 17 00:00:00 2001 From: Paul Lemire Date: Thu, 6 Feb 2020 06:46:21 +0100 Subject: tst_qresoucemanager: add test to make sure cleanup is working Change-Id: I5006778b74fee6d030f65deaba86bb38a7a0a86b Reviewed-by: Mike Krus --- .../core/qresourcemanager/tst_qresourcemanager.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/auto/core/qresourcemanager/tst_qresourcemanager.cpp b/tests/auto/core/qresourcemanager/tst_qresourcemanager.cpp index 9a387a919..a41ea83b5 100644 --- a/tests/auto/core/qresourcemanager/tst_qresourcemanager.cpp +++ b/tests/auto/core/qresourcemanager/tst_qresourcemanager.cpp @@ -50,6 +50,7 @@ private slots: void heavyDutyMultiThreadedAccessRelease(); void collectResources(); void activeHandles(); + void checkCleanup(); }; class tst_ArrayResource @@ -422,6 +423,26 @@ void tst_QResourceManager::activeHandles() } } +void tst_QResourceManager::checkCleanup() +{ + // GIVEN + Qt3DCore::QResourceManager manager; + + // WHEN + tHandle newHandle = manager.getOrAcquireHandle(883U); + tst_ArrayResource *data = manager.data(newHandle); + + data->m_value.ref(); + // THEN + QCOMPARE(data->m_value.load(), 1); + + // WHEN + manager.release(newHandle); + + // THEN + QCOMPARE(data->m_value.load(), 0); +} + -- cgit v1.2.3 From fa6799f63f3211300705b814b97716ca689d4bfa Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Tue, 28 Jan 2020 13:22:25 +0100 Subject: Remove unneeded export of inline functions Fix MinGW-warings src/core/transforms/matrix4x4_sse_p.h:485:50: warning: inline function 'Vector3D Qt3DCore::operator*(const Qt3DCore::Matrix4x4_SSE&, const Vector3D&)' declared as dllimport: attribute ignored [-Wattributes] Q_3DCORE_PRIVATE_EXPORT Q_ALWAYS_INLINE Vector3D operator*(const Matrix4x4_SSE &matrix, const Vector3D &vector) Change-Id: Ib8b39c613ce05b6dc3848c1251a88eea53903212 Reviewed-by: Paul Lemire --- src/core/transforms/matrix4x4_sse_p.h | 2 +- src/core/transforms/vector3d_sse_p.h | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/transforms/matrix4x4_sse_p.h b/src/core/transforms/matrix4x4_sse_p.h index adef74daf..2531616a0 100644 --- a/src/core/transforms/matrix4x4_sse_p.h +++ b/src/core/transforms/matrix4x4_sse_p.h @@ -483,7 +483,7 @@ Q_ALWAYS_INLINE Vector3D operator*(const Vector3D &vector, const Matrix4x4_SSE & return v; } -Q_3DCORE_PRIVATE_EXPORT Q_ALWAYS_INLINE Vector3D operator*(const Matrix4x4_SSE &matrix, const Vector3D &vector) +Q_ALWAYS_INLINE Vector3D operator*(const Matrix4x4_SSE &matrix, const Vector3D &vector) { const Matrix4x4_SSE transposed = matrix.transposed(); return vector * transposed; diff --git a/src/core/transforms/vector3d_sse_p.h b/src/core/transforms/vector3d_sse_p.h index bc25cd705..290cdfd3f 100644 --- a/src/core/transforms/vector3d_sse_p.h +++ b/src/core/transforms/vector3d_sse_p.h @@ -350,13 +350,13 @@ public: #ifdef __AVX2__ friend class Matrix4x4_AVX2; - friend Q_3DCORE_PRIVATE_EXPORT Vector3D_SSE operator*(const Vector3D_SSE &vector, const Matrix4x4_AVX2 &matrix); - friend Q_3DCORE_PRIVATE_EXPORT Vector3D_SSE operator*(const Matrix4x4_AVX2 &matrix, const Vector3D_SSE &vector); + friend Vector3D_SSE operator*(const Vector3D_SSE &vector, const Matrix4x4_AVX2 &matrix); + friend Vector3D_SSE operator*(const Matrix4x4_AVX2 &matrix, const Vector3D_SSE &vector); #endif friend class Matrix4x4_SSE; - friend Q_3DCORE_PRIVATE_EXPORT Vector3D_SSE operator*(const Vector3D_SSE &vector, const Matrix4x4_SSE &matrix); - friend Q_3DCORE_PRIVATE_EXPORT Vector3D_SSE operator*(const Matrix4x4_SSE &matrix, const Vector3D_SSE &vector); + friend Vector3D_SSE operator*(const Vector3D_SSE &vector, const Matrix4x4_SSE &matrix); + friend Vector3D_SSE operator*(const Matrix4x4_SSE &matrix, const Vector3D_SSE &vector); friend Q_ALWAYS_INLINE const Vector3D_SSE operator+(Vector3D_SSE v1, Vector3D_SSE v2) { return v1 += v2; } friend Q_ALWAYS_INLINE const Vector3D_SSE operator-(Vector3D_SSE v1, Vector3D_SSE v2) { return v1 -= v2; } -- cgit v1.2.3