summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMike Krus <mike.krus@kdab.com>2020-02-07 18:08:29 +0000
committerMike Krus <mike.krus@kdab.com>2020-02-07 18:10:43 +0000
commitb0eb152b82cdd9658154ff7d9ef9e764eccc1ebd (patch)
treed754ad4412d5c1d26caedd54f2455f3e27cbbd46
parent137b0cbbc746eecc6dd6a93f9a268f8d42c96bcc (diff)
parentfa6799f63f3211300705b814b97716ca689d4bfa (diff)
Merge remote-tracking branch 5.15 into dev
-rw-r--r--dist/changes-5.13.220
-rw-r--r--dist/changes-5.14.049
-rw-r--r--dist/changes-5.14.120
-rw-r--r--examples/qt3d/advancedcustommaterial/doc/src/advancedcustommaterial.qdoc6
-rw-r--r--examples/qt3d/audio-visualizer-qml/doc/src/audio-visualizer-qml.qdoc8
-rw-r--r--examples/qt3d/planets-qml/SolarSystem.qml14
-rw-r--r--examples/qt3d/planets-qml/android/AndroidManifest.xml8
-rw-r--r--examples/qt3d/planets-qml/doc/src/planets-qml.qdoc14
-rw-r--r--examples/qt3d/planets-qml/planets.js32
-rw-r--r--examples/qt3d/scene3d/AnimatedEntity.qml7
-rw-r--r--examples/qt3d/scene3d/main.cpp16
-rw-r--r--examples/qt3d/scene3d/main.qml50
-rw-r--r--examples/qt3d/simple-qml/main.qml3
-rw-r--r--examples/qt3d/simplecustommaterial/doc/src/simplecustommaterial.qdoc2
-rw-r--r--qt3d.pro3
-rw-r--r--src/3rdparty/imgui/LICENSE.txt21
-rw-r--r--src/3rdparty/imgui/imconfig.h73
-rw-r--r--src/3rdparty/imgui/imgui.cpp9091
-rw-r--r--src/3rdparty/imgui/imgui.h2050
-rw-r--r--src/3rdparty/imgui/imgui.pri9
-rw-r--r--src/3rdparty/imgui/imgui_draw.cpp3156
-rw-r--r--src/3rdparty/imgui/imgui_internal.h1331
-rw-r--r--src/3rdparty/imgui/imgui_widgets.cpp5744
-rw-r--r--src/3rdparty/imgui/imstb_rectpack.h623
-rw-r--r--src/3rdparty/imgui/imstb_textedit.h1409
-rw-r--r--src/3rdparty/imgui/imstb_truetype.h4854
-rw-r--r--src/3rdparty/imgui/qt_attribution.json16
-rw-r--r--src/animation/animation.pro1
-rw-r--r--src/animation/backend/abstractevaluateclipanimatorjob.cpp5
-rw-r--r--src/animation/backend/animationclip.cpp2
-rw-r--r--src/animation/backend/buildblendtreesjob.cpp3
-rw-r--r--src/animation/backend/channelmapping.cpp4
-rw-r--r--src/animation/backend/evaluateblendclipanimatorjob.cpp1
-rw-r--r--src/animation/backend/evaluateclipanimatorjob.cpp1
-rw-r--r--src/animation/backend/findrunningclipanimatorsjob.cpp3
-rw-r--r--src/animation/backend/gltfimporter.cpp8
-rw-r--r--src/animation/backend/loadanimationclipjob.cpp1
-rw-r--r--src/animation/backend/skeleton.cpp1
-rw-r--r--src/animation/frontend/qabstractanimationclip.cpp8
-rw-r--r--src/animation/frontend/qabstractanimationclip.h3
-rw-r--r--src/animation/frontend/qabstractchannelmapping.cpp1
-rw-r--r--src/animation/frontend/qabstractclipanimator.cpp5
-rw-r--r--src/animation/frontend/qabstractclipanimator.h2
-rw-r--r--src/animation/frontend/qanimationcallback.qdoc51
-rw-r--r--src/animation/frontend/qanimationclip.cpp4
-rw-r--r--src/animation/frontend/qanimationclipdata.cpp2
-rw-r--r--src/animation/frontend/qanimationcliploader.cpp6
-rw-r--r--src/animation/frontend/qanimationcliploader.h2
-rw-r--r--src/animation/frontend/qcallbackmapping.cpp2
-rw-r--r--src/animation/frontend/qchannel.cpp2
-rw-r--r--src/animation/frontend/qchannelmapper.cpp2
-rw-r--r--src/animation/frontend/qchannelmapping.cpp2
-rw-r--r--src/animation/frontend/qclipanimator.cpp3
-rw-r--r--src/animation/frontend/qclipblendvalue.cpp4
-rw-r--r--src/animation/frontend/qmorphtarget.cpp4
-rw-r--r--src/animation/frontend/qvertexblendanimation.cpp4
-rw-r--r--src/core/aspects/aspectcommanddebugger.cpp20
-rw-r--r--src/core/aspects/aspectcommanddebugger_p.h18
-rw-r--r--src/core/aspects/aspects.pri12
-rw-r--r--src/core/aspects/qabstractaspect.cpp24
-rw-r--r--src/core/aspects/qabstractaspect.h3
-rw-r--r--src/core/aspects/qabstractaspect_p.h3
-rw-r--r--src/core/aspects/qaspectengine.cpp24
-rw-r--r--src/core/aspects/qaspectengine_p.h10
-rw-r--r--src/core/aspects/qaspectmanager.cpp167
-rw-r--r--src/core/aspects/qaspectmanager_p.h16
-rw-r--r--src/core/changes/qcomponentaddedchange.h10
-rw-r--r--src/core/changes/qcomponentremovedchange.h10
-rw-r--r--src/core/changes/qdynamicpropertyupdatedchange.h4
-rw-r--r--src/core/changes/qnodecommand.h2
-rw-r--r--src/core/changes/qnodecreatedchange.h5
-rw-r--r--src/core/changes/qnodedestroyedchange.h4
-rw-r--r--src/core/changes/qpropertynodeaddedchange.h4
-rw-r--r--src/core/changes/qpropertynoderemovedchange.h4
-rw-r--r--src/core/changes/qpropertyupdatedchange.h4
-rw-r--r--src/core/changes/qpropertyupdatedchangebase.h4
-rw-r--r--src/core/changes/qpropertyvalueaddedchange.h4
-rw-r--r--src/core/changes/qpropertyvalueaddedchangebase.h6
-rw-r--r--src/core/changes/qpropertyvalueremovedchange.h4
-rw-r--r--src/core/changes/qpropertyvalueremovedchangebase.h6
-rw-r--r--src/core/changes/qscenechange.cpp1
-rw-r--r--src/core/changes/qscenechange.h26
-rw-r--r--src/core/changes/qscenechange_p.h13
-rw-r--r--src/core/changes/qskeletoncreatedchange_p.h7
-rw-r--r--src/core/changes/qstaticpropertyupdatedchangebase.h6
-rw-r--r--src/core/changes/qstaticpropertyvalueaddedchangebase.h2
-rw-r--r--src/core/changes/qstaticpropertyvalueremovedchangebase.h2
-rw-r--r--src/core/changes/qtypedpropertyupdatechange_p.h3
-rw-r--r--src/core/configure.json3
-rw-r--r--src/core/core.pro1
-rw-r--r--src/core/jobs/qaspectjob_p.h67
-rw-r--r--src/core/jobs/qaspectjobmanager.cpp14
-rw-r--r--src/core/jobs/qaspectjobmanager_p.h4
-rw-r--r--src/core/jobs/qaspectjobproviderinterface_p.h2
-rw-r--r--src/core/jobs/qthreadpooler.cpp128
-rw-r--r--src/core/jobs/qthreadpooler_p.h17
-rw-r--r--src/core/jobs/task.cpp21
-rw-r--r--src/core/jobs/task_p.h4
-rw-r--r--src/core/nodes/qbackendnode.cpp12
-rw-r--r--src/core/nodes/qbackendnode.h12
-rw-r--r--src/core/nodes/qentity.cpp52
-rw-r--r--src/core/nodes/qentity_p.h1
-rw-r--r--src/core/nodes/qnode.cpp29
-rw-r--r--src/core/nodes/qnode.h12
-rw-r--r--src/core/nodes/qnode_p.h24
-rw-r--r--src/core/nodes/qnodecreatedchangegenerator_p.h3
-rw-r--r--src/core/qchangearbiter_p.h10
-rw-r--r--src/core/qpostman_p.h2
-rw-r--r--src/core/qscheduler.cpp16
-rw-r--r--src/core/qscheduler_p.h6
-rw-r--r--src/core/qt3dcore_global.h6
-rw-r--r--src/core/resources/qloadgltf_p.h73
-rw-r--r--src/core/resources/qresourcemanager_p.h39
-rw-r--r--src/core/resources/resources.pri1
-rw-r--r--src/core/services/nullservices_p.h14
-rw-r--r--src/core/services/qdownloadnetworkworker.cpp2
-rw-r--r--src/core/services/qservicelocator.cpp16
-rw-r--r--src/core/services/qservicelocator_p.h3
-rw-r--r--src/core/services/qsysteminformationservice.cpp360
-rw-r--r--src/core/services/qsysteminformationservice_p.h31
-rw-r--r--src/core/services/qsysteminformationservice_p_p.h89
-rw-r--r--src/core/transforms/matrix4x4_avx2_p.h1
-rw-r--r--src/core/transforms/matrix4x4_sse_p.h3
-rw-r--r--src/core/transforms/qabstractskeleton.cpp19
-rw-r--r--src/core/transforms/qabstractskeleton.h3
-rw-r--r--src/core/transforms/qskeletonloader.cpp50
-rw-r--r--src/core/transforms/qskeletonloader_p.h1
-rw-r--r--src/core/transforms/qtransform.cpp1
-rw-r--r--src/core/transforms/qtransform.h1
-rw-r--r--src/core/transforms/sqt_p.h2
-rw-r--r--src/core/transforms/vector3d_sse_p.h8
-rw-r--r--src/doc/src/qmlextramaterials.qdoc35
-rw-r--r--src/extras/defaults/qabstractspritesheet.cpp2
-rw-r--r--src/extras/defaults/qforwardrenderer.cpp19
-rw-r--r--src/extras/defaults/qforwardrenderer.h4
-rw-r--r--src/extras/defaults/qforwardrenderer_p.h2
-rw-r--r--src/extras/defaults/qt3dwindow.cpp2
-rw-r--r--src/extras/extras.pro1
-rw-r--r--src/extras/shaders/es2/distancefieldtext.frag2
-rw-r--r--src/extras/shaders/gl3/distancefieldtext.frag4
-rw-r--r--src/extras/text/qtext2dentity.cpp13
-rw-r--r--src/input/backend/keyboardeventfilter.cpp1
-rw-r--r--src/input/backend/keyboardhandler.cpp1
-rw-r--r--src/input/backend/mousedevice.cpp11
-rw-r--r--src/input/backend/mousedevice_p.h2
-rw-r--r--src/input/backend/mouseeventfilter.cpp1
-rw-r--r--src/input/backend/mousehandler.cpp1
-rw-r--r--src/input/frontend/qabstractphysicaldeviceproxy.cpp1
-rw-r--r--src/input/frontend/qaction.cpp6
-rw-r--r--src/input/frontend/qaction.h4
-rw-r--r--src/input/frontend/qactioninput.cpp2
-rw-r--r--src/input/frontend/qaxis.cpp6
-rw-r--r--src/input/frontend/qaxis.h4
-rw-r--r--src/input/frontend/qaxisaccumulator.cpp6
-rw-r--r--src/input/frontend/qaxisaccumulator.h4
-rw-r--r--src/input/frontend/qkeyboarddevice.cpp12
-rw-r--r--src/input/frontend/qkeyboarddevice.h1
-rw-r--r--src/input/frontend/qkeyboardhandler.cpp6
-rw-r--r--src/input/frontend/qkeyboardhandler.h4
-rw-r--r--src/input/frontend/qkeyevent.cpp6
-rw-r--r--src/input/frontend/qmousedevice.cpp38
-rw-r--r--src/input/frontend/qmousedevice.h4
-rw-r--r--src/input/frontend/qmousedevice_p.h1
-rw-r--r--src/input/frontend/qmouseevent.cpp6
-rw-r--r--src/input/frontend/qmouseevent.h15
-rw-r--r--src/input/frontend/qmousehandler.cpp12
-rw-r--r--src/input/frontend/qmousehandler.h2
-rw-r--r--src/input/frontend/qphysicaldevicecreatedchange.cpp2
-rw-r--r--src/input/input.pro1
-rw-r--r--src/logic/callbackjob.cpp2
-rw-r--r--src/logic/executor.cpp4
-rw-r--r--src/logic/logic.pro1
-rw-r--r--src/logic/manager.cpp2
-rw-r--r--src/logic/qlogicaspect.cpp1
-rw-r--r--src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp9
-rw-r--r--src/plugins/renderers/dummy/dummy.pro0
-rw-r--r--src/plugins/renderers/opengl/debug/debug.pri10
-rw-r--r--src/plugins/renderers/opengl/debug/imguirenderer.cpp706
-rw-r--r--src/plugins/renderers/opengl/debug/imguirenderer_p.h137
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp)136
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicscontext_p.h)39
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp)13
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes2_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp)4
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h)4
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp)2
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperes3_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp)8
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp)18
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp)16
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp)16
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h)10
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h)13
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri (renamed from src/render/renderers/opengl/graphicshelpers/graphicshelpers.pri)4
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp (renamed from src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp)8
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h (renamed from src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h)12
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h (renamed from src/render/backend/qgraphicsutils_p.h)12
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp (renamed from src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp)135
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h (renamed from src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h)40
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp (renamed from src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp)7
-rw-r--r--src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h (renamed from src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h)8
-rw-r--r--src/plugins/renderers/opengl/io/glbuffer.cpp (renamed from src/render/renderers/opengl/io/glbuffer.cpp)6
-rw-r--r--src/plugins/renderers/opengl/io/glbuffer_p.h (renamed from src/render/renderers/opengl/io/glbuffer_p.h)10
-rw-r--r--src/plugins/renderers/opengl/io/io.pri (renamed from src/render/renderers/opengl/io/io.pri)0
-rw-r--r--src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp (renamed from src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp)8
-rw-r--r--src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h (renamed from src/render/renderers/opengl/jobs/filtercompatibletechniquejob_p.h)12
-rw-r--r--src/plugins/renderers/opengl/jobs/jobs.pri (renamed from src/render/renderers/opengl/jobs/jobs.pri)6
-rw-r--r--src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp (renamed from src/render/renderers/opengl/jobs/materialparametergathererjob.cpp)6
-rw-r--r--src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h (renamed from src/render/renderers/opengl/jobs/materialparametergathererjob_p.h)14
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp (renamed from src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp)32
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h (renamed from src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h)40
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp85
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h100
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp87
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_p.h107
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp (renamed from src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp)10
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h (renamed from src/render/renderers/opengl/jobs/renderviewinitializerjob_p.h)12
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp (renamed from src/render/renderers/opengl/jobs/renderviewjobutils.cpp)43
-rw-r--r--src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h (renamed from src/render/renderers/opengl/jobs/renderviewjobutils_p.h)20
-rw-r--r--src/plugins/renderers/opengl/main.cpp59
-rw-r--r--src/plugins/renderers/opengl/managers/gl_handle_types_p.h (renamed from src/render/renderers/opengl/textures/gltexturemanager_p.h)34
-rw-r--r--src/plugins/renderers/opengl/managers/glresourcemanagers.cpp (renamed from src/render/renderers/opengl/renderer/rendercommand.cpp)52
-rw-r--r--src/plugins/renderers/opengl/managers/glresourcemanagers_p.h139
-rw-r--r--src/plugins/renderers/opengl/managers/managers.pri8
-rw-r--r--src/plugins/renderers/opengl/opengl.pri41
-rw-r--r--src/plugins/renderers/opengl/opengl.pro10
-rw-r--r--src/plugins/renderers/opengl/openglrenderer.json3
-rw-r--r--src/plugins/renderers/opengl/renderer/commandexecuter.cpp (renamed from src/render/backend/commandexecuter.cpp)46
-rw-r--r--src/plugins/renderers/opengl/renderer/commandexecuter_p.h (renamed from src/render/backend/commandexecuter_p.h)8
-rw-r--r--src/plugins/renderers/opengl/renderer/frameprofiler_p.h (renamed from src/render/backend/frameprofiler_p.h)79
-rw-r--r--src/plugins/renderers/opengl/renderer/glfence_p.h (renamed from src/render/renderers/opengl/graphicshelpers/glfence_p.h)0
-rw-r--r--src/plugins/renderers/opengl/renderer/glshader.cpp321
-rw-r--r--src/plugins/renderers/opengl/renderer/glshader_p.h164
-rw-r--r--src/plugins/renderers/opengl/renderer/logging.cpp69
-rw-r--r--src/plugins/renderers/opengl/renderer/logging_p.h85
-rw-r--r--src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp (renamed from src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp)14
-rw-r--r--src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h (renamed from src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h)20
-rw-r--r--src/plugins/renderers/opengl/renderer/rendercommand.cpp93
-rw-r--r--src/plugins/renderers/opengl/renderer/rendercommand_p.h (renamed from src/render/renderers/opengl/renderer/rendercommand_p.h)70
-rw-r--r--src/plugins/renderers/opengl/renderer/renderer.cpp (renamed from src/render/renderers/opengl/renderer/renderer.cpp)749
-rw-r--r--src/plugins/renderers/opengl/renderer/renderer.pri (renamed from src/render/renderers/opengl/renderer/renderer.pri)13
-rw-r--r--src/plugins/renderers/opengl/renderer/renderer_p.h (renamed from src/render/renderers/opengl/renderer/renderer_p.h)128
-rw-r--r--src/plugins/renderers/opengl/renderer/renderercache_p.h (renamed from src/render/renderers/opengl/renderer/renderercache_p.h)25
-rw-r--r--src/plugins/renderers/opengl/renderer/renderqueue.cpp (renamed from src/render/renderers/opengl/renderer/renderqueue.cpp)6
-rw-r--r--src/plugins/renderers/opengl/renderer/renderqueue_p.h (renamed from src/render/renderers/opengl/renderer/renderqueue_p.h)10
-rw-r--r--src/plugins/renderers/opengl/renderer/renderview.cpp (renamed from src/render/renderers/opengl/renderer/renderview.cpp)741
-rw-r--r--src/plugins/renderers/opengl/renderer/renderview_p.h (renamed from src/render/renderers/opengl/renderer/renderview_p.h)63
-rw-r--r--src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp (renamed from src/render/renderers/opengl/renderer/renderviewbuilder.cpp)591
-rw-r--r--src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h (renamed from src/render/renderers/opengl/renderer/renderviewbuilder_p.h)71
-rw-r--r--src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp (renamed from src/render/renderers/opengl/renderer/shaderparameterpack.cpp)5
-rw-r--r--src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h (renamed from src/render/renderers/opengl/renderer/shaderparameterpack_p.h)69
-rw-r--r--src/plugins/renderers/opengl/renderer/shadervariables_p.h (renamed from src/render/renderers/opengl/renderer/shadervariables_p.h)24
-rw-r--r--src/plugins/renderers/opengl/textures/gltexture.cpp (renamed from src/render/renderers/opengl/textures/gltexture.cpp)26
-rw-r--r--src/plugins/renderers/opengl/textures/gltexture_p.h (renamed from src/render/renderers/opengl/textures/gltexture_p.h)12
-rw-r--r--src/plugins/renderers/opengl/textures/renderbuffer.cpp (renamed from src/render/renderers/opengl/textures/renderbuffer.cpp)2
-rw-r--r--src/plugins/renderers/opengl/textures/renderbuffer_p.h (renamed from src/render/renderers/opengl/textures/renderbuffer_p.h)8
-rw-r--r--src/plugins/renderers/opengl/textures/textures.pri (renamed from src/render/renderers/opengl/textures/textures.pri)3
-rw-r--r--src/plugins/renderers/renderers.pro9
-rw-r--r--src/plugins/renderplugins/scene2d/scene2d.pro1
-rw-r--r--src/plugins/sceneparsers/assimp/assimp.pro1
-rw-r--r--src/plugins/sceneparsers/gltf/gltf.pro1
-rw-r--r--src/plugins/sceneparsers/gltf/gltfimporter.cpp10
-rw-r--r--src/plugins/sceneparsers/gltfexport/gltfexport.pro1
-rw-r--r--src/quick3d/imports/animation/importsanimation.pro1
-rw-r--r--src/quick3d/imports/animation/plugins.qmltypes55
-rw-r--r--src/quick3d/imports/core/importscore.pro1
-rw-r--r--src/quick3d/imports/core/plugins.qmltypes73
-rw-r--r--src/quick3d/imports/extras/importsextras.pro1
-rw-r--r--src/quick3d/imports/extras/plugins.qmltypes55
-rw-r--r--src/quick3d/imports/extras/qt3dquick3dextrasplugin.cpp1
-rw-r--r--src/quick3d/imports/input/importsinput.pro1
-rw-r--r--src/quick3d/imports/input/plugins.qmltypes2
-rw-r--r--src/quick3d/imports/input/qt3dquick3dinputplugin.cpp1
-rw-r--r--src/quick3d/imports/logic/importslogic.pro1
-rw-r--r--src/quick3d/imports/logic/plugins.qmltypes2
-rw-r--r--src/quick3d/imports/render/importsrender.pro1
-rw-r--r--src/quick3d/imports/render/plugins.qmltypes255
-rw-r--r--src/quick3d/imports/render/qt3dquick3drenderplugin.cpp4
-rw-r--r--src/quick3d/imports/scene2d/importsscene2d.pro1
-rw-r--r--src/quick3d/imports/scene2d/plugins.qmltypes2
-rw-r--r--src/quick3d/imports/scene3d/importsscene3d.pro1
-rw-r--r--src/quick3d/imports/scene3d/plugins.qmltypes38
-rw-r--r--src/quick3d/imports/scene3d/scene3ditem.cpp81
-rw-r--r--src/quick3d/imports/scene3d/scene3drenderer.cpp23
-rw-r--r--src/quick3d/imports/scene3d/scene3drenderer_p.h3
-rw-r--r--src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp1
-rw-r--r--src/quick3d/imports/scene3d/scene3dview.cpp2
-rw-r--r--src/quick3d/quick3d/qquaternionanimation.cpp2
-rw-r--r--src/quick3d/quick3d/quick3d.pro1
-rw-r--r--src/quick3d/quick3danimation/quick3danimation.pro1
-rw-r--r--src/quick3d/quick3dextras/qt3dquickwindow.cpp2
-rw-r--r--src/quick3d/quick3dextras/quick3dextras.pro1
-rw-r--r--src/quick3d/quick3dinput/quick3dinput.pro1
-rw-r--r--src/quick3d/quick3drender/quick3drender.pro1
-rw-r--r--src/quick3d/quick3dscene2d/items/qscene2d.cpp6
-rw-r--r--src/quick3d/quick3dscene2d/items/qscene2d.h5
-rw-r--r--src/quick3d/quick3dscene2d/items/scene2d.cpp18
-rw-r--r--src/quick3d/quick3dscene2d/items/scene2dsharedobject.cpp1
-rw-r--r--src/quick3d/quick3dscene2d/quick3dscene2d.pro1
-rw-r--r--src/render/backend/abstractrenderer_p.h11
-rw-r--r--src/render/backend/apishadermanager_p.h224
-rw-r--r--src/render/backend/attachmentpack_p.h5
-rw-r--r--src/render/backend/backendnode.cpp8
-rw-r--r--src/render/backend/backendnode_p.h2
-rw-r--r--src/render/backend/bufferutils_p.h4
-rw-r--r--src/render/backend/cameralens.cpp63
-rw-r--r--src/render/backend/cameralens_p.h7
-rw-r--r--src/render/backend/computecommand.cpp29
-rw-r--r--src/render/backend/computecommand_p.h5
-rw-r--r--src/render/backend/entity.cpp4
-rw-r--r--src/render/backend/entity_p.h4
-rw-r--r--src/render/backend/handle_types_p.h6
-rw-r--r--src/render/backend/levelofdetail_p.h2
-rw-r--r--src/render/backend/managers_p.h101
-rw-r--r--src/render/backend/nodemanagers.cpp29
-rw-r--r--src/render/backend/nodemanagers_p.h27
-rw-r--r--src/render/backend/offscreensurfacehelper_p.h3
-rw-r--r--src/render/backend/platformsurfacefilter.cpp2
-rw-r--r--src/render/backend/platformsurfacefilter_p.h2
-rw-r--r--src/render/backend/render-backend.pri12
-rw-r--r--src/render/backend/rendersettings.cpp28
-rw-r--r--src/render/backend/rendersettings_p.h4
-rw-r--r--src/render/backend/rendertarget_p.h2
-rw-r--r--src/render/backend/rendertargetoutput_p.h2
-rw-r--r--src/render/backend/renderthread_p.h4
-rw-r--r--src/render/backend/resourceaccessor.cpp43
-rw-r--r--src/render/backend/resourceaccessor_p.h5
-rw-r--r--src/render/backend/segmentsvisitor.cpp52
-rw-r--r--src/render/backend/stringtoint.cpp39
-rw-r--r--src/render/backend/stringtoint_p.h3
-rw-r--r--src/render/backend/transform.cpp1
-rw-r--r--src/render/backend/transform_p.h2
-rw-r--r--src/render/backend/trianglesvisitor.cpp11
-rw-r--r--src/render/backend/uniform_p.h10
-rw-r--r--src/render/backend/visitorutils_p.h2
-rw-r--r--src/render/framegraph/blitframebuffer_p.h2
-rw-r--r--src/render/framegraph/buffercapture_p.h2
-rw-r--r--src/render/framegraph/cameraselectornode.cpp3
-rw-r--r--src/render/framegraph/cameraselectornode_p.h2
-rw-r--r--src/render/framegraph/clearbuffers_p.h2
-rw-r--r--src/render/framegraph/debugoverlay.cpp60
-rw-r--r--src/render/framegraph/debugoverlay_p.h75
-rw-r--r--src/render/framegraph/dispatchcompute_p.h2
-rw-r--r--src/render/framegraph/framegraph.pri9
-rw-r--r--src/render/framegraph/framegraphnode.cpp2
-rw-r--r--src/render/framegraph/framegraphnode_p.h5
-rw-r--r--src/render/framegraph/framegraphvisitor.cpp2
-rw-r--r--src/render/framegraph/framegraphvisitor_p.h3
-rw-r--r--src/render/framegraph/frustumculling_p.h2
-rw-r--r--src/render/framegraph/layerfilternode_p.h2
-rw-r--r--src/render/framegraph/memorybarrier_p.h2
-rw-r--r--src/render/framegraph/nodraw_p.h2
-rw-r--r--src/render/framegraph/nopicking_p.h1
-rw-r--r--src/render/framegraph/proximityfilter_p.h2
-rw-r--r--src/render/framegraph/qblitframebuffer.cpp4
-rw-r--r--src/render/framegraph/qbuffercapture.cpp12
-rw-r--r--src/render/framegraph/qdebugoverlay.cpp (renamed from src/render/jobs/sendrendercapturejob.cpp)53
-rw-r--r--src/render/framegraph/qdebugoverlay.h63
-rw-r--r--src/render/framegraph/qdebugoverlay_p.h (renamed from src/render/jobs/sendrendercapturejob_p.h)43
-rw-r--r--src/render/framegraph/qframegraphnode.cpp59
-rw-r--r--src/render/framegraph/qframegraphnode_p.h3
-rw-r--r--src/render/framegraph/qrendercapture.cpp4
-rw-r--r--src/render/framegraph/qsetfence.cpp9
-rw-r--r--src/render/framegraph/qsortpolicy.cpp7
-rw-r--r--src/render/framegraph/qsortpolicy.h1
-rw-r--r--src/render/framegraph/qwaitfence.cpp12
-rw-r--r--src/render/framegraph/rendercapture.cpp26
-rw-r--r--src/render/framegraph/rendercapture_p.h4
-rw-r--r--src/render/framegraph/renderpassfilternode_p.h2
-rw-r--r--src/render/framegraph/rendersurfaceselector.cpp1
-rw-r--r--src/render/framegraph/rendersurfaceselector_p.h2
-rw-r--r--src/render/framegraph/rendertargetselectornode.cpp1
-rw-r--r--src/render/framegraph/rendertargetselectornode_p.h2
-rw-r--r--src/render/framegraph/setfence.cpp1
-rw-r--r--src/render/framegraph/setfence_p.h2
-rw-r--r--src/render/framegraph/sortpolicy_p.h2
-rw-r--r--src/render/framegraph/statesetnode_p.h2
-rw-r--r--src/render/framegraph/subtreeenabler.cpp19
-rw-r--r--src/render/framegraph/techniquefilternode_p.h2
-rw-r--r--src/render/framegraph/viewportnode_p.h2
-rw-r--r--src/render/frontend/qabstractfunctor.h4
-rw-r--r--src/render/frontend/qcamera.cpp34
-rw-r--r--src/render/frontend/qcameralens.cpp42
-rw-r--r--src/render/frontend/qcameralens_p.h21
-rw-r--r--src/render/frontend/qcomputecommand.cpp6
-rw-r--r--src/render/frontend/qlevelofdetail.cpp5
-rw-r--r--src/render/frontend/qlevelofdetail.h2
-rw-r--r--src/render/frontend/qlevelofdetailswitch.cpp6
-rw-r--r--src/render/frontend/qlevelofdetailswitch.h2
-rw-r--r--src/render/frontend/qrenderaspect.cpp83
-rw-r--r--src/render/frontend/qrenderaspect_p.h4
-rw-r--r--src/render/frontend/qrendercapabilities.cpp431
-rw-r--r--src/render/frontend/qrendercapabilities.h144
-rw-r--r--src/render/frontend/qrendercapabilities_p.h105
-rw-r--r--src/render/frontend/qrendersettings.cpp35
-rw-r--r--src/render/frontend/qrendersettings.h5
-rw-r--r--src/render/frontend/qrendersettings_p.h2
-rw-r--r--src/render/frontend/render-frontend.pri7
-rw-r--r--src/render/frontend/sphere.cpp48
-rw-r--r--src/render/frontend/sphere_p.h2
-rw-r--r--src/render/geometry/armature_p.h2
-rw-r--r--src/render/geometry/attribute_p.h2
-rw-r--r--src/render/geometry/buffer.cpp44
-rw-r--r--src/render/geometry/buffer_p.h2
-rw-r--r--src/render/geometry/buffermanager_p.h2
-rw-r--r--src/render/geometry/geometry_p.h2
-rw-r--r--src/render/geometry/geometryrenderer.cpp10
-rw-r--r--src/render/geometry/geometryrenderer_p.h2
-rw-r--r--src/render/geometry/geometryrenderermanager_p.h2
-rw-r--r--src/render/geometry/gltfskeletonloader.cpp6
-rw-r--r--src/render/geometry/joint_p.h2
-rw-r--r--src/render/geometry/qbuffer.cpp40
-rw-r--r--src/render/geometry/qbuffer.h11
-rw-r--r--src/render/geometry/qbuffer_p.h2
-rw-r--r--src/render/geometry/qgeometryrenderer.cpp9
-rw-r--r--src/render/geometry/qgeometryrenderer.h6
-rw-r--r--src/render/geometry/qmesh.cpp27
-rw-r--r--src/render/geometry/qmesh.h2
-rw-r--r--src/render/geometry/qmesh_p.h3
-rw-r--r--src/render/geometry/skeleton.cpp2
-rw-r--r--src/render/geometry/skeleton_p.h2
-rw-r--r--src/render/io/qsceneloader.cpp8
-rw-r--r--src/render/io/qsceneloader.h2
-rw-r--r--src/render/io/scene.cpp4
-rw-r--r--src/render/io/scene_p.h2
-rw-r--r--src/render/io/scenemanager_p.h2
-rw-r--r--src/render/jobs/abstractpickingjob.cpp3
-rw-r--r--src/render/jobs/abstractpickingjob_p.h3
-rw-r--r--src/render/jobs/calcboundingvolumejob.cpp2
-rw-r--r--src/render/jobs/calcgeometrytrianglevolumes.cpp2
-rw-r--r--src/render/jobs/computefilteredboundingvolumejob.cpp38
-rw-r--r--src/render/jobs/computefilteredboundingvolumejob_p.h4
-rw-r--r--src/render/jobs/expandboundingvolumejob.cpp7
-rw-r--r--src/render/jobs/filterentitybycomponentjob_p.h6
-rw-r--r--src/render/jobs/filterlayerentityjob.cpp2
-rw-r--r--src/render/jobs/filterproximitydistancejob.cpp6
-rw-r--r--src/render/jobs/filterproximitydistancejob_p.h3
-rw-r--r--src/render/jobs/framecleanupjob.cpp6
-rw-r--r--src/render/jobs/frustumcullingjob.cpp3
-rw-r--r--src/render/jobs/frustumcullingjob_p.h18
-rw-r--r--src/render/jobs/genericlambdajob_p.h4
-rw-r--r--src/render/jobs/job_common_p.h10
-rw-r--r--src/render/jobs/jobs.pri2
-rw-r--r--src/render/jobs/lightgatherer.cpp6
-rw-r--r--src/render/jobs/lightgatherer_p.h3
-rw-r--r--src/render/jobs/loadbufferjob.cpp34
-rw-r--r--src/render/jobs/loadbufferjob_p.h6
-rw-r--r--src/render/jobs/loadgeometryjob.cpp2
-rw-r--r--src/render/jobs/loadgeometryjob_p.h3
-rw-r--r--src/render/jobs/loadscenejob.cpp4
-rw-r--r--src/render/jobs/loadscenejob_p.h3
-rw-r--r--src/render/jobs/loadskeletonjob.cpp5
-rw-r--r--src/render/jobs/pickboundingvolumejob.cpp1
-rw-r--r--src/render/jobs/pickboundingvolumejob_p.h3
-rw-r--r--src/render/jobs/raycastingjob.cpp1
-rw-r--r--src/render/jobs/raycastingjob_p.h3
-rw-r--r--src/render/jobs/sendbuffercapturejob.cpp68
-rw-r--r--src/render/jobs/sendbuffercapturejob_p.h10
-rw-r--r--src/render/jobs/updateentitylayersjob.cpp2
-rw-r--r--src/render/jobs/updatemeshtrianglelistjob.cpp2
-rw-r--r--src/render/jobs/updateshaderdatatransformjob.cpp2
-rw-r--r--src/render/jobs/updateskinningpalettejob.cpp2
-rw-r--r--src/render/jobs/updateskinningpalettejob_p.h3
-rw-r--r--src/render/jobs/updatetreeenabledjob.cpp3
-rw-r--r--src/render/jobs/updateworldboundingvolumejob.cpp4
-rw-r--r--src/render/jobs/updateworldtransformjob.cpp14
-rw-r--r--src/render/lights/environmentlight_p.h2
-rw-r--r--src/render/lights/light_p.h2
-rw-r--r--src/render/lights/lightsource_p.h4
-rw-r--r--src/render/lights/qdirectionallight.cpp10
-rw-r--r--src/render/lights/qenvironmentlight.cpp12
-rw-r--r--src/render/lights/qpointlight.cpp30
-rw-r--r--src/render/lights/qspotlight.cpp50
-rw-r--r--src/render/materialsystem/effect.cpp2
-rw-r--r--src/render/materialsystem/effect_p.h2
-rw-r--r--src/render/materialsystem/filterkey_p.h2
-rw-r--r--src/render/materialsystem/material_p.h3
-rw-r--r--src/render/materialsystem/materialsystem.pri2
-rw-r--r--src/render/materialsystem/parameter_p.h2
-rw-r--r--src/render/materialsystem/qshaderimage.cpp25
-rw-r--r--src/render/materialsystem/qshaderprogram.cpp44
-rw-r--r--src/render/materialsystem/qshaderprogram.h11
-rw-r--r--src/render/materialsystem/qshaderprogram_p.h7
-rw-r--r--src/render/materialsystem/qshaderprogrambuilder.cpp5
-rw-r--r--src/render/materialsystem/qshaderprogrambuilder.h2
-rw-r--r--src/render/materialsystem/renderpass.cpp1
-rw-r--r--src/render/materialsystem/renderpass_p.h2
-rw-r--r--src/render/materialsystem/shader.cpp366
-rw-r--r--src/render/materialsystem/shader_p.h136
-rw-r--r--src/render/materialsystem/shaderbuilder.cpp4
-rw-r--r--src/render/materialsystem/shadercache.cpp174
-rw-r--r--src/render/materialsystem/shaderdata.cpp8
-rw-r--r--src/render/materialsystem/shaderdata_p.h11
-rw-r--r--src/render/materialsystem/shaderimage.cpp1
-rw-r--r--src/render/materialsystem/technique.cpp1
-rw-r--r--src/render/materialsystem/techniquemanager_p.h2
-rw-r--r--src/render/picking/objectpicker_p.h2
-rw-r--r--src/render/picking/pickeventfilter_p.h3
-rw-r--r--src/render/picking/qabstractraycaster.cpp16
-rw-r--r--src/render/picking/qobjectpicker.cpp7
-rw-r--r--src/render/picking/qobjectpicker.h4
-rw-r--r--src/render/picking/qobjectpicker_p.h1
-rw-r--r--src/render/picking/raycaster.cpp1
-rw-r--r--src/render/picking/raycaster_p.h2
-rw-r--r--src/render/qrendererplugin.cpp68
-rw-r--r--src/render/qrendererplugin_p.h86
-rw-r--r--src/render/qrendererpluginfactory.cpp102
-rw-r--r--src/render/qrendererpluginfactory_p.h79
-rw-r--r--src/render/raycasting/qcollisionqueryresult.cpp1
-rw-r--r--src/render/raycasting/qcollisionqueryresult_p.h2
-rw-r--r--src/render/render.pro16
-rw-r--r--src/render/renderers/opengl/opengl.pri13
-rw-r--r--src/render/renderers/opengl/renderstates/renderstates.pri7
-rw-r--r--src/render/renderers/renderers.pri7
-rw-r--r--src/render/renderstates/genericstate_p.h3
-rw-r--r--src/render/renderstates/qrastermode.cpp4
-rw-r--r--src/render/renderstates/renderstatenode_p.h3
-rw-r--r--src/render/renderstates/renderstates.cpp1
-rw-r--r--src/render/renderstates/renderstates.pri6
-rw-r--r--src/render/renderstates/renderstates_p.h44
-rw-r--r--src/render/renderstates/renderstateset.cpp (renamed from src/render/renderers/opengl/renderstates/renderstateset.cpp)3
-rw-r--r--src/render/renderstates/renderstateset_p.h (renamed from src/render/renderers/opengl/renderstates/renderstateset_p.h)4
-rw-r--r--src/render/renderstates/statevariant_p.h2
-rw-r--r--src/render/services/vsyncframeadvanceservice.cpp6
-rw-r--r--src/render/services/vsyncframeadvanceservice_p.h3
-rw-r--r--src/render/texture/qabstracttexture.cpp20
-rw-r--r--src/render/texture/qabstracttexture.h2
-rw-r--r--src/render/texture/qabstracttextureimage.cpp4
-rw-r--r--src/render/texture/qtexture.cpp20
-rw-r--r--src/render/texture/qtexturegenerator.cpp3
-rw-r--r--src/render/texture/qtextureimagedata_p.h3
-rw-r--r--src/render/texture/texture.cpp12
-rw-r--r--src/render/texture/texture_p.h2
-rw-r--r--src/render/texture/texturedatamanager_p.h227
-rw-r--r--src/render/texture/textureimage_p.h2
-rw-r--r--src/src.pro11
-rw-r--r--sync.profile2
-rw-r--r--tests/auto/animation/animationclip/tst_animationclip.cpp2
-rw-r--r--tests/auto/animation/animationutils/tst_animationutils.cpp2
-rw-r--r--tests/auto/animation/blendedclipanimator/tst_blendedclipanimator.cpp2
-rw-r--r--tests/auto/animation/channelmapping/tst_channelmapping.cpp32
-rw-r--r--tests/auto/animation/qanimationcliploader/tst_qanimationcliploader.cpp1
-rw-r--r--tests/auto/animation/skeleton/tst_skeleton.cpp1
-rw-r--r--tests/auto/core/common/qbackendnodetester.cpp9
-rw-r--r--tests/auto/core/common/testpostmanarbiter.cpp4
-rw-r--r--tests/auto/core/common/testpostmanarbiter.h3
-rw-r--r--tests/auto/core/core.pro5
-rw-r--r--tests/auto/core/nodes/tst_nodes.cpp116
-rw-r--r--tests/auto/core/qaspectengine/tst_qaspectengine.cpp14
-rw-r--r--tests/auto/core/qchangearbiter/tst_qchangearbiter.cpp4
-rw-r--r--tests/auto/core/qentity/tst_qentity.cpp4
-rw-r--r--tests/auto/core/qpostman/tst_qpostman.cpp221
-rw-r--r--tests/auto/core/qresourcemanager/tst_qresourcemanager.cpp21
-rw-r--r--tests/auto/core/qscene/tst_qscene.cpp4
-rw-r--r--tests/auto/core/qscheduler/qscheduler.pro7
-rw-r--r--tests/auto/core/qscheduler/tst_qscheduler.cpp201
-rw-r--r--tests/auto/core/qservicelocator/tst_qservicelocator.cpp16
-rw-r--r--tests/auto/core/qskeleton/tst_qskeleton.cpp36
-rw-r--r--tests/auto/core/qskeletonloader/tst_qskeletonloader.cpp65
-rw-r--r--tests/auto/core/qtransform/tst_qtransform.cpp4
-rw-r--r--tests/auto/core/threadpooler/tst_threadpooler.cpp2
-rw-r--r--tests/auto/coretest/qbackendnodetester.cpp6
-rw-r--r--tests/auto/coretest/testpostmanarbiter.cpp4
-rw-r--r--tests/auto/extras/common/geometrytesthelper.h3
-rw-r--r--tests/auto/global/aspects_startup_shutdown/tst_aspects_startup_shutdown.cpp4
-rw-r--r--tests/auto/input/abstractaxisinput/tst_abstractaxisinput.cpp2
-rw-r--r--tests/auto/input/action/tst_action.cpp1
-rw-r--r--tests/auto/input/analogaxisinput/tst_analogaxisinput.cpp2
-rw-r--r--tests/auto/input/axis/tst_axis.cpp1
-rw-r--r--tests/auto/input/axisaccumulator/tst_axisaccumulator.cpp1
-rw-r--r--tests/auto/input/buttonaxisinput/tst_buttonaxisinput.cpp2
-rw-r--r--tests/auto/input/input.pro3
-rw-r--r--tests/auto/input/loadproxydevicejob/tst_loadproxydevicejob.cpp1
-rw-r--r--tests/auto/input/mousedevice/tst_mousedevice.cpp73
-rw-r--r--tests/auto/input/physicaldeviceproxy/tst_physicaldeviceproxy.cpp2
-rw-r--r--tests/auto/input/qabstractphysicaldeviceproxy/tst_qabstractphysicaldeviceproxy.cpp1
-rw-r--r--tests/auto/input/qaction/tst_qaction.cpp1
-rw-r--r--tests/auto/input/qaxis/tst_qaxis.cpp1
-rw-r--r--tests/auto/input/qaxisaccumulator/tst_qaxisaccumulator.cpp1
-rw-r--r--tests/auto/input/qmousedevice/tst_qmousedevice.cpp45
-rw-r--r--tests/auto/input/qmouseevent/qmouseevent.pro11
-rw-r--r--tests/auto/input/qmouseevent/tst_qmouseevent.cpp93
-rw-r--r--tests/auto/render/buffer/tst_buffer.cpp64
-rw-r--r--tests/auto/render/commons/testrenderer.cpp5
-rw-r--r--tests/auto/render/commons/testrenderer.h24
-rw-r--r--tests/auto/render/computecommand/tst_computecommand.cpp48
-rw-r--r--tests/auto/render/ddstextures/tst_ddstextures.cpp4
-rw-r--r--tests/auto/render/effect/tst_effect.cpp1
-rw-r--r--tests/auto/render/entity/tst_entity.cpp52
-rw-r--r--tests/auto/render/geometry/tst_geometry.cpp4
-rw-r--r--tests/auto/render/geometryrenderer/tst_geometryrenderer.cpp4
-rw-r--r--tests/auto/render/gltexture/tst_gltexture.cpp4
-rw-r--r--tests/auto/render/ktxtextures/tst_ktxtextures.cpp4
-rw-r--r--tests/auto/render/layerfiltering/tst_layerfiltering.cpp1
-rw-r--r--tests/auto/render/meshfunctors/tst_meshfunctors.cpp4
-rw-r--r--tests/auto/render/objectpicker/tst_objectpicker.cpp1
-rw-r--r--tests/auto/render/opengl/computecommand/computecommand.pro15
-rw-r--r--tests/auto/render/opengl/computecommand/tst_computecommand.cpp143
-rw-r--r--tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST (renamed from tests/auto/render/filtercompatibletechniquejob/BLACKLIST)0
-rw-r--r--tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro (renamed from tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro)7
-rw-r--r--tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp (renamed from tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp)33
-rw-r--r--tests/auto/render/opengl/glshadermanager/glshadermanager.pro15
-rw-r--r--tests/auto/render/opengl/glshadermanager/tst_glshadermanager.cpp199
-rw-r--r--tests/auto/render/opengl/graphicshelpergl2/graphicshelpergl2.pro (renamed from tests/auto/render/graphicshelpergl2/graphicshelpergl2.pro)7
-rw-r--r--tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp (renamed from tests/auto/render/graphicshelpergl2/tst_graphicshelpergl2.cpp)3
-rw-r--r--tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro (renamed from tests/auto/render/graphicshelpergl3_2/graphicshelpergl3_2.pro)7
-rw-r--r--tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp (renamed from tests/auto/render/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp)3
-rw-r--r--tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro (renamed from tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro)7
-rw-r--r--tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp (renamed from tests/auto/render/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp)3
-rw-r--r--tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro (renamed from tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro)7
-rw-r--r--tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp (renamed from tests/auto/render/graphicshelpergl4/tst_graphicshelpergl4.cpp)3
-rw-r--r--tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro (renamed from tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro)5
-rw-r--r--tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp (renamed from tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp)60
-rw-r--r--tests/auto/render/opengl/opengl.pro19
-rw-r--r--tests/auto/render/opengl/opengl_render_plugin.pri18
-rw-r--r--tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro (renamed from tests/auto/render/qgraphicsutils/qgraphicsutils.pro)3
-rw-r--r--tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp (renamed from tests/auto/render/qgraphicsutils/tst_qgraphicsutils.cpp)78
-rw-r--r--tests/auto/render/opengl/renderer/renderer.pro (renamed from tests/auto/render/renderer/renderer.pro)3
-rw-r--r--tests/auto/render/opengl/renderer/tst_renderer.cpp (renamed from tests/auto/render/renderer/tst_renderer.cpp)138
-rw-r--r--tests/auto/render/opengl/renderqueue/renderqueue.pro (renamed from tests/auto/render/renderqueue/renderqueue.pro)5
-rw-r--r--tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp (renamed from tests/auto/render/renderqueue/tst_renderqueue.cpp)36
-rw-r--r--tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro (renamed from tests/auto/render/renderviewbuilder/renderviewbuilder.pro)7
-rw-r--r--tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp (renamed from tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp)229
-rw-r--r--tests/auto/render/opengl/renderviews/renderviews.pro (renamed from tests/auto/render/renderviews/renderviews.pro)7
-rw-r--r--tests/auto/render/opengl/renderviews/tst_renderviews.cpp (renamed from tests/auto/render/renderviews/tst_renderviews.cpp)255
-rw-r--r--tests/auto/render/opengl/renderviewutils/renderviewutils.pro (renamed from tests/auto/render/renderviewutils/renderviewutils.pro)7
-rw-r--r--tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp (renamed from tests/auto/render/renderviewutils/tst_renderviewutils.cpp)83
-rw-r--r--tests/auto/render/opengl/textures/textures.pro (renamed from tests/auto/render/textures/textures.pro)7
-rw-r--r--tests/auto/render/opengl/textures/tst_textures.cpp (renamed from tests/auto/render/textures/tst_textures.cpp)63
-rw-r--r--tests/auto/render/pickboundingvolumejob/tst_pickboundingvolumejob.cpp2
-rw-r--r--tests/auto/render/picking/tst_picking.cpp3
-rw-r--r--tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp18
-rw-r--r--tests/auto/render/qabstracttexture/tst_qabstracttexture.cpp3
-rw-r--r--tests/auto/render/qbuffer/tst_qbuffer.cpp4
-rw-r--r--tests/auto/render/qcamera/tst_qcamera.cpp1
-rw-r--r--tests/auto/render/qdefaultmeshes/tst_qdefaultmeshes.cpp4
-rw-r--r--tests/auto/render/qgeometry/tst_qgeometry.cpp4
-rw-r--r--tests/auto/render/qgeometryrenderer/tst_qgeometryrenderer.cpp4
-rw-r--r--tests/auto/render/qmesh/tst_qmesh.cpp3
-rw-r--r--tests/auto/render/qraycaster/tst_qraycaster.cpp55
-rw-r--r--tests/auto/render/qrendercapture/tst_qrendercapture.cpp3
-rw-r--r--tests/auto/render/qsetfence/tst_qsetfence.cpp4
-rw-r--r--tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp68
-rw-r--r--tests/auto/render/qsharedgltexture/tst_qsharedgltexture.cpp3
-rw-r--r--tests/auto/render/qtextureimage/tst_qtextureimage.cpp3
-rw-r--r--tests/auto/render/qtextureloader/tst_qtextureloader.cpp3
-rw-r--r--tests/auto/render/raycaster/tst_raycaster.cpp1
-rw-r--r--tests/auto/render/raycastingjob/tst_raycastingjob.cpp1
-rw-r--r--tests/auto/render/render.pro19
-rw-r--r--tests/auto/render/scene2d/tst_scene2d.cpp3
-rw-r--r--tests/auto/render/segmentvisitor/tst_segmentvisitor.cpp27
-rw-r--r--tests/auto/render/sendrendercapturejob/sendrendercapturejob.pro12
-rw-r--r--tests/auto/render/sendrendercapturejob/tst_sendrendercapturejob.cpp85
-rw-r--r--tests/auto/render/setfence/tst_setfence.cpp4
-rw-r--r--tests/auto/render/shader/tst_shader.cpp94
-rw-r--r--tests/auto/render/shaderbuilder/tst_shaderbuilder.cpp1
-rw-r--r--tests/auto/render/shadercache/shadercache.pro11
-rw-r--r--tests/auto/render/shadercache/tst_shadercache.cpp293
-rw-r--r--tests/auto/render/skeleton/tst_skeleton.cpp85
-rw-r--r--tests/auto/render/technique/tst_technique.cpp1
-rw-r--r--tests/auto/render/transform/tst_transform.cpp1
-rw-r--r--tests/auto/render/trianglesextractor/tst_trianglesextractor.cpp1
-rw-r--r--tests/auto/render/trianglevisitor/tst_trianglevisitor.cpp26
-rw-r--r--tests/auto/render/uniform/tst_uniform.cpp2
-rw-r--r--tests/auto/render/vsyncframeadvanceservice/tst_vsyncframeadvanceservice.cpp2
-rw-r--r--tests/benchmarks/render/jobs/jobs.pro4
-rw-r--r--tests/benchmarks/render/jobs/tst_bench_jobs.cpp24
-rw-r--r--tests/benchmarks/render/materialparametergathering/materialparametergathering.pro3
-rw-r--r--tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp8
-rw-r--r--tests/manual/compute-manual/ComputeFrameGraph.qml91
-rw-r--r--tests/manual/compute-manual/ComputeMaterial.qml118
-rw-r--r--tests/manual/compute-manual/ParticlesScene.qml200
-rw-r--r--tests/manual/compute-manual/compute-manual.pro14
-rw-r--r--tests/manual/compute-manual/compute-manual.qrc11
-rw-r--r--tests/manual/compute-manual/main.cpp66
-rw-r--r--tests/manual/compute-manual/main.qml109
-rw-r--r--tests/manual/compute-manual/particles.comp31
-rw-r--r--tests/manual/compute-manual/particles.frag33
-rw-r--r--tests/manual/compute-manual/particles.vert27
-rw-r--r--tests/manual/manual-renderloop/main.cpp211
-rw-r--r--tests/manual/manual-renderloop/manual-renderloop.pro8
-rw-r--r--tests/manual/manual.pro8
-rw-r--r--tests/manual/rendercapture-qml/main.qml2
-rw-r--r--tests/manual/scene3d-visibility/main.cpp66
-rw-r--r--tests/manual/scene3d-visibility/main.qml161
-rw-r--r--tests/manual/scene3d-visibility/scene3d-visibility.pro10
-rw-r--r--tests/manual/scene3d-visibility/scene3d-visibility.qrc5
-rw-r--r--tests/manual/sharedtexture/main.cpp3
-rw-r--r--tests/manual/sharedtexture/videoplayer.cpp28
-rw-r--r--tests/manual/sharedtexture/videoplayer.h10
-rw-r--r--tests/manual/sharedtextureqml/main.cpp3
-rw-r--r--tests/manual/subtree-enabler-qml/FrameGraph.qml100
-rw-r--r--tests/manual/subtree-enabler-qml/SimpleCamera.qml79
-rw-r--r--tests/manual/subtree-enabler-qml/main.cpp64
-rw-r--r--tests/manual/subtree-enabler-qml/main.qml110
-rw-r--r--tests/manual/subtree-enabler-qml/subtree-enabler-qml.pro17
-rw-r--r--tests/manual/subtree-enabler-qml/subtree-enabler-qml.qrc7
-rw-r--r--tools/qgltf/qgltf.cpp12
-rw-r--r--tools/utils/exporters/blender/qt3d_animation_export.py14
-rw-r--r--tools/utils/exporters/blender/qt3d_armature_export.py17
-rw-r--r--tools/utils/exporters/blender/qt3d_path_export.py19
706 files changed, 41550 insertions, 5394 deletions
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.
diff --git a/dist/changes-5.14.0 b/dist/changes-5.14.0
new file mode 100644
index 000000000..442296db8
--- /dev/null
+++ b/dist/changes-5.14.0
@@ -0,0 +1,49 @@
+Qt 5.14 introduces many new features and improvements as well as bugfixes
+over the 5.13.x series. 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.14 series is binary compatible with the 5.13.x series.
+Applications compiled for 5.13 will continue to run with 5.14.
+
+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.
+
+****************************************************************************
+* Qt3DExtras *
+****************************************************************************
+
+ - QDistanceFieldGlyphCache:
+ * make sure the change arbiter of atlas for QText2DEntity can be set
+ when traversing node tree, and add new auto test for this.
+
+****************************************************************************
+* Qt3DRender *
+****************************************************************************
+
+ - QNoPicking: control picking execution in the FrameGraph
+ - Textures: internal data sharing removed
+ - QSortPolicy can now sort by Texture
+ - QPickEvent adds property for picked entity
+
+ - QImageTextureDataFunctor:
+ * return a invalid image data when url is invalid to ensure the property
+ of GLTexture will not be set to NoFormat
+
+****************************************************************************
+* UNSPECIFIED *
+****************************************************************************
+
+ - Add basic support for KTX container format.
+ - Add worldMatrix property on QTransform
+ - Added SubtreeEnabler to allow easing enabling
+ and disabling of frame graph subtrees.
+ - [QTBUG-74977] Scene3D add compositingMode property. Allows underlay
+ rendering.
+ - Introduce Scene3DView to render multiple distinct 3D scenes
diff --git a/dist/changes-5.14.1 b/dist/changes-5.14.1
new file mode 100644
index 000000000..d0086381b
--- /dev/null
+++ b/dist/changes-5.14.1
@@ -0,0 +1,20 @@
+Qt 5.14.1 is a bug-fix release. It maintains both forward and backward
+compatibility (source and binary) with Qt 5.14.0.
+
+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.14 series is binary compatible with the 5.13.x series.
+Applications compiled for 5.13 will continue to run with 5.14.
+
+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.
diff --git a/examples/qt3d/advancedcustommaterial/doc/src/advancedcustommaterial.qdoc b/examples/qt3d/advancedcustommaterial/doc/src/advancedcustommaterial.qdoc
index 377bb952c..d845fa8da 100644
--- a/examples/qt3d/advancedcustommaterial/doc/src/advancedcustommaterial.qdoc
+++ b/examples/qt3d/advancedcustommaterial/doc/src/advancedcustommaterial.qdoc
@@ -42,7 +42,7 @@
Advanced custom material example shows more complex shaders, and demonstrates controlling your
shader properties with QtQuick user interface and Animation. Water is a 3D mesh, that is
modeled and uv mapped inside Blender, and then brought into Scene 3D as an \c {.obj} file.
- Shader properties that user can control, are defined in \l {advancedcustommaterial/WaterMaterial.qml}{WaterMaterial}.
+ Shader properties that user can control, are defined in \c {advancedcustommaterial/WaterMaterial.qml}.
\section1 Controls
\section2 Texture scale slider
@@ -53,7 +53,7 @@
\section2 Texture speed slider
Offsets values for texture coordinates which are animated in
- \l {advancedcustommaterial/Water.qml}{Water.qml} and then passed to vertex shader.
+ \c {advancedcustommaterial/Water.qml} and then passed to vertex shader.
Creates the effect of textures scrolling over the surface.
\section2 Specularity
@@ -80,5 +80,5 @@
\section2 Mesh rotation
- Rotates the water mesh in \l {advancedcustommaterial/Water.qml}{Water.qml}.
+ Rotates the water mesh in \c {advancedcustommaterial/Water.qml}.
*/
diff --git a/examples/qt3d/audio-visualizer-qml/doc/src/audio-visualizer-qml.qdoc b/examples/qt3d/audio-visualizer-qml/doc/src/audio-visualizer-qml.qdoc
index 5a204757e..6c0b40301 100644
--- a/examples/qt3d/audio-visualizer-qml/doc/src/audio-visualizer-qml.qdoc
+++ b/examples/qt3d/audio-visualizer-qml/doc/src/audio-visualizer-qml.qdoc
@@ -41,7 +41,7 @@
\section1 Qt Quick 2D Implementation
- The Qt Quick Implementation \l{audio-visualizer-qml/main.qml}{main.qml} of the example uses
+ The Qt Quick Implementation in \c {audio-visualizer-qml/main.qml} of the example uses
\c{MediaPlayer} to play audio content.
\snippet audio-visualizer-qml/main.qml 0
@@ -57,8 +57,8 @@
\section1 Qt 3D Implementation
- The 3D elements of the example are created in the
- \l{audio-visualizer-qml/Visualizer.qml}{Visualizer.qml}. The camera is set to a fixed position
+ The 3D elements of the example are created in
+ \c {audio-visualizer-qml/Visualizer.qml}. The camera is set to a fixed position
to show the visualized bars from a correct angle.
\snippet audio-visualizer-qml/Visualizer.qml 0
@@ -73,7 +73,7 @@
\snippet audio-visualizer-qml/Visualizer.qml 2
- In \l{audio-visualizer-qml/BarEntity.qml}{BarEntity.qml} there are animations for rotating the
+ In \c {audio-visualizer-qml/BarEntity.qml} there are animations for rotating the
bars and changing the bar color. The bars are rotated on a level following a ring form. At the
same time the color of the bars is animated.
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/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 @@
<?xml version="1.0"?>
<manifest package="org.qtproject.planets.qml" xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.0" android:versionCode="1" android:installLocation="auto">
- <application android:hardwareAccelerated="true" android:name="org.qtproject.qt5.android.bindings.QtApplication" android:label="-- %%INSERT_APP_NAME%% --" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
+ <application android:hardwareAccelerated="true" android:name="org.qtproject.qt5.android.bindings.QtApplication" android:label="-- %%INSERT_APP_NAME%% --" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:extractNativeLibs="true">
<activity android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation" android:name="org.qtproject.qt5.android.bindings.QtActivity" android:label="-- %%INSERT_APP_NAME%% --" android:screenOrientation="unspecified" android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
@@ -13,12 +13,10 @@
<meta-data android:name="android.app.bundled_libs_resource_id" android:resource="@array/bundled_libs"/>
<!-- Deploy Qt libs as part of package -->
<meta-data android:name="android.app.bundle_local_qt_libs" android:value="-- %%BUNDLE_LOCAL_QT_LIBS%% --"/>
- <meta-data android:name="android.app.bundled_in_lib_resource_id" android:resource="@array/bundled_in_lib"/>
- <meta-data android:name="android.app.bundled_in_assets_resource_id" android:resource="@array/bundled_in_assets"/>
<!-- Run with local libs -->
<meta-data android:name="android.app.use_local_qt_libs" android:value="-- %%USE_LOCAL_QT_LIBS%% --"/>
<meta-data android:name="android.app.libs_prefix" android:value="/data/local/tmp/qt/"/>
- <meta-data android:name="android.app.load_local_libs" android:value="-- %%INSERT_LOCAL_LIBS%% --"/>
+ <meta-data android:name="android.app.load_local_libs_resource_id" android:resource="@array/load_local_libs"/>
<meta-data android:name="android.app.load_local_jars" android:value="-- %%INSERT_LOCAL_JARS%% --"/>
<meta-data android:name="android.app.static_init_classes" android:value="-- %%INSERT_INIT_CLASSES%% --"/>
<!-- Messages maps -->
@@ -42,7 +40,7 @@
<!-- Background running -->
</activity>
</application>
- <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="16"/>
+ <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28"/>
<supports-screens android:largeScreens="true" android:normalScreens="true" android:anyDensity="true" android:smallScreens="true"/>
<!-- The following comment will be replaced upon deployment with default permissions based on the dependencies of the application.
diff --git a/examples/qt3d/planets-qml/doc/src/planets-qml.qdoc b/examples/qt3d/planets-qml/doc/src/planets-qml.qdoc
index 2dae457a0..a8c89fbe2 100644
--- a/examples/qt3d/planets-qml/doc/src/planets-qml.qdoc
+++ b/examples/qt3d/planets-qml/doc/src/planets-qml.qdoc
@@ -50,14 +50,14 @@
\section1 Qt Quick 2D Implementation
- The Qt Quick Implementation \l{planets-qml/PlanetsMain.qml}{PlanetsMain.qml} of the
+ The Qt Quick Implementation in \c {planets-qml/PlanetsMain.qml} of the
example renders the 3D content using the \c Scene3D type.
\snippet planets-qml/PlanetsMain.qml 0
The planet related information is stored into a \c{ListModel}. The selection buttons for the
planets and the information sheet are created based on the model. The 2D elements, selection
- buttons and sliders, are implemented in the \l{planets-qml/PlanetsMain.qml}{PlanetsMain.qml}.
+ buttons and sliders, are implemented in \c {planets-qml/PlanetsMain.qml}.
The selection buttons change the \c{focusedPlanet} property of the \c{mainview}. As the property
changes, the planet information is updated, and the camera is animated to the new position.
@@ -65,14 +65,14 @@
\snippet planets-qml/PlanetsMain.qml 1
The camera position and the camera look at point are updated based on values that are animated
- in the \l{planets-qml/SolarSystem.qml}{SolarSystem.qml}, triggered from the
+ in \c {planets-qml/SolarSystem.qml}, triggered from the
\c{changePlanetFocus()} function.
\snippet planets-qml/SolarSystem.qml 0
The sliders are used to adjust the rotation speed, the planet size, and the viewing distance.
- When a slider value changes, a JavaScript function in \l{planets-qml/SolarSystem.qml}
- {SolarSystem.qml} is called to adjust the given property. For example, changing the value of
+ When a slider value changes, a JavaScript function in \c {planets-qml/SolarSystem.qml}
+ is called to adjust the given property. For example, changing the value of
the \e{Viewing Distance} slider calls the \c{changeCameraDistance()} method.
\snippet planets-qml/PlanetsMain.qml 2
@@ -80,7 +80,7 @@
\section1 Qt 3D Implementation
The main part of the implementation, including the movement and rotation maths for the planets,
- is done in the \l{planets-qml/SolarSystem.qml}{SolarSystem.qml}.
+ is done in \c {planets-qml/SolarSystem.qml}.
First, a \c Camera, a \c{Light}, and a \c Configuration are added, followed by \c{Effect}s for
the planet \c{Material}s, and finally the planets themselves. For example, Earth is constructed
@@ -89,7 +89,7 @@
\snippet planets-qml/SolarSystem.qml 1
Planet data, which is needed for the movement and rotation calculations, among other things, is
- constructed with JavaScript in \l{planets-qml/planets.js}{planets.js} by calling
+ constructed with JavaScript in \c {planets-qml/planets.js} by calling
\c{loadPlanetData()} as the component completes. Other initializations, such as inserting the
planets into an array for easier handling, calculating the ring radii for Saturn and Uranus
rings, and setting the default scale, speed, and camera offset, are done as well:
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;
}
}
diff --git a/examples/qt3d/scene3d/AnimatedEntity.qml b/examples/qt3d/scene3d/AnimatedEntity.qml
index d1975cb47..77cc15aa3 100644
--- a/examples/qt3d/scene3d/AnimatedEntity.qml
+++ b/examples/qt3d/scene3d/AnimatedEntity.qml
@@ -49,15 +49,16 @@
****************************************************************************/
import Qt3D.Core 2.0
-import Qt3D.Render 2.0
+import Qt3D.Render 2.15
import Qt3D.Input 2.0
-import Qt3D.Extras 2.0
+import Qt3D.Extras 2.15
import QtQuick 2.0 as QQ2
Entity {
id: sceneRoot
+ property RenderCapabilities capabilities : renderSettings.renderCapabilities
Camera {
id: camera
@@ -74,9 +75,11 @@ Entity {
components: [
RenderSettings {
+ id: renderSettings
activeFrameGraph: ForwardRenderer {
camera: camera
clearColor: "transparent"
+ showDebugOverlay: true
}
},
InputSettings { }
diff --git a/examples/qt3d/scene3d/main.cpp b/examples/qt3d/scene3d/main.cpp
index 8886263f4..2a988a271 100644
--- a/examples/qt3d/scene3d/main.cpp
+++ b/examples/qt3d/scene3d/main.cpp
@@ -53,11 +53,25 @@
int main(int argc, char **argv)
{
+ {
+ // Set OpenGL requirements
+ QSurfaceFormat format = QSurfaceFormat::defaultFormat();
+#ifndef QT_OPENGL_ES_2
+ format.setVersion(4, 1);
+ format.setProfile(QSurfaceFormat::CoreProfile);
+ format.setSamples(4);
+#else
+ format.setVersion(3, 0);
+ format.setProfile(QSurfaceFormat::NoProfile);
+ format.setRenderableType(QSurfaceFormat::OpenGLES);
+#endif
+ QSurfaceFormat::setDefaultFormat(format);
+ }
QGuiApplication app(argc, 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/examples/qt3d/simple-qml/main.qml b/examples/qt3d/simple-qml/main.qml
index 5eed965ca..9f4149202 100644
--- a/examples/qt3d/simple-qml/main.qml
+++ b/examples/qt3d/simple-qml/main.qml
@@ -52,7 +52,7 @@ import QtQuick 2.2 as QQ2
import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Input 2.0
-import Qt3D.Extras 2.0
+import Qt3D.Extras 2.15
Entity {
id: sceneRoot
@@ -78,6 +78,7 @@ Entity {
activeFrameGraph: ForwardRenderer {
clearColor: Qt.rgba(0, 0.5, 1, 1)
camera: camera
+ showDebugOverlay: true
}
},
// Event Source will be set by the Qt3DQuickWindow
diff --git a/examples/qt3d/simplecustommaterial/doc/src/simplecustommaterial.qdoc b/examples/qt3d/simplecustommaterial/doc/src/simplecustommaterial.qdoc
index d10927d39..7ec7c7abb 100644
--- a/examples/qt3d/simplecustommaterial/doc/src/simplecustommaterial.qdoc
+++ b/examples/qt3d/simplecustommaterial/doc/src/simplecustommaterial.qdoc
@@ -48,7 +48,7 @@
\section1 Specifying the Material
- The material is specified in \l{simplecustommaterial/SimpleMaterial.qml}{SimpleMaterial.qml}
+ The material is specified in \c {simplecustommaterial/SimpleMaterial.qml}
using \l Material type. First the material specifies parameters,
which are mapped to the corresponding uniforms in the shaders so that they can be
changed from the qml.
diff --git a/qt3d.pro b/qt3d.pro
index d5dbda4b9..c5232e116 100644
--- a/qt3d.pro
+++ b/qt3d.pro
@@ -14,4 +14,5 @@ load(qt_parts)
#gcov: SUBDIRS -= sub_tools
OTHER_FILES += \
- sync.profile
+ sync.profile \
+ .qmake.conf
diff --git a/src/3rdparty/imgui/LICENSE.txt b/src/3rdparty/imgui/LICENSE.txt
new file mode 100644
index 000000000..21b6ee7e2
--- /dev/null
+++ b/src/3rdparty/imgui/LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2018 Omar Cornut
+
+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.
diff --git a/src/3rdparty/imgui/imconfig.h b/src/3rdparty/imgui/imconfig.h
new file mode 100644
index 000000000..3f48da1ac
--- /dev/null
+++ b/src/3rdparty/imgui/imconfig.h
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------------
+// COMPILE-TIME OPTIONS FOR DEAR IMGUI
+// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
+// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
+//-----------------------------------------------------------------------------
+// A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h)
+// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h"
+// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ dear imgui is used, which include
+// the imgui*.cpp files but also _any_ of your code that uses imgui. This is because some compile-time options have an affect on data structures.
+// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
+// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
+//-----------------------------------------------------------------------------
+
+#pragma once
+
+//---- Define assertion handler. Defaults to calling assert().
+//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
+//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
+
+//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
+//#define IMGUI_API __declspec( dllexport )
+//#define IMGUI_API __declspec( dllimport )
+
+//---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
+//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
+//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
+//---- It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp.
+//#define IMGUI_DISABLE_DEMO_WINDOWS
+
+//---- Don't implement some functions to reduce linkage requirements.
+//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc.
+#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow.
+#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function.
+//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf.
+//#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h.
+//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
+
+//---- Include imgui_user.h at the end of imgui.h as a convenience
+//#define IMGUI_INCLUDE_IMGUI_USER_H
+
+//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
+//#define IMGUI_USE_BGRA_PACKED_COLOR
+
+//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
+// By default the embedded implementations are declared static and not available outside of imgui cpp files.
+//#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
+
+//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
+// This will be inlined as part of ImVec2 and ImVec4 class declarations.
+/*
+#define IM_VEC2_CLASS_EXTRA \
+ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
+ operator MyVec2() const { return MyVec2(x,y); }
+
+#define IM_VEC4_CLASS_EXTRA \
+ ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
+ operator MyVec4() const { return MyVec4(x,y,z,w); }
+*/
+
+//---- Use 32-bit vertex indices (default is 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it.
+#define ImDrawIdx unsigned int
+
+//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
+/*
+namespace ImGui
+{
+ void MyFunction(const char* name, const MyMatrix44& v);
+}
+*/
diff --git a/src/3rdparty/imgui/imgui.cpp b/src/3rdparty/imgui/imgui.cpp
new file mode 100644
index 000000000..b6bf9dc09
--- /dev/null
+++ b/src/3rdparty/imgui/imgui.cpp
@@ -0,0 +1,9091 @@
+// dear imgui, v1.66b
+// (main code and documentation)
+
+// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
+// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
+// Get latest version at https://github.com/ocornut/imgui
+// Releases change-log at https://github.com/ocornut/imgui/releases
+// Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
+// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
+// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
+// This library is free but I need your support to sustain development and maintenance.
+// If you work for a company, please consider financial support, see README. For individuals: https://www.patreon.com/imgui
+
+// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
+// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
+// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
+// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
+// to a better solution or official support for them.
+
+/*
+
+Index of this file:
+
+DOCUMENTATION
+
+- MISSION STATEMENT
+- END-USER GUIDE
+- PROGRAMMER GUIDE (read me!)
+ - Read first
+ - How to update to a newer version of Dear ImGui
+ - Getting started with integrating Dear ImGui in your code/engine
+ - This is how a simple application may look like (2 variations)
+ - This is how a simple rendering function may look like
+ - Using gamepad/keyboard navigation controls
+- API BREAKING CHANGES (read me when you update!)
+- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
+ - How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
+ - How can I display an image? What is ImTextureID, how does it works?
+ - How can I have multiple widgets with the same label or without a label? A primer on labels and the ID Stack.
+ - How can I use my own math types instead of ImVec2/ImVec4?
+ - How can I load a different font than the default?
+ - How can I easily use icons in my application?
+ - How can I load multiple fonts?
+ - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
+ - How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
+ - I integrated Dear ImGui in my engine and the text or lines are blurry..
+ - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ - How can I help?
+
+CODE
+(search for "[SECTION]" in the code to find them)
+
+// [SECTION] FORWARD DECLARATIONS
+// [SECTION] CONTEXT AND MEMORY ALLOCATORS
+// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
+// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
+// [SECTION] MISC HELPER/UTILITIES (ImText* functions)
+// [SECTION] MISC HELPER/UTILITIES (Color functions)
+// [SECTION] ImGuiStorage
+// [SECTION] ImGuiTextFilter
+// [SECTION] ImGuiTextBuffer
+// [SECTION] ImGuiListClipper
+// [SECTION] RENDER HELPERS
+// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
+// [SECTION] TOOLTIPS
+// [SECTION] POPUPS
+// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
+// [SECTION] COLUMNS
+// [SECTION] DRAG AND DROP
+// [SECTION] LOGGING/CAPTURING
+// [SECTION] SETTINGS
+// [SECTION] PLATFORM DEPENDENT HELPERS
+// [SECTION] METRICS/DEBUG WINDOW
+
+*/
+
+//-----------------------------------------------------------------------------
+// DOCUMENTATION
+//-----------------------------------------------------------------------------
+
+/*
+
+ MISSION STATEMENT
+ =================
+
+ - Easy to use to create code-driven and data-driven tools
+ - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
+ - Easy to hack and improve
+ - Minimize screen real-estate usage
+ - Minimize setup and maintenance
+ - Minimize state storage on user side
+ - Portable, minimize dependencies, run on target (consoles, phones, etc.)
+ - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,
+ opening a tree node for the first time, etc. but a typical frame should not allocate anything)
+
+ Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
+ - Doesn't look fancy, doesn't animate
+ - Limited layout features, intricate layouts are typically crafted in code
+
+
+ END-USER GUIDE
+ ==============
+
+ - Double-click on title bar to collapse window.
+ - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
+ - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
+ - Click and drag on any empty space to move window.
+ - TAB/SHIFT+TAB to cycle through keyboard editable fields.
+ - CTRL+Click on a slider or drag box to input value as text.
+ - Use mouse wheel to scroll.
+ - Text editor:
+ - Hold SHIFT or use mouse to select text.
+ - CTRL+Left/Right to word jump.
+ - CTRL+Shift+Left/Right to select words.
+ - CTRL+A our Double-Click to select all.
+ - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
+ - CTRL+Z,CTRL+Y to undo/redo.
+ - ESCAPE to revert text to its original value.
+ - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
+ - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
+ - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
+ - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
+
+
+ PROGRAMMER GUIDE
+ ================
+
+ READ FIRST
+
+ - Read the FAQ below this section!
+ - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
+ or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
+ - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
+ - You can learn about immediate-mode GUI principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
+ See README.md for more links describing the IMGUI paradigm. Dear ImGui is an implementation of the IMGUI paradigm.
+
+ HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
+
+ - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
+ - Or maintain your own branch where you have imconfig.h modified.
+ - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
+ If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
+ from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
+ likely be a comment about it. Please report any issue to the GitHub page!
+ - Try to keep your copy of dear imgui reasonably up to date.
+
+ GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
+
+ - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
+ - Add the Dear ImGui source files to your projects or using your preferred build system.
+ It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
+ - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types.
+ - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
+ - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
+ Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
+ phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
+ - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
+ - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
+
+ HOW A SIMPLE APPLICATION MAY LOOK LIKE
+ EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder)
+
+ // Application init: create a dear imgui context, setup some options, load fonts
+ ImGui::CreateContext();
+ ImGuiIO& io = ImGui::GetIO();
+ // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
+ // TODO: Fill optional fields of the io structure later.
+ // TODO: Load TTF/OTF fonts if you don't want to use the default font.
+
+ // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
+ ImGui_ImplWin32_Init(hwnd);
+ ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
+
+ // Application main loop
+ while (true)
+ {
+ // Feed inputs to dear imgui, start new frame
+ ImGui_ImplDX11_NewFrame();
+ ImGui_ImplWin32_NewFrame();
+ ImGui::NewFrame();
+
+ // Any application code here
+ ImGui::Text("Hello, world!");
+
+ // Render dear imgui into screen
+ ImGui::Render();
+ ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
+ g_pSwapChain->Present(1, 0);
+ }
+
+ // Shutdown
+ ImGui_ImplDX11_Shutdown();
+ ImGui_ImplWin32_Shutdown();
+ ImGui::DestroyContext();
+
+ HOW A SIMPLE APPLICATION MAY LOOK LIKE
+ EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE
+
+ // Application init: create a dear imgui context, setup some options, load fonts
+ ImGui::CreateContext();
+ ImGuiIO& io = ImGui::GetIO();
+ // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
+ // TODO: Fill optional fields of the io structure later.
+ // TODO: Load TTF/OTF fonts if you don't want to use the default font.
+
+ // Build and load the texture atlas into a texture
+ // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
+ int width, height;
+ unsigned char* pixels = NULL;
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
+
+ // At this point you've got the texture data and you need to upload that your your graphic system:
+ // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
+ // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
+ MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
+ io.Fonts->TexID = (void*)texture;
+
+ // Application main loop
+ while (true)
+ {
+ // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
+ // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
+ io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
+ io.DisplaySize.x = 1920.0f; // set the current display width
+ io.DisplaySize.y = 1280.0f; // set the current display height here
+ io.MousePos = my_mouse_pos; // set the mouse position
+ io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
+ io.MouseDown[1] = my_mouse_buttons[1];
+
+ // Call NewFrame(), after this point you can use ImGui::* functions anytime
+ // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere)
+ ImGui::NewFrame();
+
+ // Most of your application code here
+ ImGui::Text("Hello, world!");
+ MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
+ MyGameRender(); // may use any ImGui functions as well!
+
+ // Render imgui, swap buffers
+ // (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code)
+ ImGui::EndFrame();
+ ImGui::Render();
+ ImDrawData* draw_data = ImGui::GetDrawData();
+ MyImGuiRenderFunction(draw_data);
+ SwapBuffers();
+ }
+
+ // Shutdown
+ ImGui::DestroyContext();
+
+ HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
+
+ void void MyImGuiRenderFunction(ImDrawData* draw_data)
+ {
+ // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
+ // TODO: Setup viewport using draw_data->DisplaySize
+ // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
+ // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
+ {
+ const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
+ const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
+ 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
+ {
+ // The texture for the draw call is specified by pcmd->TextureId.
+ // The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization.
+ MyEngineBindTexture((MyTexture*)pcmd->TextureId);
+
+ // We are using scissoring to clip some objects. All low-level graphics API should supports it.
+ // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
+ // (some elements visible outside their bounds) but you can fix that once everything else works!
+ // - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
+ // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
+ // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
+ // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
+ // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
+ ImVec2 pos = draw_data->DisplayPos;
+ MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
+
+ // Render 'pcmd->ElemCount/3' indexed triangles.
+ // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
+ MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
+ }
+ idx_buffer += pcmd->ElemCount;
+ }
+ }
+ }
+
+ - The examples/ folders contains many actual implementation of the pseudo-codes above.
+ - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
+ They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs
+ from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information.
+ - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
+
+ USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
+
+ - The gamepad/keyboard navigation is fairly functional and keeps being improved.
+ - Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
+ - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
+ - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
+ - Gamepad:
+ - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
+ - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
+ Note that io.NavInputs[] is cleared by EndFrame().
+ - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
+ 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
+ - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
+ Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
+ - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
+ - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
+ to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
+ - Keyboard:
+ - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
+ NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
+ - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
+ will be set. For more advanced uses, you may want to read from:
+ - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
+ - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
+ - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
+ Please reach out if you think the game vs navigation input sharing could be improved.
+ - Mouse:
+ - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
+ - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
+ - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
+ Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
+ When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
+ When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
+ (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
+ (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
+ to set a boolean to ignore your other external mouse positions until the external source is moved again.)
+
+
+ API BREAKING CHANGES
+ ====================
+
+ Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
+ Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
+ When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
+ You can read releases logs https://github.com/ocornut/imgui/releases for more details.
+
+ - 2018/10/12 (1.66) - Renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
+ - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
+ - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
+ If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
+ - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
+ - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
+ NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
+ Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
+ - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
+ - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
+ - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
+ - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges to enable the feature.
+ - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
+ - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
+ - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
+ - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
+ - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
+ - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
+ If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
+ To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
+ If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
+ - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
+ consistent with other functions. Kept redirection functions (will obsolete).
+ - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
+ - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
+ - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
+ - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
+ - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
+ - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
+ - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
+ - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
+ - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
+ - removed Shutdown() function, as DestroyContext() serve this purpose.
+ - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
+ - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
+ - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
+ - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
+ - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
+ - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
+ - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
+ - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
+ - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
+ - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
+ - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
+ - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
+ - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
+ - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
+ - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
+ - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
+ - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
+ - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
+ - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
+ Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
+ - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
+ - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
+ - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
+ - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
+ - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
+ - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
+ - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
+ removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
+ - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
+ - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
+ - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
+ - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
+ - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
+ - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
+ - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
+ - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
+ - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
+ - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
+ - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
+ - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
+ - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
+ - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
+ - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
+ - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
+ - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
+ - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
+ - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
+ - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
+ - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
+ - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
+ - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
+ - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
+ - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
+ If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
+ If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
+ This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
+ ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
+ {
+ float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
+ return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
+ }
+ If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
+ - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
+ - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
+ - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
+ - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
+ - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
+ - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
+ - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
+ - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
+ - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
+ - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
+ - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
+ - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
+ GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
+ GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
+ - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
+ - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
+ - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
+ - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
+ you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
+ - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
+ this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
+ - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
+ - the signature of the io.RenderDrawListsFn handler has changed!
+ old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
+ new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
+ argument: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
+ ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
+ ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
+ - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
+ - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
+ - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
+ - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
+ - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
+ - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
+ - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
+ - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
+ - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
+ - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
+ - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
+ - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
+ - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
+ - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
+ - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
+ - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
+ - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
+ - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
+ - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
+ - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
+ - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
+ - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
+ - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
+ - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->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 <stb_image.h>
+ [...]
+ 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<ImWchar> 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 <ctype.h> // toupper, isprint
+#include <stdio.h> // vsnprintf, sscanf, printf
+#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
+#include <stddef.h> // intptr_t
+#else
+#include <stdint.h> // 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<ImDrawList*>* out_list, ImDrawList* draw_list);
+static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window);
+static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* 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<ImWchar> 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<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
+{
+ ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
+ ImVector<ImGuiStorage::Pair>::iterator last = data.end();
+ size_t count = (size_t)(last - first);
+ while (count > 0)
+ {
+ size_t count2 = count >> 1;
+ ImVector<ImGuiStorage::Pair>::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<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(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<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
+ if (it == Data.end() || it->key != key)
+ return default_val;
+ return it->val_f;
+}
+
+void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
+{
+ ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(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<Pair>::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<Pair>::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<Pair>::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<Pair>::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<Pair>::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<Pair>::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<TextRange>* 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<ImGuiWindow*>* 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<ImDrawList*>* 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<ImDrawList*>* 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<ImDrawList*>& 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<ImDrawList*>* 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<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
+ if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
+ if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
+ if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
+ }
+ g.NavMoveClipDir = g.NavMoveDir;
+ }
+ else
+ {
+ // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
+ // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
+ IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
+ IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
+ g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
+ }
+
+ // Update PageUp/PageDown scroll
+ float nav_scoring_rect_offset_y = 0.0f;
+ if (nav_keyboard_active)
+ nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags);
+
+ // If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
+ if (g.NavMoveDir != ImGuiDir_None)
+ {
+ g.NavMoveRequest = true;
+ g.NavMoveDirLast = g.NavMoveDir;
+ }
+ if (g.NavMoveRequest && g.NavId == 0)
+ {
+ g.NavInitRequest = g.NavInitRequestFromMove = true;
+ g.NavInitResultId = 0;
+ g.NavDisableHighlight = false;
+ }
+ NavUpdateAnyRequestFlag();
+
+ // Scrolling
+ if (g.NavWindow && !(g.NavWindow->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 <Windows.h>
+#else
+#include <windows.h>
+#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<char> 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 <imm.h>
+#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<ImGuiWindow*>& 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]: <None>");
+ 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 <float.h> // FLT_MAX
+#include <stdarg.h> // va_list
+#include <stddef.h> // ptrdiff_t, NULL
+#include <string.h> // 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 <assert.h>
+#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 <stdint.h>
+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; // <unset> // 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]; // <unset> // 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; // <auto> // 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; // <unset> (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; // <unset> (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<typename T>
+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<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); }
+ inline ImVector<T>& operator=(const ImVector<T>& 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<value_type>& 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 <new> 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<typename T> 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<TextRange>* out) const;
+ };
+ char InputBuf[256];
+ ImVector<TextRange> Filters;
+ int CountGrep;
+};
+
+// Helper: Growable text buffer for logging/accumulating text
+// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder')
+struct ImGuiTextBuffer
+{
+ ImVector<char> 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<Pair> 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_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT))
+#define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white = 0xFFFFFFFF
+#define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black
+#define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000
+
+// Helper: ImColor() implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)
+// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API.
+// **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE.
+// **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed.
+struct ImColor
+{
+ ImVec4 Value;
+
+ ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; }
+ ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
+ ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>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<ImDrawCmd> CmdBuffer;
+ ImVector<ImDrawIdx> 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<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
+ ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
+ ImVector<ImDrawVert> 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<ImVec4> _ClipRectStack; // [Internal]
+ ImVector<ImTextureID> _TextureIdStack; // [Internal]
+ ImVector<ImVec2> _Path; // [Internal] current path building
+ int _ChannelsCurrent; // [Internal] current channel number (0)
+ int _ChannelsCount; // [Internal] number of active channels (1+)
+ ImVector<ImDrawChannel> _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<unsigned char> 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<ImWchar>* 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<ImFont*> 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<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
+ ImVector<ImFontConfig> 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; // <user set> // 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<ImFontGlyph> Glyphs; // // All glyphs.
+ ImVector<float> IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
+ ImVector<ImWchar> 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 : "<unknown>"; }
+
+ // '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 <stdio.h> // vsnprintf, sscanf, printf
+#if !defined(alloca)
+#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__)
+#include <alloca.h> // alloca (glibc uses <alloca.h>. Note that Cygwin may have _WIN32 defined, so the order matters here)
+#elif defined(_WIN32)
+#include <malloc.h> // alloca
+#if !defined(alloca)
+#define alloca _alloca // for clang with MS Codegen
+#endif
+#else
+#include <stdlib.h> // 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<ImVec2>* 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<ImDrawVert> 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<ImFontAtlas::CustomRect>& 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<stbrp_rect> 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<ImWchar>* 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^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#"
+ "`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL"
+ "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-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+`&#0j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N"
+ "*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cX&#2m#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)"
+ "tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX"
+ "ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::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[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G"
+ "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[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<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+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[K<L"
+ "%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#"
+ "OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)("
+ "h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h"
+ "o;#2:;%d&#x9v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`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<j$UpK<Q4a1]MupW^-"
+ "sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-"
+ "eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO"
+ "M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-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'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$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$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++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&VB<HFF*qL("
+ "$/V,;(kXZejWO`<[5?\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<"
+ "nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?"
+ "7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;"
+ ")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](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<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#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-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTG&#1T5g)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@aeg<Z'<$#4H)6,>e0jT6'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<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P&#9r+$%CE=68>K8r0=dSC%%(@p7"
+ ".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'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<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#"
+ "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#"
+ "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0"
+ "d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoF&#4DoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8"
+ "6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#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^xBdLjL<Lni;''X.`$#8+1GD"
+ ":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+"
+ "tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*"
+ "$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7"
+ ":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A"
+ "7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7"
+ "u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT"
+ "LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M"
+ ":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>"
+ "_>@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'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>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<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%"
+ "9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$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,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY"
+ "8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-"
+ "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`"
+ "0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/"
+ "+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*: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&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V"
+ "?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK"
+ "Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa"
+ ">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>"
+ "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^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'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#"
+ "Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$"
+ "MlvAF_jCK*.O-^(63adMT->W%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*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'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<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>"
+ "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#"
+ "d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4&#3^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#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#"
+ "m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#"
+ "TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)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 <stdio.h> // FILE*
+#include <stdlib.h> // NULL, malloc, free, qsort, atoi, atof
+#include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf
+#include <limits.h> // 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<typename T> static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; }
+template<typename T> static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; }
+template<typename T> static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
+template<typename T> static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); }
+template<typename T> 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<typename T>
+struct IMGUI_API ImPool
+{
+ ImVector<T> 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<ImWchar> 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<char> InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered)
+ ImVector<char> 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<ImGuiColumnData> 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<ImDrawList*> 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<ImGuiWindow*> Windows; // Windows, sorted in display order, back to front
+ ImVector<ImGuiWindow*> WindowsFocusOrder; // Windows, sorted in focus order, back to front
+ ImVector<ImGuiWindow*> WindowsSortBuffer;
+ ImVector<ImGuiWindow*> 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<ImGuiColorMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
+ ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
+ ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont()
+ ImVector<ImGuiPopupRef> OpenPopupStack; // Which popups are open (persistent)
+ ImVector<ImGuiPopupRef> 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<unsigned char> 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<char> 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<ImGuiSettingsHandler> SettingsHandlers; // List of .ini settings handlers
+ ImVector<ImGuiWindowSettings> 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<ImGuiWindow*> 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]
+ ImVector<ImGuiItemFlags>ItemFlagsStack;
+ ImVector<float> ItemWidthStack;
+ ImVector<float> TextWrapPosStack;
+ ImVector<ImGuiGroupData>GroupStack;
+ 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<ImGuiID> 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<ImGuiColumnsSet> 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<float, float>(const char* format, ImGuiDataType data_type, float v); "
+ template<typename T, typename SIGNED_T, typename FLOAT_T> 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<typename T, typename SIGNED_T, typename FLOAT_T> 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<typename T, typename FLOAT_T> IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos);
+ template<typename T, typename SIGNED_T> 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 <ctype.h> // toupper, isprint
+#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
+#include <stddef.h> // intptr_t
+#else
+#include <stdint.h> // 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 | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
+ // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
+ // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
+ // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
+ // 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 <on release>
+ 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 <on release>
+ 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<typename TYPE>
+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<typename TYPE, typename SIGNEDTYPE>
+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<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
+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<TYPE, SIGNEDTYPE>(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<ImS32, ImS32, float >(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<ImU32, ImS32, float >(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<ImS64, ImS64, double>(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<ImU64, ImS64, double>(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<float, float, float >(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<double,double,double>(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<typename TYPE, typename FLOATTYPE>
+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<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
+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<TYPE,FLOATTYPE>(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<TYPE,SIGNEDTYPE>(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<TYPE,FLOATTYPE>(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<ImS32, ImS32, float >(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<ImU32, ImS32, float >(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<ImS64, ImS64, double>(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<ImU64, ImS64, double>(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<float, float, float >(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<double,double,double>(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<int>(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 <stdlib.h>
+#define STBRP_SORT qsort
+#endif
+
+#ifndef STBRP_ASSERT
+#include <assert.h>
+#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 <string.h>
+#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 <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,
+// then the character should be displayed in the rectangle from
+// <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).
+//
+// Advancing for the next character:
+// Call GlyphHMetrics, and compute 'current_point += SF * advance'.
+//
+//
+// ADVANCED USAGE
+//
+// Quality:
+//
+// - Use the functions with Subpixel at the end to allow your characters
+// to have subpixel positioning. Since the font is anti-aliased, not
+// hinted, this is very import for quality. (This is not possible with
+// baked fonts.)
+//
+// - Kerning is now supported, and if you're supporting subpixel rendering
+// then kerning is worth using to give your text a polished look.
+//
+// Performance:
+//
+// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
+// if you don't do this, stb_truetype is forced to do the conversion on
+// every call.
+//
+// - There are a lot of memory allocations. We should modify it to take
+// a temp buffer and allocate from the temp buffer (without freeing),
+// should help performance a lot.
+//
+// NOTES
+//
+// The system uses the raw data found in the .ttf file without changing it
+// and without building auxiliary data structures. This is a bit inefficient
+// on little-endian systems (the data is big-endian), but assuming you're
+// caching the bitmaps or glyph shapes this shouldn't be a big deal.
+//
+// It appears to be very hard to programmatically determine what font a
+// given file is in a general way. I provide an API for this, but I don't
+// recommend it.
+//
+//
+// SOURCE STATISTICS (based on v0.6c, 2050 LOC)
+//
+// Documentation & header file 520 LOC \___ 660 LOC documentation
+// Sample code 140 LOC /
+// Truetype parsing 620 LOC ---- 620 LOC TrueType
+// Software rasterization 240 LOC \ .
+// Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
+// Bitmap management 100 LOC /
+// Baked bitmap interface 70 LOC /
+// Font name matching & access 150 LOC ---- 150
+// C runtime library abstraction 60 LOC ---- 60
+//
+//
+// PERFORMANCE MEASUREMENTS FOR 1.06:
+//
+// 32-bit 64-bit
+// Previous release: 8.83 s 7.68 s
+// Pool allocations: 7.72 s 6.34 s
+// Inline sort : 6.54 s 5.65 s
+// New rasterizer : 5.63 s 5.00 s
+
+//////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////
+////
+//// SAMPLE PROGRAMS
+////
+//
+// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
+//
+#if 0
+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
+#include "stb_truetype.h"
+
+unsigned char ttf_buffer[1<<20];
+unsigned char temp_bitmap[512*512];
+
+stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
+GLuint ftex;
+
+void my_stbtt_initfont(void)
+{
+ fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
+ stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
+ // can free ttf_buffer at this point
+ glGenTextures(1, &ftex);
+ glBindTexture(GL_TEXTURE_2D, ftex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
+ // can free temp_bitmap at this point
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+}
+
+void my_stbtt_print(float x, float y, char *text)
+{
+ // assume orthographic projection with units = screen pixels, origin at top left
+ glEnable(GL_TEXTURE_2D);
+ glBindTexture(GL_TEXTURE_2D, ftex);
+ glBegin(GL_QUADS);
+ while (*text) {
+ if (*text >= 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 <stdio.h>
+#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 <math.h>
+ #define STBTT_ifloor(x) ((int) floor(x))
+ #define STBTT_iceil(x) ((int) ceil(x))
+ #endif
+
+ #ifndef STBTT_sqrt
+ #include <math.h>
+ #define STBTT_sqrt(x) sqrt(x)
+ #define STBTT_pow(x,y) pow(x,y)
+ #endif
+
+ #ifndef STBTT_fmod
+ #include <math.h>
+ #define STBTT_fmod(x,y) fmod(x,y)
+ #endif
+
+ #ifndef STBTT_cos
+ #include <math.h>
+ #define STBTT_cos(x) cos(x)
+ #define STBTT_acos(x) acos(x)
+ #endif
+
+ #ifndef STBTT_fabs
+ #include <math.h>
+ #define STBTT_fabs(x) fabs(x)
+ #endif
+
+ // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
+ #ifndef STBTT_malloc
+ #include <stdlib.h>
+ #define STBTT_malloc(x,u) ((void)(u),malloc(x))
+ #define STBTT_free(x,u) ((void)(u),free(x))
+ #endif
+
+ #ifndef STBTT_assert
+ #include <assert.h>
+ #define STBTT_assert(x) assert(x)
+ #endif
+
+ #ifndef STBTT_strlen
+ #include <string.h>
+ #define STBTT_strlen(x) strlen(x)
+ #endif
+
+ #ifndef STBTT_memcpy
+ #include <string.h>
+ #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<lookupCount; ++i) {
+ stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);
+ stbtt_uint8 *lookupTable = lookupList + lookupOffset;
+
+ stbtt_uint16 lookupType = ttUSHORT(lookupTable);
+ stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);
+ stbtt_uint8 *subTableOffsets = lookupTable + 6;
+ switch(lookupType) {
+ case 2: { // Pair Adjustment Positioning Subtable
+ stbtt_int32 sti;
+ for (sti=0; sti<subTableCount; sti++) {
+ stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);
+ stbtt_uint8 *table = lookupTable + subtableOffset;
+ stbtt_uint16 posFormat = ttUSHORT(table);
+ stbtt_uint16 coverageOffset = ttUSHORT(table + 2);
+ stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);
+ if (coverageIndex == -1) continue;
+
+ switch (posFormat) {
+ case 1: {
+ stbtt_int32 l, r, m;
+ int straw, needle;
+ stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);
+ stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);
+ stbtt_int32 valueRecordPairSizeInBytes = 2;
+ stbtt_uint16 pairSetCount = ttUSHORT(table + 8);
+ stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);
+ stbtt_uint8 *pairValueTable = table + pairPosOffset;
+ stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);
+ stbtt_uint8 *pairValueArray = pairValueTable + 2;
+ // 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;
+
+ STBTT_assert(coverageIndex < pairSetCount);
+ STBTT__NOTUSED(pairSetCount);
+
+ needle=glyph2;
+ r=pairValueCount-1;
+ l=0;
+
+ // Binary search.
+ while (l <= r) {
+ stbtt_uint16 secondGlyph;
+ stbtt_uint8 *pairValue;
+ m = (l + r) >> 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 && mid<n: 0>n => n; 0<n => 0 */
+ /* 0<mid && mid>n: 0>n => 0; 0<n => 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/animation/animation.pro b/src/animation/animation.pro
index 9c5db68f2..53d448d54 100644
--- a/src/animation/animation.pro
+++ b/src/animation/animation.pro
@@ -1,6 +1,7 @@
TARGET = Qt3DAnimation
DEFINES += QT3DANIMATION_LIBRARY
+DEFINES += BUILD_QT3D_MODULE
MODULE = 3danimation
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<AnimationCallbackAndValue> 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<HBlendedClipAnimator> &blendedClipAnimatorHandles)
diff --git a/src/animation/backend/channelmapping.cpp b/src/animation/backend/channelmapping.cpp
index cf4511279..1e3aa76f0 100644
--- a/src/animation/backend/channelmapping.cpp
+++ b/src/animation/backend/channelmapping.cpp
@@ -105,9 +105,9 @@ void ChannelMapping::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs
const QCallbackMapping *callbackMapping = qobject_cast<const QCallbackMapping *>(frontEnd);
if (callbackMapping) {
m_mappingType = ChannelMappingType;
- m_channelName = channelMapping->channelName();
+ m_channelName = callbackMapping->channelName();
- const QCallbackMappingPrivate *d = static_cast<const QCallbackMappingPrivate *>(Qt3DCore::QNodePrivate::get(channelMapping));
+ const QCallbackMappingPrivate *d = static_cast<const QCallbackMappingPrivate *>(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<HClipAnimator> &clipAnimatorHandles)
diff --git a/src/animation/backend/gltfimporter.cpp b/src/animation/backend/gltfimporter.cpp
index 521a0742d..f7907b3c2 100644
--- a/src/animation/backend/gltfimporter.cpp
+++ b/src/animation/backend/gltfimporter.cpp
@@ -35,6 +35,9 @@
****************************************************************************/
#include "gltfimporter_p.h"
+
+#include <Qt3DCore/private/qloadgltf_p.h>
+
#include <Qt3DAnimation/private/animationlogging_p.h>
#include <Qt3DAnimation/private/fcurve_p.h>
#include <Qt3DAnimation/private/keyframe_p.h>
@@ -434,10 +437,7 @@ GLTFImporter::GLTFImporter()
bool GLTFImporter::load(QIODevice *ioDev)
{
- QByteArray jsonData = ioDev->readAll();
- QJsonDocument sceneDocument = QJsonDocument::fromJson(jsonData);
-
- if (Q_UNLIKELY(!setJSON(sceneDocument))) {
+ if (Q_UNLIKELY(!setJSON(qLoadGLTF(ioDev->readAll())))) {
qWarning("not a JSON document");
return false;
}
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/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 <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qabstractskeleton_p.h>
QT_BEGIN_NAMESPACE
diff --git a/src/animation/frontend/qabstractanimationclip.cpp b/src/animation/frontend/qabstractanimationclip.cpp
index e662a1408..08133072c 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 <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -122,7 +121,7 @@ void QAbstractAnimationClipPrivate::setDuration(float duration)
animator->setRunning(true);
\endcode
- \sa QAnimationClip, QAnimationClipLoader
+ \sa Qt3DAnimation::QAnimationClip, Qt3DAnimation::QAnimationClipLoader
*/
/*!
@@ -134,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/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/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/qanimationcallback.qdoc b/src/animation/frontend/qanimationcallback.qdoc
new file mode 100644
index 000000000..5c6e8e212
--- /dev/null
+++ b/src/animation/frontend/qanimationcallback.qdoc
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the documentation of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:FDL$
+** 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 Free Documentation License Usage
+** Alternatively, this file may be used under the terms of the GNU Free
+** Documentation License version 1.3 as published by the Free Software
+** Foundation and appearing in the file included in the packaging of
+** this file. Please review the following information to ensure
+** the GNU Free Documentation License version 1.3 requirements
+** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+/*!
+ \class Qt3DAnimation::QAnimationCallback
+ \inmodule Qt3DAnimation
+ \brief Represents an animation callback object.
+*/
+
+/*!
+ \enum Qt3DAnimation::QAnimationCallback::Flag
+
+ Flags to indicate how the valueChanged() function is called.
+
+ \value OnOwningThread
+ Callback function is called on the owning (GUI or main) thread.
+ \value OnThreadPool
+ Callback function is called on the thread pool's worker thread.
+*/
+
+/*!
+ \fn Qt3DAnimation::QAnimationCallback::valueChanged(const QVariant &value)
+
+ Callback function that is triggered for changes in the animated \a value.
+
+ \sa QCallbackMapping::setCallback()
+*/
diff --git a/src/animation/frontend/qanimationclip.cpp b/src/animation/frontend/qanimationclip.cpp
index d624a246a..74a9b8371 100644
--- a/src/animation/frontend/qanimationclip.cpp
+++ b/src/animation/frontend/qanimationclip.cpp
@@ -51,8 +51,8 @@ QAnimationClipPrivate::QAnimationClipPrivate()
}
/*!
- \class QAnimationClip
- \inherits QAbstractAnimationClip
+ \class Qt3DAnimation::QAnimationClip
+ \inherits Qt3dAnimation::QAbstractAnimationClip
\inmodule Qt3DAnimation
\brief Specifies key frame animation data.
*/
diff --git a/src/animation/frontend/qanimationclipdata.cpp b/src/animation/frontend/qanimationclipdata.cpp
index 49de71e79..e105b7b43 100644
--- a/src/animation/frontend/qanimationclipdata.cpp
+++ b/src/animation/frontend/qanimationclipdata.cpp
@@ -53,7 +53,7 @@ public:
};
/*!
- \class QAnimationClipData
+ \class Qt3DAnimation::QAnimationClipData
\inmodule Qt3DAnimation
\brief Class containing the animation data.
*/
diff --git a/src/animation/frontend/qanimationcliploader.cpp b/src/animation/frontend/qanimationcliploader.cpp
index 446995b17..bf901e54f 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 <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -113,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/animation/frontend/qcallbackmapping.cpp b/src/animation/frontend/qcallbackmapping.cpp
index 435191b2d..a86785012 100644
--- a/src/animation/frontend/qcallbackmapping.cpp
+++ b/src/animation/frontend/qcallbackmapping.cpp
@@ -56,7 +56,7 @@ QCallbackMappingPrivate::QCallbackMappingPrivate()
}
/*!
- \class QCallbackMapping
+ \class Qt3DAnimation::QCallbackMapping
\inherits Qt3DCore::QAbstractChannelMapping
\inmodule Qt3DAnimation
\brief Allows to map the channels within the clip onto an invocation
diff --git a/src/animation/frontend/qchannel.cpp b/src/animation/frontend/qchannel.cpp
index eab7f0df4..1e0da3c3f 100644
--- a/src/animation/frontend/qchannel.cpp
+++ b/src/animation/frontend/qchannel.cpp
@@ -54,7 +54,7 @@ public:
};
/*!
- \class QChannel
+ \class Qt3DAnimation::QChannel
\inmodule Qt3DAnimation
\brief Defines a channel for a QAnimationClipData.
The animation system interpolates each channel component independently
diff --git a/src/animation/frontend/qchannelmapper.cpp b/src/animation/frontend/qchannelmapper.cpp
index ab98039b4..c5909adbc 100644
--- a/src/animation/frontend/qchannelmapper.cpp
+++ b/src/animation/frontend/qchannelmapper.cpp
@@ -49,7 +49,7 @@ QChannelMapperPrivate::QChannelMapperPrivate()
}
/*!
- \class QChannelMapper
+ \class Qt3DAnimation::QChannelMapper
\inmodule Qt3DAnimation
\brief Allows to map the channels within the clip onto properties of
objects in the application.
diff --git a/src/animation/frontend/qchannelmapping.cpp b/src/animation/frontend/qchannelmapping.cpp
index 59620ab49..16651afe6 100644
--- a/src/animation/frontend/qchannelmapping.cpp
+++ b/src/animation/frontend/qchannelmapping.cpp
@@ -161,7 +161,7 @@ void QChannelMappingPrivate::updatePropertyNameTypeAndComponentCount()
}
/*!
- \class QChannelMapping
+ \class Qt3DAnimation::QChannelMapping
\inherits Qt3DCore::QNode
\inmodule Qt3DAnimation
\brief Allows to map the channels within the clip onto properties of
diff --git a/src/animation/frontend/qclipanimator.cpp b/src/animation/frontend/qclipanimator.cpp
index 03510aa93..ffad588c1 100644
--- a/src/animation/frontend/qclipanimator.cpp
+++ b/src/animation/frontend/qclipanimator.cpp
@@ -107,7 +107,8 @@ bool QClipAnimatorPrivate::canPlay() const
The properties for controlling the animator are provided by the QAbstractClipAnimator base
class.
- \sa QAbstractClipAnimator, QAbstractAnimationClip, QChannelMapper, QBlendedClipAnimator
+ \sa Qt3DAnimation::QAbstractClipAnimator, Qt3DAnimation::QAbstractAnimationClip,
+ Qt3DAnimation::QChannelMapper, Qt3DAnimation::QBlendedClipAnimator
*/
QClipAnimator::QClipAnimator(Qt3DCore::QNode *parent)
diff --git a/src/animation/frontend/qclipblendvalue.cpp b/src/animation/frontend/qclipblendvalue.cpp
index 72a7dd796..053453e33 100644
--- a/src/animation/frontend/qclipblendvalue.cpp
+++ b/src/animation/frontend/qclipblendvalue.cpp
@@ -53,14 +53,14 @@ QClipBlendValuePrivate::QClipBlendValuePrivate()
}
/*!
- \class QClipBlendValue
+ \class Qt3DAnimation::QClipBlendValue
\inherits Qt3DAnimation::QAbstractClipBlendNode
\inmodule Qt3DAnimation
\brief Class used for including a clip in a blend tree.
*/
/*!
\qmltype ClipBlendValue
- \instantiates QClipBlendValue
+ \instantiates Qt3DAnimation::QClipBlendValue
\inqmlmodule Qt3D.Animation
\brief Type used for including a clip in a blend tree.
*/
diff --git a/src/animation/frontend/qmorphtarget.cpp b/src/animation/frontend/qmorphtarget.cpp
index 76b1a598e..da068d477 100644
--- a/src/animation/frontend/qmorphtarget.cpp
+++ b/src/animation/frontend/qmorphtarget.cpp
@@ -86,8 +86,8 @@ namespace Qt3DAnimation {
*/
/*!
\qmlmethod MorphTarget Qt3D.Animation::MorphTarget::fromGeometry(geometry, stringList)
- Returns a morph target based on the attributes defined by the given stringList from
- the given geometry.
+ Returns a morph target based on the attributes defined by the given \a stringList from
+ the given \a geometry.
*/
QMorphTargetPrivate::QMorphTargetPrivate()
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<Qt3DRender::QAttribute *> baseAttributes = m_currentBase->attributeList();
const QVector<Qt3DRender::QAttribute *> targetAttributes = m_currentTarget->attributeList();
for (int i = 0; i < baseAttributes.size(); ++i) {
diff --git a/src/core/aspects/aspectcommanddebugger.cpp b/src/core/aspects/aspectcommanddebugger.cpp
index eceec1bbd..7635f44c0 100644
--- a/src/core/aspects/aspectcommanddebugger.cpp
+++ b/src/core/aspects/aspectcommanddebugger.cpp
@@ -39,12 +39,12 @@
#include "aspectcommanddebugger_p.h"
-#include <Qt3DCore/qaspectengine.h>
#include <QtNetwork/QTcpSocket>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <Qt3DCore/private/qabstractaspect_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p.h>
QT_BEGIN_NAMESPACE
@@ -64,13 +64,6 @@ struct CommandHeader
} // anonymous
-AspectCommandDebugger::ReadBuffer::ReadBuffer()
- : buffer()
- , startIdx(0)
- , endIdx(0)
-{
-}
-
void AspectCommandDebugger::ReadBuffer::insert(const QByteArray &array)
{
buffer.insert(endIdx, array);
@@ -88,9 +81,9 @@ void AspectCommandDebugger::ReadBuffer::trim()
}
}
-AspectCommandDebugger::AspectCommandDebugger(QObject *parent)
+AspectCommandDebugger::AspectCommandDebugger(QSystemInformationService *parent)
: QTcpServer(parent)
- , m_aspectEngine(nullptr)
+ , m_service(parent)
{
}
@@ -115,11 +108,6 @@ void AspectCommandDebugger::initialize()
qWarning() << Q_FUNC_INFO << "failed to listen on port 8883";
}
-void AspectCommandDebugger::setAspectEngine(QAspectEngine *engine)
-{
- m_aspectEngine = engine;
-}
-
void AspectCommandDebugger::asynchronousReplyFinished(AsynchronousCommandReply *reply)
{
Q_ASSERT(reply->isFinished());
@@ -189,7 +177,7 @@ void AspectCommandDebugger::executeCommand(const QString &command,
QTcpSocket *socket)
{
// Only a single aspect is going to reply
- const QVariant response = m_aspectEngine->executeCommand(command);
+ const QVariant response = m_service->executeCommand(command);
if (response.userType() == qMetaTypeId<AsynchronousCommandReply *>()) { // AsynchronousCommand
// Store the command | socket in a table
AsynchronousCommandReply *reply = response.value<AsynchronousCommandReply *>();
diff --git a/src/core/aspects/aspectcommanddebugger_p.h b/src/core/aspects/aspectcommanddebugger_p.h
index bb6100df5..b39708ab1 100644
--- a/src/core/aspects/aspectcommanddebugger_p.h
+++ b/src/core/aspects/aspectcommanddebugger_p.h
@@ -54,32 +54,30 @@
//
#include <QTcpServer>
+#include <Qt3DCore/private/qt3dcore_global_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
-class QAspectEngine;
+class QSystemInformationService;
namespace Debug {
class AsynchronousCommandReply;
-class Q_AUTOTEST_EXPORT AspectCommandDebugger : public QTcpServer
+class Q_3DCORE_PRIVATE_EXPORT AspectCommandDebugger : public QTcpServer
{
Q_OBJECT
public:
- explicit AspectCommandDebugger(QObject *parent = nullptr);
+ explicit AspectCommandDebugger(QSystemInformationService *parent = nullptr);
void initialize();
- void setAspectEngine(QAspectEngine *engine);
-
- struct ReadBuffer {
- ReadBuffer();
+ struct Q_3DCORE_PRIVATE_EXPORT ReadBuffer {
QByteArray buffer;
- int startIdx;
- int endIdx;
+ int startIdx = 0;
+ int endIdx = 0;
inline int size() const { return endIdx - startIdx; }
void insert(const QByteArray &array);
@@ -95,7 +93,7 @@ private:
void executeCommand(const QString &command, QTcpSocket *socket);
QVector<QTcpSocket *> m_connections;
- QAspectEngine *m_aspectEngine;
+ QSystemInformationService *m_service;
ReadBuffer m_readBuffer;
QHash<AsynchronousCommandReply *, QTcpSocket *> m_asyncCommandToSocketEntries;
diff --git a/src/core/aspects/aspects.pri b/src/core/aspects/aspects.pri
index 5e8327192..268a2fc37 100644
--- a/src/core/aspects/aspects.pri
+++ b/src/core/aspects/aspects.pri
@@ -1,10 +1,9 @@
-#DEFINES += QT3D_CORE_JOB_TIMING
-
SOURCES += \
$$PWD/qabstractaspect.cpp \
$$PWD/qaspectengine.cpp \
$$PWD/qaspectfactory.cpp \
- $$PWD/qaspectmanager.cpp
+ $$PWD/qaspectmanager.cpp \
+ $$PWD/aspectcommanddebugger.cpp
HEADERS += \
$$PWD/qabstractaspect.h \
@@ -12,13 +11,10 @@ HEADERS += \
$$PWD/qabstractaspect_p.h \
$$PWD/qaspectengine_p.h \
$$PWD/qaspectfactory_p.h \
- $$PWD/qaspectmanager_p.h
+ $$PWD/qaspectmanager_p.h \
+ $$PWD/aspectcommanddebugger_p.h
INCLUDEPATH += $$PWD
include($$QT3D_BUILD_ROOT/src/core/qt3dcore-config.pri)
QT_FOR_CONFIG += 3dcore-private
-qtConfig(qt3d-profile-jobs): {
- HEADERS += $$PWD/aspectcommanddebugger_p.h
- SOURCES += $$PWD/aspectcommanddebugger.cpp
-}
diff --git a/src/core/aspects/qabstractaspect.cpp b/src/core/aspects/qabstractaspect.cpp
index 05afdd293..824434ce6 100644
--- a/src/core/aspects/qabstractaspect.cpp
+++ b/src/core/aspects/qabstractaspect.cpp
@@ -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<QAspectJobPtr> QAbstractAspect::jobsToExecute(qint64 time)
{
- Q_UNUSED(time);
+ Q_UNUSED(time)
return QVector<QAspectJobPtr>();
}
-void QAbstractAspect::syncDirtyFrontEndNodes(const QVector<QNode *> &nodes)
-{
- Q_D(QAbstractAspect);
- d->syncDirtyFrontEndNodes(nodes);
-}
-
-void QAbstractAspect::syncDirtyFrontEndSubNodes(const QVector<NodeRelationshipChange> &nodes)
-{
- Q_D(QAbstractAspect);
- d->syncDirtyFrontEndSubNodes(nodes);
-}
-
QAbstractAspectPrivate::BackendNodeMapperAndInfo QAbstractAspectPrivate::mapperForNode(const QMetaObject *metaObj) const
{
Q_ASSERT(metaObj);
@@ -520,6 +508,14 @@ QVector<QAspectJobPtr> QAbstractAspectPrivate::jobsToExecute(qint64 time)
return res;
}
+void QAbstractAspectPrivate::jobsDone()
+{
+}
+
+void QAbstractAspectPrivate::frameDone()
+{
+}
+
/*!
* Called in the context of the aspect thread once the aspect has been registered.
* This provides an opportunity for the aspect to do any initialization tasks that
diff --git a/src/core/aspects/qabstractaspect.h b/src/core/aspects/qabstractaspect.h
index 8059421a6..3b2f31c50 100644
--- a/src/core/aspects/qabstractaspect.h
+++ b/src/core/aspects/qabstractaspect.h
@@ -87,9 +87,6 @@ protected:
void unregisterBackendType(const QMetaObject &);
private:
- void syncDirtyFrontEndNodes(const QVector<QNode *> &nodes);
- void syncDirtyFrontEndSubNodes(const QVector<NodeRelationshipChange> &nodes);
-
virtual QVariant executeCommand(const QStringList &args);
virtual QVector<QAspectJobPtr> jobsToExecute(qint64 time);
diff --git a/src/core/aspects/qabstractaspect_p.h b/src/core/aspects/qabstractaspect_p.h
index 670302cfa..dd13ac5bf 100644
--- a/src/core/aspects/qabstractaspect_p.h
+++ b/src/core/aspects/qabstractaspect_p.h
@@ -57,6 +57,7 @@
#include <Qt3DCore/private/qaspectjobproviderinterface_p.h>
#include <Qt3DCore/private/qbackendnode_p.h>
#include <Qt3DCore/private/qt3dcore_global_p.h>
+#include <Qt3DCore/private/qscenechange_p.h>
#include <QtCore/private/qobject_p.h>
#include <QMutex>
@@ -126,6 +127,8 @@ public:
QAbstractAspectJobManager *jobManager() const;
QVector<QAspectJobPtr> jobsToExecute(qint64 time) 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/qaspectengine.cpp b/src/core/aspects/qaspectengine.cpp
index 426741a61..d28306197 100644
--- a/src/core/aspects/qaspectengine.cpp
+++ b/src/core/aspects/qaspectengine.cpp
@@ -55,12 +55,9 @@
#include <Qt3DCore/private/qpostman_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qservicelocator_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p.h>
#include <Qt3DCore/qt3dcore-config.h>
-#if QT_CONFIG(qt3d_profile_jobs)
-#include <Qt3DCore/private/aspectcommanddebugger_p.h>
-#endif
-
QT_BEGIN_NAMESPACE
namespace{
@@ -122,9 +119,6 @@ QAspectEnginePrivate::QAspectEnginePrivate()
, m_scene(nullptr)
, m_initialized(false)
, m_runMode(QAspectEngine::Automatic)
- #if QT_CONFIG(qt3d_profile_jobs)
- , m_commandDebugger(new Debug::AspectCommandDebugger(q_func()))
- #endif
{
qRegisterMetaType<Qt3DCore::QAbstractAspect *>();
qRegisterMetaType<Qt3DCore::QObserverInterface *>();
@@ -276,10 +270,6 @@ void QAspectEnginePrivate::initialize()
arbiter->setScene(m_scene);
m_initialized = true;
m_aspectManager->setPostConstructorInit(m_scene->postConstructorInit());
-#if QT_CONFIG(qt3d_profile_jobs)
- m_commandDebugger->setAspectEngine(q_func());
- m_commandDebugger->initialize();
-#endif
}
/*!
@@ -419,16 +409,8 @@ QVariant QAspectEngine::executeCommand(const QString &command)
if (d->m_aspects.isEmpty())
return QLatin1String("No loaded aspect");
- QString reply;
- reply += QLatin1String("Loaded aspects:");
- for (QAbstractAspect *aspect : qAsConst(d->m_aspects)) {
- const QString name = d->m_factory.aspectName(aspect);
- if (!name.isEmpty())
- reply += QLatin1String("\n * ") + name;
- else
- reply += QLatin1String("\n * <unnamed>");
- }
- return reply;
+ const QStringList names = d->m_aspectManager->serviceLocator()->systemInformation()->aspectNames();
+ return names.join(QLatin1String("\n"));
}
QStringList args = command.split(QLatin1Char(' '));
diff --git a/src/core/aspects/qaspectengine_p.h b/src/core/aspects/qaspectengine_p.h
index c83940435..8f3abcd38 100644
--- a/src/core/aspects/qaspectengine_p.h
+++ b/src/core/aspects/qaspectengine_p.h
@@ -69,12 +69,6 @@ class QAspectManager;
class QPostman;
class QScene;
-#if QT_CONFIG(qt3d_profile_jobs)
-namespace Debug {
-class AspectCommandDebugger;
-} // Debug
-#endif
-
class Q_3DCORE_PRIVATE_EXPORT QAspectEnginePrivate : public QObjectPrivate
{
public:
@@ -93,10 +87,6 @@ public:
bool m_initialized;
QAspectEngine::RunMode m_runMode;
-#if QT_CONFIG(qt3d_profile_jobs)
- Debug::AspectCommandDebugger *m_commandDebugger;
-#endif
-
void initialize();
void shutdown();
diff --git a/src/core/aspects/qaspectmanager.cpp b/src/core/aspects/qaspectmanager.cpp
index 71e05b34f..f0dc366b2 100644
--- a/src/core/aspects/qaspectmanager.cpp
+++ b/src/core/aspects/qaspectmanager.cpp
@@ -57,6 +57,7 @@
#include <Qt3DCore/private/qchangearbiter_p.h>
#include <Qt3DCore/private/qscheduler_p.h>
#include <Qt3DCore/private/qservicelocator_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p_p.h>
#include <Qt3DCore/private/qthreadpooler_p.h>
#include <Qt3DCore/private/qtickclock_p.h>
#include <Qt3DCore/private/qtickclockservice_p.h>
@@ -65,15 +66,29 @@
#include <Qt3DCore/private/qscene_p.h>
#include <QtCore/QCoreApplication>
-
-#if defined(QT3D_CORE_JOB_TIMING)
-#include <QElapsedTimer>
-#endif
+#include <QtCore/QAbstractAnimation>
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
+#if QT_CONFIG(animation)
+class RequestFrameAnimation final : public QAbstractAnimation
+{
+public:
+ RequestFrameAnimation(QObject *parent)
+ : QAbstractAnimation(parent)
+ {
+ }
+
+ ~RequestFrameAnimation() override;
+
+ int duration() const override { return 1; }
+ void updateCurrentTime(int currentTime) override { Q_UNUSED(currentTime) }
+};
+
+RequestFrameAnimation::~RequestFrameAnimation() = default;
+#else
namespace {
class RequestFrameEvent : public QEvent
@@ -92,21 +107,27 @@ private:
int RequestFrameEvent::requestEventType = QEvent::registerEventType();
} // anonymous
-
+#endif
/*!
\class Qt3DCore::QAspectManager
\internal
*/
-QAspectManager::QAspectManager(QObject *parent)
+QAspectManager::QAspectManager(QAspectEngine *parent)
: QObject(parent)
+ , m_engine(parent)
, m_root(nullptr)
, m_scheduler(new QScheduler(this))
, m_jobManager(new QAspectJobManager(this))
, m_changeArbiter(new QChangeArbiter(this))
- , m_serviceLocator(new QServiceLocator())
+ , m_serviceLocator(new QServiceLocator(parent))
, m_simulationLoopRunning(false)
, m_driveMode(QAspectEngine::Automatic)
+ , m_postConstructorInit(nullptr)
+#if QT_CONFIG(animation)
+ , m_simulationAnimation(nullptr)
+#endif
+ , m_jobsInLastFrame(0)
{
qRegisterMetaType<QSurface *>("QSurface*");
qCDebug(Aspects) << Q_FUNC_INFO;
@@ -148,8 +169,19 @@ void QAspectManager::enterSimulationLoop()
qCDebug(Aspects) << "Done calling onEngineStartup() for each aspect";
// Start running loop if Qt3D is in charge of driving it
- if (m_driveMode == QAspectEngine::Automatic)
+ if (m_driveMode == QAspectEngine::Automatic) {
+#if QT_CONFIG(animation)
+ if (!m_simulationAnimation) {
+ m_simulationAnimation = new RequestFrameAnimation(this);
+ connect(m_simulationAnimation, &QAbstractAnimation::finished, this, [this]() {
+ processFrame();
+ if (m_simulationLoopRunning && m_driveMode == QAspectEngine::Automatic)
+ requestNextFrame();
+ });
+ }
+#endif
requestNextFrame();
+ }
}
// Main thread (called by QAspectEngine)
@@ -163,6 +195,11 @@ void QAspectManager::exitSimulationLoop()
return;
}
+#if QT_CONFIG(animation)
+ if (m_simulationAnimation)
+ m_simulationAnimation->stop();
+#endif
+
QAbstractFrameAdvanceService *frameAdvanceService =
m_serviceLocator->service<QAbstractFrameAdvanceService>(QServiceLocator::FrameAdvanceService);
if (frameAdvanceService)
@@ -192,7 +229,6 @@ void QAspectManager::exitSimulationLoop()
}
qCDebug(Aspects) << "Done calling onEngineShutdown() for each aspect";
-
m_simulationLoopRunning = false;
qCDebug(Aspects) << "exitSimulationLoop completed";
}
@@ -398,6 +434,7 @@ QVector<QNode *> QAspectManager::lookupNodes(const QVector<QNodeId> &ids) const
return d->m_scene ? d->m_scene->lookupNodes(ids) : QVector<QNode *>{};
}
+#if !QT_CONFIG(animation)
/*!
\internal
\brief Drives the Qt3D simulation loop in the main thread
@@ -413,17 +450,24 @@ bool QAspectManager::event(QEvent *e)
// the loop
if (m_simulationLoopRunning && m_driveMode == QAspectEngine::Automatic)
requestNextFrame();
+
+ return true;
}
return QObject::event(e);
}
+#endif
void QAspectManager::requestNextFrame()
{
qCDebug(Aspects) << "Requesting new Frame";
// Post event in the event loop to force
// next frame to be processed
- qApp->postEvent(this, new RequestFrameEvent());
+#if QT_CONFIG(animation)
+ m_simulationAnimation->start();
+#else
+ QCoreApplication::postEvent(this, new RequestFrameEvent());
+#endif
}
void QAspectManager::processFrame()
@@ -435,6 +479,8 @@ void QAspectManager::processFrame()
m_serviceLocator->service<QAbstractFrameAdvanceService>(QServiceLocator::FrameAdvanceService);
const qint64 t = frameAdvanceService->waitForNextFrame();
+ if (t < 0)
+ return;
// Distribute accumulated changes. This includes changes sent from the frontend
// to the backend nodes. We call this before the call to m_scheduler->update() to ensure
@@ -444,71 +490,58 @@ void QAspectManager::processFrame()
//
// Doing this as the first call in the new frame ensures the lock free approach works
// without any such data race.
-#if QT_CONFIG(qt3d_profile_jobs)
- const quint32 arbiterId = 4096;
- JobRunStats changeArbiterStats;
- changeArbiterStats.jobId.typeAndInstance[0] = arbiterId;
- changeArbiterStats.jobId.typeAndInstance[1] = 0;
- changeArbiterStats.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
- changeArbiterStats.startTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
-#endif
-
- // Tell the NodePostConstructorInit to process any pending nodes which will add them to our list of
- // tree changes
- m_postConstructorInit->processNodes();
-
- // Add and Remove Nodes
- const QVector<NodeTreeChange> nodeTreeChanges = std::move(m_nodeTreeChanges);
- for (const NodeTreeChange &change : nodeTreeChanges) {
- // Buckets ensure that even if we have intermingled node added / removed
- // buckets, we preserve the order of the sequences
-
- for (QAbstractAspect *aspect : qAsConst(m_aspects)) {
- switch (change.type) {
- case NodeTreeChange::Added:
- aspect->d_func()->createBackendNode(change);
- break;
- case NodeTreeChange::Removed:
- aspect->d_func()->clearBackendNode(change);
- break;
+ {
+ // scope for QTaskLogger
+ 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
+ m_postConstructorInit->processNodes();
+
+ // Add and Remove Nodes
+ const QVector<NodeTreeChange> nodeTreeChanges = std::move(m_nodeTreeChanges);
+ for (const NodeTreeChange &change : nodeTreeChanges) {
+ // Buckets ensure that even if we have intermingled node added / removed
+ // buckets, we preserve the order of the sequences
+
+ for (QAbstractAspect *aspect : qAsConst(m_aspects)) {
+ switch (change.type) {
+ case NodeTreeChange::Added:
+ aspect->d_func()->createBackendNode(change);
+ break;
+ case NodeTreeChange::Removed:
+ aspect->d_func()->clearBackendNode(change);
+ break;
+ }
}
}
- }
-
- // Sync node / subnode relationship changes
- const auto dirtySubNodes = m_changeArbiter->takeDirtyFrontEndSubNodes();
- if (dirtySubNodes.size())
- for (QAbstractAspect *aspect : qAsConst(m_aspects))
- aspect->syncDirtyFrontEndSubNodes(dirtySubNodes);
- // Sync property updates
- const auto dirtyFrontEndNodes = m_changeArbiter->takeDirtyFrontEndNodes();
- if (dirtyFrontEndNodes.size())
- for (QAbstractAspect *aspect : qAsConst(m_aspects))
- 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
- // races. This could therefore be removed for Qt 6.
- m_changeArbiter->syncChanges();
-#if QT_CONFIG(qt3d_profile_jobs)
- changeArbiterStats.endTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
- QThreadPooler::addJobLogStatsEntry(changeArbiterStats);
-#endif
+ // Sync node / subnode relationship changes
+ const auto dirtySubNodes = m_changeArbiter->takeDirtyFrontEndSubNodes();
+ if (dirtySubNodes.size())
+ for (QAbstractAspect *aspect : qAsConst(m_aspects))
+ QAbstractAspectPrivate::get(aspect)->syncDirtyFrontEndSubNodes(dirtySubNodes);
+
+ // Sync property updates
+ const auto dirtyFrontEndNodes = m_changeArbiter->takeDirtyFrontEndNodes();
+ if (dirtyFrontEndNodes.size())
+ for (QAbstractAspect *aspect : qAsConst(m_aspects))
+ 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
+ // races. This could therefore be removed for Qt 6.
+ m_changeArbiter->syncChanges();
+ }
// 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_scheduler->scheduleAndWaitForFrameAspectJobs(t);
-#if defined(QT3D_CORE_JOB_TIMING)
- qDebug() << "Jobs took" << timer.nsecsElapsed() / 1.0e6;
-#endif
+ m_jobsInLastFrame = m_scheduler->scheduleAndWaitForFrameAspectJobs(t);
- // TODO sync backend changes to frontend
+ // 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/aspects/qaspectmanager_p.h b/src/core/aspects/qaspectmanager_p.h
index d9a6c41ec..2038e0822 100644
--- a/src/core/aspects/qaspectmanager_p.h
+++ b/src/core/aspects/qaspectmanager_p.h
@@ -73,15 +73,19 @@ class QScheduler;
class QChangeArbiter;
class QAbstractAspect;
class QAbstractAspectJobManager;
+class QAspectEngine;
class QServiceLocator;
class NodePostConstructorInit;
struct NodeTreeChange;
+#if QT_CONFIG(animation)
+class RequestFrameAnimation;
+#endif
class Q_3DCORE_PRIVATE_EXPORT QAspectManager : public QObject
{
Q_OBJECT
public:
- explicit QAspectManager(QObject *parent = nullptr);
+ explicit QAspectManager(QAspectEngine *parent = nullptr);
~QAspectManager();
void setRunMode(QAspectEngine::RunMode mode);
@@ -111,10 +115,15 @@ public:
QNode *lookupNode(QNodeId id) const;
QVector<QNode *> lookupNodes(const QVector<QNodeId> &ids) const;
+ int jobsInLastFrame() const { return m_jobsInLastFrame; }
+
private:
+#if !QT_CONFIG(animation)
bool event(QEvent *event) override;
+#endif
void requestNextFrame();
+ QAspectEngine *m_engine;
QVector<QAbstractAspect *> m_aspects;
QEntity *m_root;
QVariantMap m_data;
@@ -122,12 +131,15 @@ private:
QAbstractAspectJobManager *m_jobManager;
QChangeArbiter *m_changeArbiter;
QScopedPointer<QServiceLocator> m_serviceLocator;
- bool m_mainLoopRunning;
bool m_simulationLoopRunning;
QAspectEngine::RunMode m_driveMode;
QVector<NodeTreeChange> m_nodeTreeChanges;
NodePostConstructorInit* m_postConstructorInit;
+#if QT_CONFIG(animation)
+ RequestFrameAnimation *m_simulationAnimation;
+#endif
+ int m_jobsInLastFrame;
};
} // namespace Qt3DCore
diff --git a/src/core/changes/qcomponentaddedchange.h b/src/core/changes/qcomponentaddedchange.h
index ef2f6a227..9e1522024 100644
--- a/src/core/changes/qcomponentaddedchange.h
+++ b/src/core/changes/qcomponentaddedchange.h
@@ -53,10 +53,10 @@ class QComponentAddedChangePrivate;
class Q_3DCORESHARED_EXPORT QComponentAddedChange : public QSceneChange
{
public:
- explicit QComponentAddedChange(const QEntity *entity,
- const QComponent *component);
- explicit QComponentAddedChange(const QComponent *component,
- const QEntity *entity);
+ Q3D_DECL_DEPRECATED explicit QComponentAddedChange(const QEntity *entity,
+ const QComponent *component);
+ Q3D_DECL_DEPRECATED explicit QComponentAddedChange(const QComponent *component,
+ const QEntity *entity);
~QComponentAddedChange();
QNodeId entityId() const Q_DECL_NOTHROW;
@@ -67,7 +67,7 @@ private:
Q_DECLARE_PRIVATE(QComponentAddedChange)
};
-typedef QSharedPointer<QComponentAddedChange> QComponentAddedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QComponentAddedChange> QComponentAddedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qcomponentremovedchange.h b/src/core/changes/qcomponentremovedchange.h
index 8108b33d5..e0b039780 100644
--- a/src/core/changes/qcomponentremovedchange.h
+++ b/src/core/changes/qcomponentremovedchange.h
@@ -53,10 +53,10 @@ class QComponentRemovedChangePrivate;
class Q_3DCORESHARED_EXPORT QComponentRemovedChange : public QSceneChange
{
public:
- explicit QComponentRemovedChange(const QEntity *entity,
- const QComponent *component);
- explicit QComponentRemovedChange(const QComponent *component,
- const QEntity *entity);
+ Q3D_DECL_DEPRECATED explicit QComponentRemovedChange(const QEntity *entity,
+ const QComponent *component);
+ Q3D_DECL_DEPRECATED explicit QComponentRemovedChange(const QComponent *component,
+ const QEntity *entity);
~QComponentRemovedChange();
QNodeId entityId() const Q_DECL_NOTHROW;
@@ -67,7 +67,7 @@ private:
Q_DECLARE_PRIVATE(QComponentRemovedChange)
};
-typedef QSharedPointer<QComponentRemovedChange> QComponentRemovedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QComponentRemovedChange> QComponentRemovedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qdynamicpropertyupdatedchange.h b/src/core/changes/qdynamicpropertyupdatedchange.h
index 0509582b0..7009e1fe7 100644
--- a/src/core/changes/qdynamicpropertyupdatedchange.h
+++ b/src/core/changes/qdynamicpropertyupdatedchange.h
@@ -51,7 +51,7 @@ class QDynamicPropertyUpdatedChangePrivate;
class Q_3DCORESHARED_EXPORT QDynamicPropertyUpdatedChange : public QPropertyUpdatedChangeBase
{
public:
- explicit QDynamicPropertyUpdatedChange(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QDynamicPropertyUpdatedChange(QNodeId subjectId);
~QDynamicPropertyUpdatedChange();
QByteArray propertyName() const;
@@ -65,7 +65,7 @@ protected:
QDynamicPropertyUpdatedChange(QDynamicPropertyUpdatedChangePrivate &dd, QNodeId subjectId);
};
-typedef QSharedPointer<QDynamicPropertyUpdatedChange> QDynamicPropertyUpdatedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QDynamicPropertyUpdatedChange> QDynamicPropertyUpdatedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qnodecommand.h b/src/core/changes/qnodecommand.h
index 3622f7421..a31af1d6d 100644
--- a/src/core/changes/qnodecommand.h
+++ b/src/core/changes/qnodecommand.h
@@ -57,7 +57,7 @@ public:
typedef quint32 CommandId;
#endif
- explicit QNodeCommand(QNodeId id);
+ Q3D_DECL_DEPRECATED explicit QNodeCommand(QNodeId id);
~QNodeCommand();
CommandId commandId() const;
diff --git a/src/core/changes/qnodecreatedchange.h b/src/core/changes/qnodecreatedchange.h
index f46e8abee..31d00f3ac 100644
--- a/src/core/changes/qnodecreatedchange.h
+++ b/src/core/changes/qnodecreatedchange.h
@@ -51,7 +51,7 @@ class QNodeCreatedChangeBasePrivate;
class Q_3DCORESHARED_EXPORT QNodeCreatedChangeBase : public QSceneChange
{
public:
- explicit QNodeCreatedChangeBase(const QNode *node);
+ Q3D_DECL_DEPRECATED explicit QNodeCreatedChangeBase(const QNode *node);
~QNodeCreatedChangeBase();
QNodeId parentId() const Q_DECL_NOTHROW;
@@ -71,11 +71,14 @@ template<typename T>
class QNodeCreatedChange : public QNodeCreatedChangeBase
{
public:
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
explicit QNodeCreatedChange(const QNode *_node)
: QNodeCreatedChangeBase(_node)
, data()
{
}
+ QT_WARNING_POP
T data;
};
diff --git a/src/core/changes/qnodedestroyedchange.h b/src/core/changes/qnodedestroyedchange.h
index c072dd412..dce6da59e 100644
--- a/src/core/changes/qnodedestroyedchange.h
+++ b/src/core/changes/qnodedestroyedchange.h
@@ -50,7 +50,7 @@ class QNodeDestroyedChangePrivate;
class Q_3DCORESHARED_EXPORT QNodeDestroyedChange : public QSceneChange
{
public:
- explicit QNodeDestroyedChange(const QNode *node, const QVector<QNodeIdTypePair> &subtreeIdsAndTypes);
+ Q3D_DECL_DEPRECATED explicit QNodeDestroyedChange(const QNode *node, const QVector<QNodeIdTypePair> &subtreeIdsAndTypes);
~QNodeDestroyedChange();
QVector<QNodeIdTypePair> subtreeIdsAndTypes() const;
@@ -59,7 +59,7 @@ private:
Q_DECLARE_PRIVATE(QNodeDestroyedChange)
};
-typedef QSharedPointer<QNodeDestroyedChange> QNodeDestroyedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QNodeDestroyedChange> QNodeDestroyedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertynodeaddedchange.h b/src/core/changes/qpropertynodeaddedchange.h
index ce3288a65..062244f88 100644
--- a/src/core/changes/qpropertynodeaddedchange.h
+++ b/src/core/changes/qpropertynodeaddedchange.h
@@ -53,7 +53,7 @@ class QPropertyNodeAddedChangePrivate;
class Q_3DCORESHARED_EXPORT QPropertyNodeAddedChange : public QStaticPropertyValueAddedChangeBase
{
public:
- explicit QPropertyNodeAddedChange(QNodeId subjectId, QNode *node);
+ Q3D_DECL_DEPRECATED explicit QPropertyNodeAddedChange(QNodeId subjectId, QNode *node);
~QPropertyNodeAddedChange();
QNodeId addedNodeId() const;
@@ -63,7 +63,7 @@ private:
Q_DECLARE_PRIVATE(QPropertyNodeAddedChange)
};
-typedef QSharedPointer<QPropertyNodeAddedChange> QPropertyNodeAddedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyNodeAddedChange> QPropertyNodeAddedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertynoderemovedchange.h b/src/core/changes/qpropertynoderemovedchange.h
index 1a4db8f1c..a8ea9d6c4 100644
--- a/src/core/changes/qpropertynoderemovedchange.h
+++ b/src/core/changes/qpropertynoderemovedchange.h
@@ -53,7 +53,7 @@ class QPropertyNodeRemovedChangePrivate;
class Q_3DCORESHARED_EXPORT QPropertyNodeRemovedChange : public QStaticPropertyValueRemovedChangeBase
{
public:
- explicit QPropertyNodeRemovedChange(QNodeId subjectId, QNode *node);
+ Q3D_DECL_DEPRECATED explicit QPropertyNodeRemovedChange(QNodeId subjectId, QNode *node);
~QPropertyNodeRemovedChange();
QNodeId removedNodeId() const;
@@ -63,7 +63,7 @@ private:
Q_DECLARE_PRIVATE(QPropertyNodeRemovedChange)
};
-typedef QSharedPointer<QPropertyNodeRemovedChange> QPropertyNodeRemovedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyNodeRemovedChange> QPropertyNodeRemovedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertyupdatedchange.h b/src/core/changes/qpropertyupdatedchange.h
index e0c12f13d..aa0dd9364 100644
--- a/src/core/changes/qpropertyupdatedchange.h
+++ b/src/core/changes/qpropertyupdatedchange.h
@@ -51,7 +51,7 @@ class QPropertyUpdatedChangePrivate;
class Q_3DCORESHARED_EXPORT QPropertyUpdatedChange : public QStaticPropertyUpdatedChangeBase
{
public:
- explicit QPropertyUpdatedChange(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyUpdatedChange(QNodeId subjectId);
virtual ~QPropertyUpdatedChange();
QVariant value() const;
@@ -62,7 +62,7 @@ protected:
QPropertyUpdatedChange(QPropertyUpdatedChangePrivate &dd, QNodeId subjectId);
};
-typedef QSharedPointer<QPropertyUpdatedChange> QPropertyUpdatedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyUpdatedChange> QPropertyUpdatedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertyupdatedchangebase.h b/src/core/changes/qpropertyupdatedchangebase.h
index 800abb477..5a0f6c87f 100644
--- a/src/core/changes/qpropertyupdatedchangebase.h
+++ b/src/core/changes/qpropertyupdatedchangebase.h
@@ -56,12 +56,12 @@ public:
~QPropertyUpdatedChangeBase();
protected:
- explicit QPropertyUpdatedChangeBase(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyUpdatedChangeBase(QNodeId subjectId);
QPropertyUpdatedChangeBase(QPropertyUpdatedChangeBasePrivate &dd, QNodeId subjectId);
Q_DECLARE_PRIVATE(QPropertyUpdatedChangeBase)
};
-typedef QSharedPointer<QPropertyUpdatedChangeBase> QPropertyUpdatedChangeBasePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyUpdatedChangeBase> QPropertyUpdatedChangeBasePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertyvalueaddedchange.h b/src/core/changes/qpropertyvalueaddedchange.h
index d85720246..e70d78b7e 100644
--- a/src/core/changes/qpropertyvalueaddedchange.h
+++ b/src/core/changes/qpropertyvalueaddedchange.h
@@ -53,7 +53,7 @@ class QPropertyValueAddedChangePrivate;
class Q_3DCORESHARED_EXPORT QPropertyValueAddedChange : public QStaticPropertyValueAddedChangeBase
{
public:
- explicit QPropertyValueAddedChange(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyValueAddedChange(QNodeId subjectId);
~QPropertyValueAddedChange();
void setAddedValue(const QVariant &value);
@@ -63,7 +63,7 @@ private:
Q_DECLARE_PRIVATE(QPropertyValueAddedChange)
};
-typedef QSharedPointer<QPropertyValueAddedChange> QPropertyValueAddedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyValueAddedChange> QPropertyValueAddedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertyvalueaddedchangebase.h b/src/core/changes/qpropertyvalueaddedchangebase.h
index 2be39ad47..148411de8 100644
--- a/src/core/changes/qpropertyvalueaddedchangebase.h
+++ b/src/core/changes/qpropertyvalueaddedchangebase.h
@@ -56,12 +56,12 @@ public:
~QPropertyValueAddedChangeBase();
protected:
- explicit QPropertyValueAddedChangeBase(QNodeId subjectId);
- explicit QPropertyValueAddedChangeBase(QPropertyValueAddedChangeBasePrivate &dd, QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyValueAddedChangeBase(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyValueAddedChangeBase(QPropertyValueAddedChangeBasePrivate &dd, QNodeId subjectId);
Q_DECLARE_PRIVATE(QPropertyValueAddedChangeBase)
};
-typedef QSharedPointer<QPropertyValueAddedChangeBase> QPropertyValueAddedChangeBasePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyValueAddedChangeBase> QPropertyValueAddedChangeBasePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertyvalueremovedchange.h b/src/core/changes/qpropertyvalueremovedchange.h
index 2bd781ed5..70eb42db4 100644
--- a/src/core/changes/qpropertyvalueremovedchange.h
+++ b/src/core/changes/qpropertyvalueremovedchange.h
@@ -53,7 +53,7 @@ class QPropertyValueRemovedChangePrivate;
class Q_3DCORESHARED_EXPORT QPropertyValueRemovedChange : public QStaticPropertyValueRemovedChangeBase
{
public:
- explicit QPropertyValueRemovedChange(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyValueRemovedChange(QNodeId subjectId);
~QPropertyValueRemovedChange();
void setRemovedValue(const QVariant &value);
@@ -63,7 +63,7 @@ private:
Q_DECLARE_PRIVATE(QPropertyValueRemovedChange)
};
-typedef QSharedPointer<QPropertyValueRemovedChange> QPropertyValueRemovedChangePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyValueRemovedChange> QPropertyValueRemovedChangePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qpropertyvalueremovedchangebase.h b/src/core/changes/qpropertyvalueremovedchangebase.h
index 233354078..b5ead7d22 100644
--- a/src/core/changes/qpropertyvalueremovedchangebase.h
+++ b/src/core/changes/qpropertyvalueremovedchangebase.h
@@ -57,11 +57,11 @@ public:
protected:
Q_DECLARE_PRIVATE(QPropertyValueRemovedChangeBase)
- explicit QPropertyValueRemovedChangeBase(QNodeId subjectId);
- explicit QPropertyValueRemovedChangeBase(QPropertyValueRemovedChangeBasePrivate &dd, QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyValueRemovedChangeBase(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QPropertyValueRemovedChangeBase(QPropertyValueRemovedChangeBasePrivate &dd, QNodeId subjectId);
};
-typedef QSharedPointer<QPropertyValueRemovedChangeBase> QPropertyValueRemovedChangeBasePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QPropertyValueRemovedChangeBase> QPropertyValueRemovedChangeBasePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qscenechange.cpp b/src/core/changes/qscenechange.cpp
index 87bf06ea0..822451b5f 100644
--- a/src/core/changes/qscenechange.cpp
+++ b/src/core/changes/qscenechange.cpp
@@ -48,6 +48,7 @@ namespace Qt3DCore {
/*!
* \enum Qt3DCore::ChangeFlag
* \relates Qt3DCore::QSceneChange
+ * \obsolete
*
* The types of change that can be sent and received by Qt3D's change notification system.
*
diff --git a/src/core/changes/qscenechange.h b/src/core/changes/qscenechange.h
index e8c0ea748..3fc896aca 100644
--- a/src/core/changes/qscenechange.h
+++ b/src/core/changes/qscenechange.h
@@ -48,7 +48,7 @@ QT_BEGIN_NAMESPACE
namespace Qt3DCore {
-enum ChangeFlag {
+enum Q3D_DECL_DEPRECATED ChangeFlag {
NodeCreated = 1 << 0,
NodeDeleted = 1 << 1,
PropertyUpdated = 1 << 2,
@@ -60,18 +60,14 @@ enum ChangeFlag {
CallbackTriggered = 1 << 8,
AllChanges = 0xFFFFFFFF
};
+
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag)
Q_DECLARE_OPERATORS_FOR_FLAGS(ChangeFlags)
+QT_WARNING_POP
class QNode;
-//! internal
-struct NodeRelationshipChange {
- QNode *node;
- QNode *subNode;
- ChangeFlag change;
- const char *property;
-};
-
class QSceneChangePrivate;
class Q_3DCORESHARED_EXPORT QSceneChange
@@ -86,7 +82,10 @@ public:
virtual ~QSceneChange();
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
ChangeFlag type() const Q_DECL_NOTHROW;
+ QT_WARNING_POP
void setDeliveryFlags(DeliveryFlags flags) Q_DECL_NOTHROW;
DeliveryFlags deliveryFlags() const Q_DECL_NOTHROW;
@@ -95,9 +94,12 @@ public:
protected:
Q_DECLARE_PRIVATE(QSceneChange)
- explicit QSceneChange(ChangeFlag type, QNodeId subjectId);
- explicit QSceneChange(QSceneChangePrivate &dd,
- ChangeFlag type, QNodeId subjectId);
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
+ Q3D_DECL_DEPRECATED explicit QSceneChange(ChangeFlag type, QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QSceneChange(QSceneChangePrivate &dd,
+ ChangeFlag type, QNodeId subjectId);
+ QT_WARNING_POP
QSceneChangePrivate *d_ptr;
private:
diff --git a/src/core/changes/qscenechange_p.h b/src/core/changes/qscenechange_p.h
index d32f6eec3..4e112fe93 100644
--- a/src/core/changes/qscenechange_p.h
+++ b/src/core/changes/qscenechange_p.h
@@ -63,6 +63,16 @@ namespace Qt3DCore {
class QSceneChange;
class QNodeId;
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
+struct NodeRelationshipChange {
+ QNode *node;
+ QNode *subNode;
+ ChangeFlag change;
+ const char *property;
+};
+QT_WARNING_POP
+
class Q_3DCORE_PRIVATE_EXPORT QSceneChangePrivate
{
public :
@@ -75,7 +85,10 @@ public :
QNodeId m_subjectId;
QSceneChange::DeliveryFlags m_deliveryFlags;
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
ChangeFlag m_type;
+ QT_WARNING_POP
};
} // Qt3D
diff --git a/src/core/changes/qskeletoncreatedchange_p.h b/src/core/changes/qskeletoncreatedchange_p.h
index 09b37d545..9f0c361da 100644
--- a/src/core/changes/qskeletoncreatedchange_p.h
+++ b/src/core/changes/qskeletoncreatedchange_p.h
@@ -60,7 +60,7 @@ class QSkeletonCreatedChangeBasePrivate;
class Q_3DCORESHARED_EXPORT QSkeletonCreatedChangeBase : public QNodeCreatedChangeBase
{
public:
- explicit QSkeletonCreatedChangeBase(const QAbstractSkeleton *skeleton);
+ Q3D_DECL_DEPRECATED explicit QSkeletonCreatedChangeBase(const QAbstractSkeleton *skeleton);
~QSkeletonCreatedChangeBase();
enum SkeletonType {
@@ -74,17 +74,20 @@ private:
Q_DECLARE_PRIVATE(QSkeletonCreatedChangeBase)
};
-typedef QSharedPointer<QSkeletonCreatedChangeBase> QSkeletonCreatedChangeBasePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QSkeletonCreatedChangeBase> QSkeletonCreatedChangeBasePtr;
template<typename T>
class QSkeletonCreatedChange : public QSkeletonCreatedChangeBase
{
public:
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
explicit QSkeletonCreatedChange(const QAbstractSkeleton *_skeleton)
: QSkeletonCreatedChangeBase(_skeleton)
, data()
{
}
+ QT_WARNING_POP
T data;
};
diff --git a/src/core/changes/qstaticpropertyupdatedchangebase.h b/src/core/changes/qstaticpropertyupdatedchangebase.h
index b698d1f06..c59a87a20 100644
--- a/src/core/changes/qstaticpropertyupdatedchangebase.h
+++ b/src/core/changes/qstaticpropertyupdatedchangebase.h
@@ -57,12 +57,12 @@ public:
void setPropertyName(const char *name);
protected:
- explicit QStaticPropertyUpdatedChangeBase(QNodeId subjectId);
- explicit QStaticPropertyUpdatedChangeBase(QStaticPropertyUpdatedChangeBasePrivate &dd, QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QStaticPropertyUpdatedChangeBase(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QStaticPropertyUpdatedChangeBase(QStaticPropertyUpdatedChangeBasePrivate &dd, QNodeId subjectId);
Q_DECLARE_PRIVATE(QStaticPropertyUpdatedChangeBase)
};
-typedef QSharedPointer<QStaticPropertyUpdatedChangeBase> QStaticPropertyUpdatedChangeBasePtr;
+Q3D_DECL_DEPRECATED typedef QSharedPointer<QStaticPropertyUpdatedChangeBase> QStaticPropertyUpdatedChangeBasePtr;
} // namespace Qt3DCore
diff --git a/src/core/changes/qstaticpropertyvalueaddedchangebase.h b/src/core/changes/qstaticpropertyvalueaddedchangebase.h
index e56e8f18a..7e6807764 100644
--- a/src/core/changes/qstaticpropertyvalueaddedchangebase.h
+++ b/src/core/changes/qstaticpropertyvalueaddedchangebase.h
@@ -59,7 +59,7 @@ public:
protected:
Q_DECLARE_PRIVATE(QStaticPropertyValueAddedChangeBase)
- explicit QStaticPropertyValueAddedChangeBase(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QStaticPropertyValueAddedChangeBase(QNodeId subjectId);
QStaticPropertyValueAddedChangeBase(QStaticPropertyValueAddedChangeBasePrivate &dd,
QNodeId subjectId);
};
diff --git a/src/core/changes/qstaticpropertyvalueremovedchangebase.h b/src/core/changes/qstaticpropertyvalueremovedchangebase.h
index e9f53fb12..d1b96f83e 100644
--- a/src/core/changes/qstaticpropertyvalueremovedchangebase.h
+++ b/src/core/changes/qstaticpropertyvalueremovedchangebase.h
@@ -59,7 +59,7 @@ public:
protected:
Q_DECLARE_PRIVATE(QStaticPropertyValueRemovedChangeBase)
- explicit QStaticPropertyValueRemovedChangeBase(QNodeId subjectId);
+ Q3D_DECL_DEPRECATED explicit QStaticPropertyValueRemovedChangeBase(QNodeId subjectId);
QStaticPropertyValueRemovedChangeBase(QStaticPropertyValueRemovedChangeBasePrivate &dd,
QNodeId subjectId);
};
diff --git a/src/core/changes/qtypedpropertyupdatechange_p.h b/src/core/changes/qtypedpropertyupdatechange_p.h
index f196ee5eb..6793144ca 100644
--- a/src/core/changes/qtypedpropertyupdatechange_p.h
+++ b/src/core/changes/qtypedpropertyupdatechange_p.h
@@ -61,11 +61,14 @@ template<typename T>
class QTypedPropertyUpdatedChange : public QStaticPropertyUpdatedChangeBase
{
public:
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
explicit QTypedPropertyUpdatedChange(QNodeId _subjectId)
: QStaticPropertyUpdatedChangeBase(_subjectId)
, data()
{
}
+ QT_WARNING_POP
T data;
};
diff --git a/src/core/configure.json b/src/core/configure.json
index 2ba205530..2e13d9027 100644
--- a/src/core/configure.json
+++ b/src/core/configure.json
@@ -44,7 +44,7 @@
"output": [ "privateFeature" ]
},
"qt3d-profile-jobs": {
- "label": "Output Qt3D Job traces",
+ "label": "Output Qt3D Job traces (deprecated)",
"autoDetect": false,
"output": [ "privateFeature" ]
},
@@ -112,7 +112,6 @@
"entries": [
"assimp",
"system-assimp",
- "qt3d-profile-jobs",
"qt3d-profile-gl",
"qt3d-simd-sse2",
"qt3d-simd-avx2",
diff --git a/src/core/core.pro b/src/core/core.pro
index b1ba54be2..b76198e35 100644
--- a/src/core/core.pro
+++ b/src/core/core.pro
@@ -2,6 +2,7 @@ TARGET = Qt3DCore
MODULE = 3dcore
QT = core-private gui-private network
+DEFINES += BUILD_QT3D_MODULE
gcov {
QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage
diff --git a/src/core/jobs/qaspectjob_p.h b/src/core/jobs/qaspectjob_p.h
index b16c3cad2..ddad09c86 100644
--- a/src/core/jobs/qaspectjob_p.h
+++ b/src/core/jobs/qaspectjob_p.h
@@ -54,6 +54,7 @@
#include <QtCore/QWeakPointer>
#include <Qt3DCore/private/qt3dcore_global_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p_p.h>
#include <Qt3DCore/qt3dcore-config.h>
QT_BEGIN_NAMESPACE
@@ -63,47 +64,6 @@ namespace Qt3DCore {
class QAspectJob;
class QAspectManager;
-#if QT_CONFIG(qt3d_profile_jobs)
-struct FrameHeader
-{
- FrameHeader()
- : frameId(0)
- , jobCount(0)
- , frameType(WorkerJob)
- {
- }
-
- enum FrameType {
- WorkerJob = 0,
- Submission
- };
-
- quint32 frameId;
- quint16 jobCount;
- quint16 frameType; // Submission or worker job
-};
-
-union JobId
-{
- quint32 typeAndInstance[2];
- quint64 id;
-};
-
-struct JobRunStats
-{
- JobRunStats()
- {
- jobId.id = 0;
- }
-
- qint64 startTime;
- qint64 endTime;
- JobId jobId;
- // QAspectJob subclasses should properly populate the jobId
- quint64 threadId;
-};
-#endif
-
class Q_3DCORE_PRIVATE_EXPORT QAspectJobPrivate
{
public:
@@ -115,29 +75,16 @@ public:
virtual void postFrame(QAspectManager *aspectManager);
QVector<QWeakPointer<QAspectJob> > m_dependencies;
-#if QT_CONFIG(qt3d_profile_jobs)
- JobRunStats m_stats;
-#endif
+ JobId m_jobId;
};
-
} // Qt3D
-#if QT_CONFIG(qt3d_profile_jobs)
-
-#include <Qt3DCore/private/qaspectjob_p.h>
-
#define SET_JOB_RUN_STAT_TYPE(job, type, instance) \
- Qt3DCore::QAspectJobPrivate::get(job)->m_stats.jobId.typeAndInstance[0] = type; \
- Qt3DCore::QAspectJobPrivate::get(job)->m_stats.jobId.typeAndInstance[1] = instance;
-
-#else
-
-#define SET_JOB_RUN_STAT_TYPE(job, type, instance) \
- Q_UNUSED(job) \
- Q_UNUSED(type) \
- Q_UNUSED(instance)
-
-#endif
+ { \
+ auto &jobId = Qt3DCore::QAspectJobPrivate::get(job)->m_jobId; \
+ jobId.typeAndInstance[0] = type; \
+ jobId.typeAndInstance[1] = instance; \
+ }
QT_END_NAMESPACE
diff --git a/src/core/jobs/qaspectjobmanager.cpp b/src/core/jobs/qaspectjobmanager.cpp
index 91394924f..be7942359 100644
--- a/src/core/jobs/qaspectjobmanager.cpp
+++ b/src/core/jobs/qaspectjobmanager.cpp
@@ -44,7 +44,7 @@
#include <QtCore/QDebug>
#include <QtCore/QThread>
#include <QtCore/QFuture>
-
+#include <Qt3DCore/private/qaspectmanager_p.h>
#include <Qt3DCore/private/qthreadpooler_p.h>
#include <Qt3DCore/private/task_p.h>
@@ -52,9 +52,10 @@ QT_BEGIN_NAMESPACE
namespace Qt3DCore {
-QAspectJobManager::QAspectJobManager(QObject *parent)
+QAspectJobManager::QAspectJobManager(QAspectManager *parent)
: QAbstractAspectJobManager(parent)
, m_threadPooler(new QThreadPooler(this))
+ , m_aspectManager(parent)
{
}
@@ -69,12 +70,16 @@ void QAspectJobManager::initialize()
// Adds all Aspect Jobs to be processed for a frame
void QAspectJobManager::enqueueJobs(const QVector<QAspectJobPtr> &jobQueue)
{
+ auto systemService = m_aspectManager ? m_aspectManager->serviceLocator()->systemInformation() : nullptr;
+ if (systemService)
+ systemService->writePreviousFrameTraces();
+
// Convert QJobs to Tasks
QHash<QAspectJob *, AspectTaskRunnable *> tasksMap;
QVector<RunnableInterface *> taskList;
taskList.reserve(jobQueue.size());
for (const QAspectJobPtr &job : jobQueue) {
- AspectTaskRunnable *task = new AspectTaskRunnable();
+ AspectTaskRunnable *task = new AspectTaskRunnable(systemService);
task->m_job = job;
tasksMap.insert(job.data(), task);
@@ -99,9 +104,6 @@ void QAspectJobManager::enqueueJobs(const QVector<QAspectJobPtr> &jobQueue)
taskDepender->m_dependerCount += dependerCount;
}
-#if QT_CONFIG(qt3d_profile_jobs)
- QThreadPooler::writeFrameJobLogStats();
-#endif
m_threadPooler->mapDependables(taskList);
}
diff --git a/src/core/jobs/qaspectjobmanager_p.h b/src/core/jobs/qaspectjobmanager_p.h
index 77e535491..acbd0263e 100644
--- a/src/core/jobs/qaspectjobmanager_p.h
+++ b/src/core/jobs/qaspectjobmanager_p.h
@@ -63,12 +63,13 @@ namespace Qt3DCore {
class QThreadPooler;
class DependencyHandler;
+class QAspectManager;
class Q_3DCORE_PRIVATE_EXPORT QAspectJobManager : public QAbstractAspectJobManager
{
Q_OBJECT
public:
- explicit QAspectJobManager(QObject *parent = 0);
+ explicit QAspectJobManager(QAspectManager *parent = nullptr);
~QAspectJobManager();
void initialize() override;
@@ -81,6 +82,7 @@ public:
private:
QThreadPooler *m_threadPooler;
+ QAspectManager *m_aspectManager;
};
} // namespace Qt3DCore
diff --git a/src/core/jobs/qaspectjobproviderinterface_p.h b/src/core/jobs/qaspectjobproviderinterface_p.h
index 29b44b3c1..bb2c5ed88 100644
--- a/src/core/jobs/qaspectjobproviderinterface_p.h
+++ b/src/core/jobs/qaspectjobproviderinterface_p.h
@@ -69,6 +69,8 @@ public:
private:
virtual QVector<QAspectJobPtr> jobsToExecute(qint64 time) = 0;
+ virtual void jobsDone() = 0;
+ virtual void frameDone() = 0;
friend class QScheduler;
};
diff --git a/src/core/jobs/qthreadpooler.cpp b/src/core/jobs/qthreadpooler.cpp
index a9f4e7a31..f5c50062a 100644
--- a/src/core/jobs/qthreadpooler.cpp
+++ b/src/core/jobs/qthreadpooler.cpp
@@ -40,45 +40,27 @@
#include "qthreadpooler_p.h"
#include <QtCore/QDebug>
-#if QT_CONFIG(qt3d_profile_jobs)
-
-#ifdef Q_OS_ANDROID
-#include <QtCore/QStandardPaths>
-#endif
-
-#include <QtCore/QCoreApplication>
-#include <QtCore/QFile>
-#include <QtCore/QThreadStorage>
-#include <QtCore/QDateTime>
-#include <QtCore/QCoreApplication>
-#endif
-
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
-#if QT_CONFIG(qt3d_profile_jobs)
-QElapsedTimer QThreadPooler::m_jobsStatTimer;
-#endif
-
QThreadPooler::QThreadPooler(QObject *parent)
: QObject(parent)
, m_futureInterface(nullptr)
, m_mutex()
, m_taskCount(0)
+ , m_threadPool(QThreadPool::globalInstance())
{
const QByteArray maxThreadCount = qgetenv("QT3D_MAX_THREAD_COUNT");
if (!maxThreadCount.isEmpty()) {
bool conversionOK = false;
const int maxThreadCountValue = maxThreadCount.toInt(&conversionOK);
if (conversionOK)
- m_threadPool.setMaxThreadCount(maxThreadCountValue);
+ m_threadPool->setMaxThreadCount(maxThreadCountValue);
}
+
// Ensures that threads will never be recycled
- m_threadPool.setExpiryTimeout(-1);
-#if QT_CONFIG(qt3d_profile_jobs)
- QThreadPooler::m_jobsStatTimer.start();
-#endif
+ m_threadPool->setExpiryTimeout(-1);
}
QThreadPooler::~QThreadPooler()
@@ -105,7 +87,7 @@ void QThreadPooler::enqueueTasks(const QVector<RunnableInterface *> &tasks)
if (!hasDependencies(*it) && !(*it)->reserved()) {
(*it)->setReserved(true);
(*it)->setPooler(this);
- m_threadPool.start((*it));
+ m_threadPool->start((*it));
}
}
}
@@ -125,7 +107,7 @@ void QThreadPooler::taskFinished(RunnableInterface *task)
if (!aspectTask->reserved()) {
aspectTask->setReserved(true);
aspectTask->setPooler(this);
- m_threadPool.start(aspectTask);
+ m_threadPool->start(aspectTask);
}
}
}
@@ -188,105 +170,9 @@ int QThreadPooler::currentCount() const
int QThreadPooler::maxThreadCount() const
{
- return m_threadPool.maxThreadCount();
-}
-
-#if QT_CONFIG(qt3d_profile_jobs)
-
-QThreadStorage<QVector<JobRunStats> *> jobStatsCached;
-
-QVector<QVector<JobRunStats> *> localStorages;
-QVector<JobRunStats> *submissionStorage = nullptr;
-
-QMutex localStoragesMutex;
-
-// Called by the jobs
-void QThreadPooler::addJobLogStatsEntry(JobRunStats &stats)
-{
- if (!jobStatsCached.hasLocalData()) {
- auto jobVector = new QVector<JobRunStats>;
- jobStatsCached.setLocalData(jobVector);
- QMutexLocker lock(&localStoragesMutex);
- localStorages.push_back(jobVector);
- }
- jobStatsCached.localData()->push_back(stats);
-}
-
-// Called after jobs have been executed (MainThread QAspectJobManager::enqueueJobs)
-void QThreadPooler::writeFrameJobLogStats()
-{
- static QScopedPointer<QFile> traceFile;
- static quint32 frameId = 0;
- if (!traceFile) {
- const QString fileName = QStringLiteral("trace_") + QCoreApplication::applicationName() + QDateTime::currentDateTime().toString(QStringLiteral("_ddd_dd_MM_yy-hh_mm_ss_"))+ QSysInfo::productType() + QStringLiteral("_") + QSysInfo::buildAbi() + QStringLiteral(".qt3d");
-#ifdef Q_OS_ANDROID
- traceFile.reset(new QFile(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + QStringLiteral("/") + fileName));
-#else
- traceFile.reset(new QFile(fileName));
-#endif
- if (!traceFile->open(QFile::WriteOnly|QFile::Truncate))
- qCritical("Failed to open trace file");
- }
-
- // Write Aspect + Job threads
- {
- FrameHeader header;
- header.frameId = frameId;
- header.jobCount = 0;
-
- for (const QVector<JobRunStats> *storage : qAsConst(localStorages))
- header.jobCount += storage->size();
-
- traceFile->write(reinterpret_cast<char *>(&header), sizeof(FrameHeader));
-
- for (QVector<JobRunStats> *storage : qAsConst(localStorages)) {
- for (const JobRunStats &stat : *storage)
- traceFile->write(reinterpret_cast<const char *>(&stat), sizeof(JobRunStats));
- storage->clear();
- }
- }
-
- // Write submission thread
- {
- QMutexLocker lock(&localStoragesMutex);
- const int submissionJobSize = submissionStorage != nullptr ? submissionStorage->size() : 0;
- if (submissionJobSize > 0) {
- FrameHeader header;
- header.frameId = frameId;
- header.jobCount = submissionJobSize;
- header.frameType = FrameHeader::Submission;
-
- traceFile->write(reinterpret_cast<char *>(&header), sizeof(FrameHeader));
-
- for (const JobRunStats &stat : *submissionStorage)
- traceFile->write(reinterpret_cast<const char *>(&stat), sizeof(JobRunStats));
- submissionStorage->clear();
- }
- }
-
- traceFile->flush();
- ++frameId;
-}
-
-// Called from Submission thread (which can be main thread in Manual drive mode)
-void QThreadPooler::addSubmissionLogStatsEntry(JobRunStats &stats)
-{
- QMutexLocker lock(&localStoragesMutex);
- if (!jobStatsCached.hasLocalData()) {
- submissionStorage = new QVector<JobRunStats>;
- jobStatsCached.setLocalData(submissionStorage);
- }
-
- // Handle the case where submission thread is also the main thread (Scene/Manual drive modes with no RenderThread)
- if (submissionStorage == nullptr && jobStatsCached.hasLocalData())
- submissionStorage = new QVector<JobRunStats>;
-
- // When having no submission thread this can be null
- submissionStorage->push_back(stats);
+ return m_threadPool->maxThreadCount();
}
-#endif
-
} // namespace Qt3DCore
QT_END_NAMESPACE
diff --git a/src/core/jobs/qthreadpooler_p.h b/src/core/jobs/qthreadpooler_p.h
index 65459efba..1970641b8 100644
--- a/src/core/jobs/qthreadpooler_p.h
+++ b/src/core/jobs/qthreadpooler_p.h
@@ -60,10 +60,6 @@
#include <Qt3DCore/private/qaspectjob_p.h>
#include <Qt3DCore/private/task_p.h>
-#if QT_CONFIG(qt3d_profile_jobs)
-#include <QtCore/QElapsedTimer>
-#endif
-
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
@@ -81,17 +77,6 @@ public:
QFuture<void> future();
int maxThreadCount() const;
-#if QT_CONFIG(qt3d_profile_jobs)
- static QElapsedTimer m_jobsStatTimer;
-
- // Aspects + Job threads
- static void addJobLogStatsEntry(JobRunStats &stats);
- static void writeFrameJobLogStats();
-
- // Submission thread
- static void addSubmissionLogStatsEntry(JobRunStats &stats);
-
-#endif
private:
void enqueueTasks(const QVector<RunnableInterface *> &tasks);
@@ -103,7 +88,7 @@ private:
QFutureInterface<void> *m_futureInterface;
QMutex m_mutex;
QAtomicInt m_taskCount;
- QThreadPool m_threadPool;
+ QThreadPool *m_threadPool;
};
} // namespace Qt3DCore
diff --git a/src/core/jobs/task.cpp b/src/core/jobs/task.cpp
index 091aabfd6..1dd5712c9 100644
--- a/src/core/jobs/task.cpp
+++ b/src/core/jobs/task.cpp
@@ -44,6 +44,7 @@
#include <QtCore/QMutexLocker>
#include <Qt3DCore/private/qthreadpooler_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p_p.h>
QT_BEGIN_NAMESPACE
@@ -55,8 +56,10 @@ RunnableInterface::~RunnableInterface()
// Aspect task
-AspectTaskRunnable::AspectTaskRunnable()
- : m_pooler(nullptr)
+AspectTaskRunnable::AspectTaskRunnable(QSystemInformationService *service)
+ : m_service(service)
+ , m_pooler(nullptr)
+ , m_id(0)
, m_reserved(false)
{
}
@@ -68,21 +71,9 @@ AspectTaskRunnable::~AspectTaskRunnable()
void AspectTaskRunnable::run()
{
if (m_job) {
-#if QT_CONFIG(qt3d_profile_jobs)
QAspectJobPrivate *jobD = QAspectJobPrivate::get(m_job.data());
- if (m_pooler) {
- jobD->m_stats.startTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
- jobD->m_stats.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
- }
-#endif
+ QTaskLogger logger(m_pooler ? m_service : nullptr, jobD->m_jobId, QTaskLogger::AspectJob);
m_job->run();
-#if QT_CONFIG(qt3d_profile_jobs)
- if (m_pooler) {
- jobD->m_stats.endTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
- // Add current job's stats to log output
- QThreadPooler::addJobLogStatsEntry(jobD->m_stats);
- }
-#endif
}
// We could have an append sub task or something in here
diff --git a/src/core/jobs/task_p.h b/src/core/jobs/task_p.h
index c81882719..ff411539f 100644
--- a/src/core/jobs/task_p.h
+++ b/src/core/jobs/task_p.h
@@ -65,6 +65,7 @@ namespace Qt3DCore {
class JobRunner;
class DependencyHandler;
class QThreadPooler;
+class QSystemInformationService;
class RunnableInterface : public QRunnable
{
@@ -92,7 +93,7 @@ public:
class AspectTaskRunnable : public RunnableInterface
{
public:
- AspectTaskRunnable();
+ AspectTaskRunnable(QSystemInformationService *service);
~AspectTaskRunnable();
void run() override;
@@ -113,6 +114,7 @@ public:
int m_dependerCount = 0;
private:
+ QSystemInformationService *m_service;
QThreadPooler *m_pooler;
int m_id; // For testing purposes for now
bool m_reserved;
diff --git a/src/core/nodes/qbackendnode.cpp b/src/core/nodes/qbackendnode.cpp
index e5f93e96f..4138ea060 100644
--- a/src/core/nodes/qbackendnode.cpp
+++ b/src/core/nodes/qbackendnode.cpp
@@ -220,6 +220,7 @@ QBackendNode::QBackendNode(QBackendNodePrivate &dd)
/*!
* Notifies observers of scene change \a e.
+ * \obsolete
*/
void QBackendNode::notifyObservers(const QSceneChangePtr &e)
{
@@ -228,6 +229,8 @@ void QBackendNode::notifyObservers(const QSceneChangePtr &e)
}
/*!
+ \obsolete
+
Send the command named \a name with contents \a data,
and specify \a replyTo as the command id to which the
reply needs to be sent.
@@ -247,6 +250,7 @@ QNodeCommand::CommandId QBackendNode::sendCommand(const QString &name,
/*!
Send the reply to \a command.
+ \obsolete
*/
void QBackendNode::sendReply(const QNodeCommandPtr &command)
{
@@ -254,9 +258,12 @@ void QBackendNode::sendReply(const QNodeCommandPtr &command)
notifyObservers(command);
}
+/*!
+ * \obsolete
+ */
void QBackendNode::initializeFromPeer(const QNodeCreatedChangeBasePtr &change)
{
- Q_UNUSED(change);
+ Q_UNUSED(change)
qCDebug(Nodes) << Q_FUNC_INFO << change->metaObject()->className() << "does not override";
}
@@ -270,8 +277,7 @@ void QBackendNode::setEnabled(bool enabled) Q_DECL_NOTHROW
}
/*!
- * TODO
- * \a e
+ * \obsolete
*/
void QBackendNode::sceneChangeEvent(const QSceneChangePtr &e)
{
diff --git a/src/core/nodes/qbackendnode.h b/src/core/nodes/qbackendnode.h
index 550ced04f..691375999 100644
--- a/src/core/nodes/qbackendnode.h
+++ b/src/core/nodes/qbackendnode.h
@@ -90,18 +90,18 @@ public:
protected:
Q_DECLARE_PRIVATE(QBackendNode)
explicit QBackendNode(QBackendNodePrivate &dd);
- void notifyObservers(const QSceneChangePtr &e);
- QNodeCommand::CommandId sendCommand(const QString &name, const QVariant &data,
- QNodeCommand::CommandId replyTo = QNodeCommand::CommandId());
- void sendReply(const QNodeCommandPtr &command);
- virtual void sceneChangeEvent(const QSceneChangePtr &e);
+ Q3D_DECL_DEPRECATED void notifyObservers(const QSceneChangePtr &e);
+ Q3D_DECL_DEPRECATED QNodeCommand::CommandId sendCommand(const QString &name, const QVariant &data,
+ QNodeCommand::CommandId replyTo = QNodeCommand::CommandId());
+ Q3D_DECL_DEPRECATED void sendReply(const QNodeCommandPtr &command);
+ Q3D_DECL_DEPRECATED virtual void sceneChangeEvent(const QSceneChangePtr &e);
QBackendNodePrivate *d_ptr;
private:
Q_DISABLE_COPY(QBackendNode)
void setPeerId(QNodeId id) Q_DECL_NOEXCEPT;
- virtual void initializeFromPeer(const QNodeCreatedChangeBasePtr &change);
+ Q3D_DECL_DEPRECATED virtual void initializeFromPeer(const QNodeCreatedChangeBasePtr &change);
friend class QBackendNodePropertyChange;
friend class QAbstractAspectPrivate;
diff --git a/src/core/nodes/qentity.cpp b/src/core/nodes/qentity.cpp
index 024991387..1199dfc4b 100644
--- a/src/core/nodes/qentity.cpp
+++ b/src/core/nodes/qentity.cpp
@@ -53,6 +53,50 @@
QT_BEGIN_NAMESPACE
+namespace {
+
+QString dumpNode(const Qt3DCore::QEntity *n) {
+ auto formatNode = [](const Qt3DCore::QNode *n) {
+ QString res = QString(QLatin1String("%1{%2}"))
+ .arg(QLatin1String(n->metaObject()->className()))
+ .arg(n->id().id());
+ if (!n->objectName().isEmpty())
+ res += QString(QLatin1String(" (%1)")).arg(n->objectName());
+ if (!n->isEnabled())
+ res += QLatin1String(" [D]");
+ return res;
+ };
+
+ QString res = formatNode(n);
+ const auto &components = n->components();
+ if (components.size()) {
+ QStringList componentNames;
+ for (const auto &c : components)
+ componentNames += formatNode(c);
+ res += QString(QLatin1String(" [ %1 ]")).arg(componentNames.join(QLatin1String(", ")));
+ }
+
+ return res;
+}
+
+QStringList dumpSG(const Qt3DCore::QEntity *n, int level = 0)
+{
+ QStringList reply;
+ QString res = dumpNode(n);
+ reply += res.rightJustified(res.length() + level * 2, ' ');
+
+ const auto children = n->childNodes();
+ for (auto *child: children) {
+ auto *childFGNode = qobject_cast<Qt3DCore::QEntity *>(child);
+ if (childFGNode != nullptr)
+ reply += dumpSG(childFGNode, level + 1);
+ }
+
+ return reply;
+}
+
+}
+
namespace Qt3DCore {
/*!
@@ -75,7 +119,7 @@ namespace Qt3DCore {
*/
/*!
- \fn template<typename T> QVector<T *> QEntity::componentsOfType() const
+ \fn template<typename T> QVector<T *> Qt3DCore::QEntity::componentsOfType() const
Returns all the components added to this entity that can be cast to
type T or an empty vector if there are no such components.
@@ -244,6 +288,12 @@ QNodeId QEntityPrivate::parentEntityId() const
return m_parentEntityId;
}
+QString QEntityPrivate::dumpSceneGraph() const
+{
+ Q_Q(const QEntity);
+ return dumpSG(q).join('\n');
+}
+
QNodeCreatedChangeBasePtr QEntity::createNodeCreationChange() const
{
auto creationChange = QNodeCreatedChangePtr<QEntityData>::create(this);
diff --git a/src/core/nodes/qentity_p.h b/src/core/nodes/qentity_p.h
index 803754c87..992f81931 100644
--- a/src/core/nodes/qentity_p.h
+++ b/src/core/nodes/qentity_p.h
@@ -82,6 +82,7 @@ public :
return typedComponents;
}
+ QString dumpSceneGraph() const;
void removeDestroyedComponent(QComponent *comp);
QComponentVector m_components;
diff --git a/src/core/nodes/qnode.cpp b/src/core/nodes/qnode.cpp
index cfe83f4db..ad084242f 100644
--- a/src/core/nodes/qnode.cpp
+++ b/src/core/nodes/qnode.cpp
@@ -382,7 +382,7 @@ void QNodePrivate::unregisterNotifiedProperties()
void QNodePrivate::propertyChanged(int propertyIndex)
{
- Q_UNUSED(propertyIndex);
+ Q_UNUSED(propertyIndex)
// Bail out early if we can to avoid the cost below
if (m_blockNotifications)
@@ -539,6 +539,8 @@ void QNode::notifyObservers(const QSceneChangePtr &change)
}
/*!
+ \obsolete
+
Called when one or more backend aspects sends a notification \a change to the
current Qt3DCore::QNode instance.
@@ -547,7 +549,7 @@ void QNode::notifyObservers(const QSceneChangePtr &change)
*/
void QNode::sceneChangeEvent(const QSceneChangePtr &change)
{
- Q_UNUSED(change);
+ Q_UNUSED(change)
if (change->type() == Qt3DCore::PropertyUpdated) {
// TODO: Do this more efficiently. We could pass the metaobject and property
// index to the animation aspect via the QChannelMapping. This would
@@ -594,8 +596,8 @@ QScene *QNodePrivate::scene() const
*/
void QNodePrivate::notifyPropertyChange(const char *name, const QVariant &value)
{
- Q_UNUSED(name);
- Q_UNUSED(value);
+ Q_UNUSED(name)
+ Q_UNUSED(value)
// Bail out early if we can to avoid operator new
if (m_blockNotifications)
@@ -606,8 +608,8 @@ void QNodePrivate::notifyPropertyChange(const char *name, const QVariant &value)
void QNodePrivate::notifyDynamicPropertyChange(const QByteArray &name, const QVariant &value)
{
- Q_UNUSED(name);
- Q_UNUSED(value);
+ Q_UNUSED(name)
+ Q_UNUSED(value)
// Bail out early if we can to avoid operator new
if (m_blockNotifications)
@@ -683,6 +685,11 @@ void QNodePrivate::update()
void QNodePrivate::updateNode(QNode *node, const char *property, ChangeFlag change)
{
if (m_changeArbiter) {
+ // Ensure node has its postConstructorInit called if we reach this
+ // point, we could otherwise endup referencing a node that has yet
+ // to be created in the backend
+ QNodePrivate::get(node)->_q_ensureBackendNodeCreated();
+
Q_Q(QNode);
m_changeArbiter->addDirtyFrontEndNode(q, node, property, change);
}
@@ -787,10 +794,9 @@ QNode::~QNode()
{
Q_D(QNode);
// Disconnect each connection that was stored
- for (auto it = d->m_destructionConnections.begin(), end = d->m_destructionConnections.end(); it != end; ++it)
- QObject::disconnect(it.value());
+ for (const auto &nodeConnectionPair : qAsConst(d->m_destructionConnections))
+ QObject::disconnect(nodeConnectionPair.second);
d->m_destructionConnections.clear();
-
Q_EMIT nodeDestroyed();
// Notify the backend that the parent lost this node as a child and
@@ -993,6 +999,9 @@ void QNode::clearPropertyTrackings()
d->updatePropertyTrackMode();
}
+/*!
+ * \obsolete
+ */
QNodeCreatedChangeBasePtr QNode::createNodeCreationChange() const
{
// Uncomment this when implementing new frontend and backend types.
@@ -1045,6 +1054,7 @@ QNodeCreatedChangeBasePtr QNode::createNodeCreationChange() const
*/
/*!
* \brief Sends a command message to the backend node
+ * \obsolete
*
* Creates a QNodeCommand message and dispatches it to the backend node. The
* command is given and a \a name and some \a data which can be used in the
@@ -1075,6 +1085,7 @@ QNodeCommand::CommandId QNode::sendCommand(const QString &name,
/*!
* \brief Send a \a command back to the backend node.
+ * \obsolete
*
* Assumes the command is to be to sent back in reply to itself to the backend node.
*
diff --git a/src/core/nodes/qnode.h b/src/core/nodes/qnode.h
index 9ca817fb6..efdec8da5 100644
--- a/src/core/nodes/qnode.h
+++ b/src/core/nodes/qnode.h
@@ -99,9 +99,9 @@ public:
void clearPropertyTracking(const QString &propertyName);
void clearPropertyTrackings();
- QNodeCommand::CommandId sendCommand(const QString &name, const QVariant &data = QVariant(),
- QNodeCommand::CommandId replyTo = QNodeCommand::CommandId());
- void sendReply(const QNodeCommandPtr &command);
+ Q3D_DECL_DEPRECATED QNodeCommand::CommandId sendCommand(const QString &name, const QVariant &data = QVariant(),
+ QNodeCommand::CommandId replyTo = QNodeCommand::CommandId());
+ Q3D_DECL_DEPRECATED void sendReply(const QNodeCommandPtr &command);
public Q_SLOTS:
void setParent(QNode *parent);
@@ -116,12 +116,12 @@ Q_SIGNALS:
protected:
explicit QNode(QNodePrivate &dd, QNode *parent = nullptr);
- void notifyObservers(const QSceneChangePtr &change);
- virtual void sceneChangeEvent(const QSceneChangePtr &change);
+ Q3D_DECL_DEPRECATED void notifyObservers(const QSceneChangePtr &change);
+ Q3D_DECL_DEPRECATED virtual void sceneChangeEvent(const QSceneChangePtr &change);
private:
Q_DECLARE_PRIVATE(QNode)
- virtual QNodeCreatedChangeBasePtr createNodeCreationChange() const;
+ Q3D_DECL_DEPRECATED virtual QNodeCreatedChangeBasePtr createNodeCreationChange() const;
// We only want setParent(QNode *) to be callable
// when dealing with QNode objects
diff --git a/src/core/nodes/qnode_p.h b/src/core/nodes/qnode_p.h
index a7a300a5e..5aa4c5328 100644
--- a/src/core/nodes/qnode_p.h
+++ b/src/core/nodes/qnode_p.h
@@ -90,7 +90,10 @@ public:
void updatePropertyTrackMode();
void update();
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
void updateNode(QNode *node, const char* property, ChangeFlag change);
+ QT_WARNING_POP
Q_DECLARE_PUBLIC(QNode)
@@ -124,7 +127,7 @@ public:
// If the node is destoyed, we make sure not to keep a dangling pointer to it
Q_Q(QNode);
auto f = [q, func]() { (static_cast<Caller *>(q)->*func)(nullptr); };
- m_destructionConnections.insert(node, QObject::connect(node, &QNode::nodeDestroyed, f));
+ m_destructionConnections.push_back({node, QObject::connect(node, &QNode::nodeDestroyed, f)});
}
template<typename Caller, typename NodeType>
@@ -133,7 +136,7 @@ public:
// If the node is destoyed, we make sure not to keep a dangling pointer to it
Q_Q(QNode);
auto f = [q, func, node]() { (static_cast<Caller *>(q)->*func)(node); };
- m_destructionConnections.insert(node, QObject::connect(node, &QNode::nodeDestroyed, f));
+ m_destructionConnections.push_back({node, QObject::connect(node, &QNode::nodeDestroyed, f)});
}
template<typename Caller, typename ValueType>
@@ -146,7 +149,7 @@ public:
// If the node is destoyed, we make sure not to keep a dangling pointer to it
Q_Q(QNode);
auto f = [q, func, resetValue]() { (static_cast<Caller *>(q)->*func)(resetValue); };
- m_destructionConnections.insert(node, QObject::connect(node, &QNode::nodeDestroyed, f));
+ m_destructionConnections.push_back({node, QObject::connect(node, &QNode::nodeDestroyed, f)});
}
template<typename Caller, typename NodeType>
@@ -154,12 +157,21 @@ public:
{
// If the node is destoyed, we make sure not to keep a dangling pointer to it
auto f = [this, func, node]() { (static_cast<Caller *>(this)->*func)(node); };
- m_destructionConnections.insert(node, QObject::connect(node, &QNode::nodeDestroyed, f));
+ m_destructionConnections.push_back({node, QObject::connect(node, &QNode::nodeDestroyed, f)});
}
void unregisterDestructionHelper(QNode *node)
{
- QObject::disconnect(m_destructionConnections.take(node));
+ m_destructionConnections.erase(std::remove_if(m_destructionConnections.begin(),
+ m_destructionConnections.end(),
+ [node] (const QPair<QNode *, QMetaObject::Connection> &nodeConnectionPair) {
+ if (nodeConnectionPair.first == node) {
+ QObject::disconnect(nodeConnectionPair.second);
+ return true;
+ }
+ return false;
+ }),
+ m_destructionConnections.end());
}
static const QMetaObject *findStaticMetaObject(const QMetaObject *metaObject);
@@ -184,7 +196,7 @@ private:
friend class PropertyChangeHandler<QNodePrivate>;
bool m_propertyChangesSetup;
PropertyChangeHandler<QNodePrivate> m_signals;
- QHash<QNode *, QMetaObject::Connection> m_destructionConnections;
+ QVector<QPair<QNode *, QMetaObject::Connection>> m_destructionConnections;
};
class NodePostConstructorInit : public QObject
diff --git a/src/core/nodes/qnodecreatedchangegenerator_p.h b/src/core/nodes/qnodecreatedchangegenerator_p.h
index b2e8fa08b..35e5b673e 100644
--- a/src/core/nodes/qnodecreatedchangegenerator_p.h
+++ b/src/core/nodes/qnodecreatedchangegenerator_p.h
@@ -69,6 +69,8 @@ public:
private:
void createCreationChange(QNode *node)
{
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
const auto creationChange = node->createNodeCreationChange();
m_creationChanges.push_back(creationChange);
@@ -82,6 +84,7 @@ private:
// Mark this node as having been handled for creation so that it is picked up
d->m_hasBackendNode = true;
+ QT_WARNING_POP
}
QVector<QNodeCreatedChangeBasePtr> m_creationChanges;
diff --git a/src/core/qchangearbiter_p.h b/src/core/qchangearbiter_p.h
index f31480685..483b46575 100644
--- a/src/core/qchangearbiter_p.h
+++ b/src/core/qchangearbiter_p.h
@@ -64,6 +64,7 @@
#include <Qt3DCore/private/qlockableobserverinterface_p.h>
#include <Qt3DCore/private/qt3dcore_global_p.h>
+#include <Qt3DCore/private/qscenechange_p.h>
QT_BEGIN_NAMESPACE
@@ -83,7 +84,10 @@ public:
virtual QAbstractPostman *postman() const = 0;
virtual void addDirtyFrontEndNode(QNode *node) = 0;
virtual void removeDirtyFrontEndNode(QNode *node) = 0;
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
virtual void addDirtyFrontEndNode(QNode *node, QNode *subNode, const char *property, ChangeFlag change) = 0;
+ QT_WARNING_POP
};
class Q_3DCORE_PRIVATE_EXPORT QChangeArbiter final
@@ -99,9 +103,12 @@ public:
void syncChanges();
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
void registerObserver(QObserverInterface *observer,
QNodeId nodeId,
ChangeFlags changeFlags = AllChanges);
+ QT_WARNING_POP
void unregisterObserver(QObserverInterface *observer,
QNodeId nodeId);
@@ -110,7 +117,10 @@ public:
void sceneChangeEventWithLock(const QSceneChangeList &e) override; // QLockableObserverInterface impl
void addDirtyFrontEndNode(QNode *node) override;
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
void addDirtyFrontEndNode(QNode *node, QNode *subNode, const char *property, ChangeFlag change) override;
+ QT_WARNING_POP
void removeDirtyFrontEndNode(QNode *node) override;
QVector<QNode *> takeDirtyFrontEndNodes();
QVector<NodeRelationshipChange> takeDirtyFrontEndSubNodes();
diff --git a/src/core/qpostman_p.h b/src/core/qpostman_p.h
index 23c638239..3e5f91742 100644
--- a/src/core/qpostman_p.h
+++ b/src/core/qpostman_p.h
@@ -75,7 +75,7 @@ class Q_AUTOTEST_EXPORT QPostman final
{
Q_OBJECT
public:
- explicit QPostman(QObject *parent = 0);
+ explicit QPostman(QObject *parent = nullptr);
~QPostman();
void setScene(QScene *sceneLookup) final;
diff --git a/src/core/qscheduler.cpp b/src/core/qscheduler.cpp
index edfbb391c..17ca1fbfd 100644
--- a/src/core/qscheduler.cpp
+++ b/src/core/qscheduler.cpp
@@ -43,6 +43,7 @@
#include <Qt3DCore/private/qabstractaspect_p.h>
#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DCore/private/qaspectjob_p.h>
#include <Qt3DCore/private/qabstractaspectjobmanager_p.h>
QT_BEGIN_NAMESPACE
@@ -69,7 +70,7 @@ QAspectManager *QScheduler::aspectManager() const
return m_aspectManager;
}
-void QScheduler::scheduleAndWaitForFrameAspectJobs(qint64 time)
+int QScheduler::scheduleAndWaitForFrameAspectJobs(qint64 time)
{
QVector<QAspectJobPtr> jobQueue;
@@ -92,8 +93,17 @@ void QScheduler::scheduleAndWaitForFrameAspectJobs(qint64 time)
m_aspectManager->jobManager()->waitForAllJobs();
- for (auto &job : qAsConst(jobQueue))
- job->postFrame(m_aspectManager);
+ {
+ 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();
+ }
+
+ return jobQueue.size();
}
} // namespace Qt3DCore
diff --git a/src/core/qscheduler_p.h b/src/core/qscheduler_p.h
index 9b1685e54..92e8e04fb 100644
--- a/src/core/qscheduler_p.h
+++ b/src/core/qscheduler_p.h
@@ -60,17 +60,17 @@ namespace Qt3DCore {
class QAspectManager;
-class QScheduler : public QObject
+class Q_AUTOTEST_EXPORT QScheduler : public QObject
{
Q_OBJECT
public:
- explicit QScheduler(QObject *parent = 0);
+ explicit QScheduler(QObject *parent = nullptr);
~QScheduler();
void setAspectManager(QAspectManager *aspectManager);
QAspectManager *aspectManager() const;
- virtual void scheduleAndWaitForFrameAspectJobs(qint64 time);
+ virtual int scheduleAndWaitForFrameAspectJobs(qint64 time);
private:
QAspectManager *m_aspectManager;
diff --git a/src/core/qt3dcore_global.h b/src/core/qt3dcore_global.h
index b2ad787c0..e932b02ba 100644
--- a/src/core/qt3dcore_global.h
+++ b/src/core/qt3dcore_global.h
@@ -55,6 +55,12 @@ QT_BEGIN_NAMESPACE
# define Q_3DCORESHARED_EXPORT
#endif
+#ifdef BUILD_QT3D_MODULE
+#define Q3D_DECL_DEPRECATED
+#else
+#define Q3D_DECL_DEPRECATED Q_DECL_DEPRECATED
+#endif
+
#define QT3D_DECLARE_TYPEINFO(NS, Class, Flags) \
} /* NS */ \
Q_DECLARE_TYPEINFO(NS :: Class, Flags); \
diff --git a/src/core/resources/qloadgltf_p.h b/src/core/resources/qloadgltf_p.h
new file mode 100644
index 000000000..ce49a2a80
--- /dev/null
+++ b/src/core/resources/qloadgltf_p.h
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2019 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 QT3DCORE_QLOADGLTF_P_H
+#define QT3DCORE_QLOADGLTF_P_H
+
+#include <QtCore/qcborarray.h>
+#include <QtCore/qcbormap.h>
+#include <QtCore/qcborvalue.h>
+#include <QtCore/qjsonarray.h>
+#include <QtCore/qjsondocument.h>
+#include <QtCore/qjsonobject.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.
+//
+
+inline QJsonDocument qLoadGLTF(const QByteArray &gltfData)
+{
+ {
+ const QCborValue cbor = QCborValue::fromCbor(gltfData);
+ if (cbor.isMap())
+ return QJsonDocument(cbor.toMap().toJsonObject());
+ if (cbor.isArray())
+ return QJsonDocument(cbor.toArray().toJsonArray());
+ }
+ return QJsonDocument::fromJson(gltfData);
+}
+
+#endif // QT3DCORE_QLOADGLTF_P_H
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 <typename T>
struct QResourceInfo
{
- enum
- {
- needsCleanup = false
- };
-};
-
-template <>
-struct QResourceInfo<void>
-{
- enum
- {
- needsCleanup = false
- };
+ static const bool needsCleanup = false;
};
enum
@@ -204,22 +192,10 @@ enum
template<> \
struct QResourceInfo<TYPE > \
{ \
- enum \
-{ \
- needsCleanup = ((FLAGS & Q_REQUIRES_CLEANUP) == 0) \
-}; \
+ static const bool needsCleanup = (FLAGS & Q_REQUIRES_CLEANUP) == 0;\
}; \
} // namespace Qt3DCore
-template <int v>
-struct Int2Type
-{
- enum
- {
- value = v
- };
-};
-
template<typename T>
class QHandleData : public QHandle<T>::Data
{
@@ -275,7 +251,7 @@ public:
typename Handle::Data *d = handle.data_ptr();
d->nextFree = freeList;
freeList = d;
- performCleanup(&static_cast<QHandleData<T> *>(d)->data, Int2Type<QResourceInfo<T>::needsCleanup>());
+ performCleanup(&static_cast<QHandleData<T> *>(d)->data, std::integral_constant<bool, QResourceInfo<T>::needsCleanup>{});
}
T *data(Handle h)
@@ -349,13 +325,16 @@ private:
}
}
- void performCleanup(T *r, Int2Type<true>)
+ template<typename Q = T>
+ void performCleanup(Q *r, std::integral_constant<bool, true>)
{
r->cleanup();
}
- void performCleanup(T *, Int2Type<false>)
- {}
+ template<typename Q = T>
+ void performCleanup(Q *, std::integral_constant<bool, false>)
+ {
+ }
};
diff --git a/src/core/resources/resources.pri b/src/core/resources/resources.pri
index e9563f935..d25070d56 100644
--- a/src/core/resources/resources.pri
+++ b/src/core/resources/resources.pri
@@ -1,4 +1,5 @@
HEADERS += \
+ $$PWD/qloadgltf_p.h \
$$PWD/qresourcemanager_p.h \
$$PWD/qhandle_p.h
diff --git a/src/core/services/nullservices_p.h b/src/core/services/nullservices_p.h
index 30dc2d543..6b2d1b029 100644
--- a/src/core/services/nullservices_p.h
+++ b/src/core/services/nullservices_p.h
@@ -54,25 +54,11 @@
#include <Qt3DCore/qt3dcore_global.h>
#include <Qt3DCore/private/qopenglinformationservice_p.h>
-#include <Qt3DCore/private/qsysteminformationservice_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
-class NullSystemInformationService : public QSystemInformationService
-{
-public:
- NullSystemInformationService()
- : QSystemInformationService(QStringLiteral("Null System Information Service"))
- {}
- ~NullSystemInformationService() {}
-
- QStringList aspectNames() const final { return QStringList(); }
- int threadPoolThreadCount() const final { return 0; }
-};
-
-
class NullOpenGLInformationService : public QOpenGLInformationService
{
public:
diff --git a/src/core/services/qdownloadnetworkworker.cpp b/src/core/services/qdownloadnetworkworker.cpp
index e1f806e92..2d89cb7a1 100644
--- a/src/core/services/qdownloadnetworkworker.cpp
+++ b/src/core/services/qdownloadnetworkworker.cpp
@@ -109,7 +109,7 @@ void QDownloadNetworkWorker::onRequestFinished(QNetworkReply *reply)
return;
auto request = (*it).first;
- if (reply->error() == QNetworkReply::NoError) {
+ if (reply->networkError() == QNetworkReply::NoError) {
request->m_succeeded = true;
}
request->onDownloaded();
diff --git a/src/core/services/qservicelocator.cpp b/src/core/services/qservicelocator.cpp
index bdcb4a521..73a40c2e4 100644
--- a/src/core/services/qservicelocator.cpp
+++ b/src/core/services/qservicelocator.cpp
@@ -46,6 +46,7 @@
#include <Qt3DCore/private/qdownloadhelperservice_p.h>
#include <Qt3DCore/private/qeventfilterservice_p.h>
#include <Qt3DCore/private/qtickclockservice_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p.h>
QT_BEGIN_NAMESPACE
@@ -85,16 +86,19 @@ QString QAbstractServiceProvider::description() const
}
+class QAspectEngine;
+
class QServiceLocatorPrivate
{
public:
- QServiceLocatorPrivate()
- : m_nonNullDefaultServices(0)
+ QServiceLocatorPrivate(QAspectEngine *aspectEngine)
+ : m_systemInfo(aspectEngine)
+ , m_nonNullDefaultServices(0)
{}
QHash<int, QAbstractServiceProvider *> m_services;
- NullSystemInformationService m_nullSystemInfo;
+ QSystemInformationService m_systemInfo;
NullOpenGLInformationService m_nullOpenGLInfo;
QTickClockService m_defaultFrameAdvanceService;
QEventFilterService m_eventFilterService;
@@ -128,8 +132,8 @@ public:
/*
Creates an instance of QServiceLocator.
*/
-QServiceLocator::QServiceLocator()
- : d_ptr(new QServiceLocatorPrivate)
+QServiceLocator::QServiceLocator(QAspectEngine *aspectEngine)
+ : d_ptr(new QServiceLocatorPrivate(aspectEngine))
{
}
@@ -196,7 +200,7 @@ int QServiceLocator::serviceCount() const
QSystemInformationService *QServiceLocator::systemInformation()
{
Q_D(QServiceLocator);
- return static_cast<QSystemInformationService *>(d->m_services.value(SystemInformation, &d->m_nullSystemInfo));
+ return static_cast<QSystemInformationService *>(d->m_services.value(SystemInformation, &d->m_systemInfo));
}
/*
diff --git a/src/core/services/qservicelocator_p.h b/src/core/services/qservicelocator_p.h
index 9111a14ab..5bf71a996 100644
--- a/src/core/services/qservicelocator_p.h
+++ b/src/core/services/qservicelocator_p.h
@@ -85,11 +85,12 @@ class QSystemInformationService;
class QServiceLocatorPrivate;
class QEventFilterService;
class QDownloadHelperService;
+class QAspectEngine;
class Q_3DCORESHARED_EXPORT QServiceLocator
{
public:
- QServiceLocator();
+ QServiceLocator(QAspectEngine *aspectEngine = nullptr);
~QServiceLocator();
enum ServiceType {
diff --git a/src/core/services/qsysteminformationservice.cpp b/src/core/services/qsysteminformationservice.cpp
index f11e0c3d1..87cc08e59 100644
--- a/src/core/services/qsysteminformationservice.cpp
+++ b/src/core/services/qsysteminformationservice.cpp
@@ -40,10 +40,236 @@
#include "qsysteminformationservice_p.h"
#include "qsysteminformationservice_p_p.h"
+#ifdef Q_OS_ANDROID
+#include <QtCore/QStandardPaths>
+#endif
+
+#include <QtCore/QThreadPool>
+#include <QtCore/QCoreApplication>
+#include <QtCore/QFile>
+#include <QtCore/QDateTime>
+#include <QtCore/QUrl>
+#include <QtCore/QDir>
+#include <QtGui/QDesktopServices>
+
+#include <Qt3DCore/QAspectEngine>
+#include <Qt3DCore/QAbstractAspect>
+#include <Qt3DCore/private/qabstractaspect_p.h>
+#include <Qt3DCore/private/qaspectengine_p.h>
+#include <Qt3DCore/private/aspectcommanddebugger_p.h>
+
QT_BEGIN_NAMESPACE
+namespace {
+
+struct FrameHeader
+{
+ FrameHeader()
+ : frameId(0)
+ , jobCount(0)
+ , frameType(WorkerJob)
+ {
+ }
+
+ enum FrameType {
+ WorkerJob = 0,
+ Submission
+ };
+
+ quint32 frameId;
+ quint16 jobCount;
+ quint16 frameType; // Submission or worker job
+};
+
+}
namespace Qt3DCore {
+QSystemInformationServicePrivate::QSystemInformationServicePrivate(QAspectEngine *aspectEngine,
+ const QString &description)
+ : QAbstractServiceProviderPrivate(QServiceLocator::SystemInformation, description)
+ , m_aspectEngine(aspectEngine)
+ , m_submissionStorage(nullptr)
+ , m_frameId(0)
+ , m_commandDebugger(nullptr)
+{
+ m_traceEnabled = qEnvironmentVariableIsSet("QT3D_TRACE_ENABLED");
+ m_graphicsTraceEnabled = qEnvironmentVariableIsSet("QT3D_GRAPHICS_TRACE_ENABLED");
+ if (m_traceEnabled || m_graphicsTraceEnabled)
+ m_jobsStatTimer.start();
+
+ const bool commandServerEnabled = qEnvironmentVariableIsSet("QT3D_COMMAND_SERVER_ENABLED");
+ if (commandServerEnabled) {
+ m_commandDebugger = new Debug::AspectCommandDebugger(q_func());
+ m_commandDebugger->initialize();
+ }
+}
+
+QSystemInformationServicePrivate::~QSystemInformationServicePrivate() = default;
+
+QSystemInformationServicePrivate *QSystemInformationServicePrivate::get(QSystemInformationService *q)
+{
+ return q->d_func();
+}
+
+// Called by the jobs
+void QSystemInformationServicePrivate::addJobLogStatsEntry(QSystemInformationServicePrivate::JobRunStats &stats)
+{
+ if (!m_traceEnabled && !m_graphicsTraceEnabled)
+ return;
+
+ if (!m_jobStatsCached.hasLocalData()) {
+ auto jobVector = new QVector<JobRunStats>;
+ m_jobStatsCached.setLocalData(jobVector);
+ QMutexLocker lock(&m_localStoragesMutex);
+ m_localStorages.push_back(jobVector);
+ }
+ m_jobStatsCached.localData()->push_back(stats);
+}
+
+// Called from Submission thread (which can be main thread in Manual drive mode)
+void QSystemInformationServicePrivate::addSubmissionLogStatsEntry(QSystemInformationServicePrivate::JobRunStats &stats)
+{
+ if (!m_traceEnabled && !m_graphicsTraceEnabled)
+ return;
+
+ QMutexLocker lock(&m_localStoragesMutex);
+ if (!m_jobStatsCached.hasLocalData()) {
+ m_submissionStorage = new QVector<JobRunStats>;
+ m_jobStatsCached.setLocalData(m_submissionStorage);
+ }
+
+ // Handle the case where submission thread is also the main thread (Scene/Manual drive modes with no RenderThread)
+ if (m_submissionStorage == nullptr && m_jobStatsCached.hasLocalData())
+ m_submissionStorage = new QVector<JobRunStats>;
+
+ // When having no submission thread this can be null
+ m_submissionStorage->push_back(stats);
+}
+
+// Called after jobs have been executed (MainThread QAspectJobManager::enqueueJobs)
+void QSystemInformationServicePrivate::writeFrameJobLogStats()
+{
+ if (!m_traceEnabled && !m_graphicsTraceEnabled)
+ return;
+
+ using JobRunStats = QSystemInformationServicePrivate::JobRunStats;
+
+ if (!m_traceFile) {
+ const QString fileName = QStringLiteral("trace_") + QCoreApplication::applicationName() +
+ QDateTime::currentDateTime().toString(QStringLiteral("_yyMMdd-hhmmss_")) +
+ QSysInfo::productType() + QStringLiteral("_") + QSysInfo::buildAbi() + QStringLiteral(".qt3d");
+#ifdef Q_OS_ANDROID
+ m_traceFile.reset(new QFile(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + QStringLiteral("/") + fileName));
+#else
+ // TODO fix for iOS
+ m_traceFile.reset(new QFile(fileName));
+#endif
+ if (!m_traceFile->open(QFile::WriteOnly|QFile::Truncate))
+ qCritical("Failed to open trace file");
+ }
+
+ // Write Aspect + Job threads
+ {
+ FrameHeader header;
+ header.frameId = m_frameId;
+ header.jobCount = 0;
+
+ for (const QVector<JobRunStats> *storage : qAsConst(m_localStorages))
+ header.jobCount += storage->size();
+
+ m_traceFile->write(reinterpret_cast<char *>(&header), sizeof(FrameHeader));
+
+ for (QVector<JobRunStats> *storage : qAsConst(m_localStorages)) {
+ for (const JobRunStats &stat : *storage)
+ m_traceFile->write(reinterpret_cast<const char *>(&stat), sizeof(JobRunStats));
+ storage->clear();
+ }
+ }
+
+ // Write submission thread
+ {
+ QMutexLocker lock(&m_localStoragesMutex);
+ const int submissionJobSize = m_submissionStorage != nullptr ? m_submissionStorage->size() : 0;
+ if (submissionJobSize > 0) {
+ FrameHeader header;
+ header.frameId = m_frameId;
+ header.jobCount = submissionJobSize;
+ header.frameType = FrameHeader::Submission;
+
+ m_traceFile->write(reinterpret_cast<char *>(&header), sizeof(FrameHeader));
+
+ for (const JobRunStats &stat : *m_submissionStorage)
+ m_traceFile->write(reinterpret_cast<const char *>(&stat), sizeof(JobRunStats));
+ m_submissionStorage->clear();
+ }
+ }
+
+ m_traceFile->flush();
+ ++m_frameId;
+}
+
+void QSystemInformationServicePrivate::updateTracing()
+{
+ if (m_traceEnabled || m_graphicsTraceEnabled) {
+ if (!m_jobsStatTimer.isValid())
+ m_jobsStatTimer.start();
+ } else {
+ m_traceFile.reset();
+ }
+}
+
+
+QTaskLogger::QTaskLogger(QSystemInformationService *service, const JobId &jobId, Type type)
+ : m_service(service && service->isTraceEnabled() ? service : nullptr)
+ , m_type(type)
+{
+ m_stats.jobId = jobId;
+ if (m_service) {
+ m_stats.startTime = QSystemInformationServicePrivate::get(m_service)->m_jobsStatTimer.nsecsElapsed();
+ m_stats.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
+ }
+}
+
+QTaskLogger::QTaskLogger(QSystemInformationService *service,
+ const quint32 jobType,
+ const quint32 instance,
+ QTaskLogger::Type type)
+ : m_service(service && service->isTraceEnabled() ? service : nullptr)
+ , m_type(type)
+{
+ m_stats.jobId.typeAndInstance[0] = jobType;
+ m_stats.jobId.typeAndInstance[1] = instance;
+ if (m_service) {
+ m_stats.startTime = QSystemInformationServicePrivate::get(m_service)->m_jobsStatTimer.nsecsElapsed();
+ m_stats.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
+ }
+}
+
+QTaskLogger::~QTaskLogger() {
+ if (m_service) {
+ auto dservice = QSystemInformationServicePrivate::get(m_service);
+ if (m_stats.endTime == 0L)
+ m_stats.endTime = dservice->m_jobsStatTimer.nsecsElapsed();
+ switch (m_type) {
+ case AspectJob: dservice->addJobLogStatsEntry(m_stats); break;
+ case Submission: dservice->addSubmissionLogStatsEntry(m_stats); break;
+ }
+ }
+}
+
+void QTaskLogger::end(qint64 t)
+{
+ m_stats.endTime = t > 0 || !m_service ? t : QSystemInformationServicePrivate::get(m_service)->m_jobsStatTimer.nsecsElapsed();
+}
+
+qint64 QTaskLogger::restart()
+{
+ if (m_service)
+ m_stats.startTime = QSystemInformationServicePrivate::get(m_service)->m_jobsStatTimer.nsecsElapsed();
+ return m_stats.startTime;
+}
+
+
/* !\internal
\class Qt3DCore::QSystemInformationService
\inmodule Qt3DCore
@@ -58,8 +284,14 @@ namespace Qt3DCore {
the new service. This constructor is protected so only subclasses can
instantiate a QSystemInformationService object.
*/
-QSystemInformationService::QSystemInformationService(const QString &description)
- : QAbstractServiceProvider(*new QSystemInformationServicePrivate(description))
+
+QSystemInformationService::QSystemInformationService(QAspectEngine *aspectEngine)
+ : QAbstractServiceProvider(*new QSystemInformationServicePrivate(aspectEngine, QLatin1String("Default System Information Service")))
+{
+}
+
+QSystemInformationService::QSystemInformationService(QAspectEngine *aspectEngine, const QString &description)
+ : QAbstractServiceProvider(*new QSystemInformationServicePrivate(aspectEngine, description))
{
}
@@ -71,19 +303,135 @@ QSystemInformationService::QSystemInformationService(QSystemInformationServicePr
{
}
+bool QSystemInformationService::isTraceEnabled() const
+{
+ Q_D(const QSystemInformationService);
+ return d->m_traceEnabled;
+}
+
+bool QSystemInformationService::isGraphicsTraceEnabled() const
+{
+ Q_D(const QSystemInformationService);
+ return d->m_graphicsTraceEnabled;
+}
+
+bool QSystemInformationService::isCommandServerEnabled() const
+{
+ Q_D(const QSystemInformationService);
+ return d->m_commandDebugger != nullptr;
+}
+
+void QSystemInformationService::setTraceEnabled(bool traceEnabled)
+{
+ Q_D(QSystemInformationService);
+ if (d->m_traceEnabled != traceEnabled) {
+ d->m_traceEnabled = traceEnabled;
+ emit traceEnabledChanged(d->m_traceEnabled);
+ d->updateTracing();
+ }
+}
+
+void QSystemInformationService::setGraphicsTraceEnabled(bool graphicsTraceEnabled)
+{
+ Q_D(QSystemInformationService);
+ if (d->m_graphicsTraceEnabled != graphicsTraceEnabled) {
+ d->m_graphicsTraceEnabled = graphicsTraceEnabled;
+ emit graphicsTraceEnabledChanged(d->m_graphicsTraceEnabled);
+ d->updateTracing();
+ }
+}
+
/*
\fn QStringList Qt3DCore::QSystemInformationService::aspectNames() const
- Subclasses should override this function and return a string list containing the
- names of all registered aspects.
+ Returns a string list containing the names of all registered aspects.
*/
+QStringList QSystemInformationService::aspectNames() const
+{
+ Q_D(const QSystemInformationService);
+ if (!d->m_aspectEngine)
+ return {};
+
+ QStringList res;
+ const auto aspects = d->m_aspectEngine->aspects();
+ if (aspects.isEmpty())
+ return { QLatin1String("No loaded aspects") };
+
+ QAspectEnginePrivate *dengine = QAspectEnginePrivate::get(d->m_aspectEngine);
+ for (auto aspect: aspects) {
+ const QString name = dengine->m_factory.aspectName(aspect);
+ if (!name.isEmpty())
+ res << name;
+ else
+ res << QLatin1String("<unnamed>");
+ }
+
+ return res;
+}
/*
\fn int Qt3DCore::QSystemInformationService::threadPoolThreadCount() const
- Subclasses should override this function and return the number of threads in the
- Qt3D task manager's threadpool.
+ Returns the maximum number of threads in the Qt3D task manager's threadpool.
*/
+int QSystemInformationService::threadPoolThreadCount() const
+{
+ return QThreadPool::globalInstance()->maxThreadCount();
+}
+
+void QSystemInformationService::writePreviousFrameTraces()
+{
+ Q_D(QSystemInformationService);
+ d->writeFrameJobLogStats();
+}
+
+void QSystemInformationService::revealLogFolder()
+{
+ QDesktopServices::openUrl(QUrl::fromLocalFile(QDir::currentPath()));
+}
+
+QVariant QSystemInformationService::executeCommand(const QString &command)
+{
+ Q_D(QSystemInformationService);
+
+ if (command == QLatin1String("tracing on")) {
+ setTraceEnabled(true);
+ return {isTraceEnabled()};
+ }
+
+ if (command == QLatin1String("tracing off")) {
+ setTraceEnabled(false);
+ return {isTraceEnabled()};
+ }
+
+ if (command == QLatin1String("glprofiling on")) {
+ setGraphicsTraceEnabled(true);
+ return {isTraceEnabled()};
+ }
+
+ if (command == QLatin1String("glprofiling off")) {
+ setGraphicsTraceEnabled(false);
+ return {isTraceEnabled()};
+ }
+
+ return d->m_aspectEngine->executeCommand(command);
+}
+
+void QSystemInformationService::dumpCommand(const QString &command)
+{
+ QVariant res = executeCommand(command);
+ QObject *obj = res.value<QObject *>();
+ if (obj) {
+ auto reply = qobject_cast<Qt3DCore::Debug::AsynchronousCommandReply*>(obj);
+ if (reply) {
+ connect(reply, &Debug::AsynchronousCommandReply::finished, this, [reply]() {
+ qWarning() << qPrintable( QLatin1String(reply->data()) );
+ });
+ return;
+ }
+ }
+ qWarning() << qPrintable(res.toString());
+}
}
diff --git a/src/core/services/qsysteminformationservice_p.h b/src/core/services/qsysteminformationservice_p.h
index a8a83701b..4e6dc0c00 100644
--- a/src/core/services/qsysteminformationservice_p.h
+++ b/src/core/services/qsysteminformationservice_p.h
@@ -53,6 +53,7 @@
#include <Qt3DCore/qt3dcore_global.h>
#include <QtCore/qstringlist.h>
+#include <QtCore/qvariant.h>
#include <Qt3DCore/private/qservicelocator_p.h>
@@ -61,16 +62,40 @@ QT_BEGIN_NAMESPACE
namespace Qt3DCore {
class QSystemInformationServicePrivate;
+struct JobRunStats;
class Q_3DCORESHARED_EXPORT QSystemInformationService : public QAbstractServiceProvider
{
Q_OBJECT
+ Q_PROPERTY(bool traceEnabled READ isTraceEnabled WRITE setTraceEnabled NOTIFY traceEnabledChanged)
+ Q_PROPERTY(bool graphicsTraceEnabled READ isGraphicsTraceEnabled WRITE setGraphicsTraceEnabled NOTIFY graphicsTraceEnabledChanged)
+ Q_PROPERTY(bool commandServerEnabled READ isCommandServerEnabled CONSTANT)
public:
- virtual QStringList aspectNames() const = 0;
- virtual int threadPoolThreadCount() const = 0;
+ QSystemInformationService(QAspectEngine *aspectEngine);
+
+ bool isTraceEnabled() const;
+ bool isGraphicsTraceEnabled() const;
+ bool isCommandServerEnabled() const;
+
+ QStringList aspectNames() const;
+ int threadPoolThreadCount() const;
+
+ void writePreviousFrameTraces();
+ Q_INVOKABLE void revealLogFolder();
+
+public Q_SLOTS:
+ void setTraceEnabled(bool traceEnabled);
+ void setGraphicsTraceEnabled(bool graphicsTraceEnabled);
+ QVariant executeCommand(const QString &command);
+ void dumpCommand(const QString &command);
+
+signals:
+ void traceEnabledChanged(bool traceEnabled);
+ void graphicsTraceEnabledChanged(bool graphicsTraceEnabled);
protected:
- QSystemInformationService(const QString &description = QString());
+ Q_DECLARE_PRIVATE(QSystemInformationService)
+ QSystemInformationService(QAspectEngine *aspectEngine, const QString &description);
QSystemInformationService(QSystemInformationServicePrivate &dd);
};
diff --git a/src/core/services/qsysteminformationservice_p_p.h b/src/core/services/qsysteminformationservice_p_p.h
index e3ce9fe49..062a693d5 100644
--- a/src/core/services/qsysteminformationservice_p_p.h
+++ b/src/core/services/qsysteminformationservice_p_p.h
@@ -51,21 +51,100 @@
// We mean it.
//
-#include <Qt3DCore/qt3dcore_global.h>
+#include <QtCore/QThreadStorage>
+#include <QtCore/QElapsedTimer>
+#include <QtCore/QFile>
+#include <QtCore/QMutex>
+#include <Qt3DCore/qt3dcore_global.h>
+#include <Qt3DCore/private/qt3dcore_global_p.h>
#include <Qt3DCore/private/qabstractserviceprovider_p.h>
#include <Qt3DCore/private/qservicelocator_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DCore {
-class QSystemInformationServicePrivate : public QAbstractServiceProviderPrivate
+namespace Debug {
+class AspectCommandDebugger;
+} // Debug
+
+union Q_3DCORE_PRIVATE_EXPORT JobId
+{
+ JobId() : id(0L) { }
+ JobId(quint32 t, quint32 i) { typeAndInstance[0] = t; typeAndInstance[1] = i; }
+
+ quint32 typeAndInstance[2];
+ quint64 id;
+};
+
+class Q_3DCORE_PRIVATE_EXPORT QSystemInformationServicePrivate : public QAbstractServiceProviderPrivate
{
public:
- QSystemInformationServicePrivate(const QString &description)
- : QAbstractServiceProviderPrivate(QServiceLocator::SystemInformation, description)
- {}
+ struct JobRunStats
+ {
+ JobRunStats() { jobId.id = 0; startTime = 0L; endTime = 0L; }
+
+ qint64 startTime;
+ qint64 endTime;
+ JobId jobId; // QAspectJob subclasses should properly populate the jobId
+ quint64 threadId;
+ };
+
+ QSystemInformationServicePrivate(QAspectEngine *aspectEngine, const QString &description);
+ ~QSystemInformationServicePrivate();
+
+ static QSystemInformationServicePrivate *get(QSystemInformationService *q);
+
+ // Aspects + Job threads
+ void addJobLogStatsEntry(JobRunStats &stats);
+
+ // Submission thread
+ void addSubmissionLogStatsEntry(JobRunStats &stats);
+
+ void writeFrameJobLogStats();
+ void updateTracing();
+
+ QAspectEngine *m_aspectEngine;
+ bool m_traceEnabled;
+ bool m_graphicsTraceEnabled;
+
+ QElapsedTimer m_jobsStatTimer;
+ QThreadStorage<QVector<JobRunStats> *> m_jobStatsCached;
+
+ QVector<QVector<JobRunStats> *> m_localStorages;
+ QVector<JobRunStats> *m_submissionStorage;
+
+ QMutex m_localStoragesMutex;
+
+ QScopedPointer<QFile> m_traceFile;
+ quint32 m_frameId;
+
+ Debug::AspectCommandDebugger *m_commandDebugger;
+
+ Q_DECLARE_PUBLIC(QSystemInformationService)
+};
+
+class Q_3DCORE_PRIVATE_EXPORT QTaskLogger {
+public:
+ enum Type {
+ AspectJob,
+ Submission
+ };
+
+ QTaskLogger(QSystemInformationService *service, const JobId &jobId, Type type);
+ QTaskLogger(QSystemInformationService *service, const quint32 jobType, const quint32 instance, Type type = Submission);
+
+ ~QTaskLogger();
+
+ void end(qint64 t = 0L);
+ qint64 restart();
+
+private:
+ QSystemInformationService *m_service;
+ QSystemInformationServicePrivate::JobRunStats m_stats;
+ Type m_type;
};
}
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..2531616a0 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)
@@ -482,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/qabstractskeleton.cpp b/src/core/transforms/qabstractskeleton.cpp
index 5f3b05eb8..4a30d0710 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 <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -47,6 +46,7 @@ namespace Qt3DCore {
QAbstractSkeletonPrivate::QAbstractSkeletonPrivate()
: Qt3DCore::QNodePrivate()
+ , m_type(QSkeletonCreatedChangeBase::Skeleton)
, m_jointCount(0)
{
}
@@ -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
@@ -127,16 +134,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<Qt3DCore::QPropertyUpdatedChange>(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..1c2eba08f 100644
--- a/src/core/transforms/qabstractskeleton.h
+++ b/src/core/transforms/qabstractskeleton.h
@@ -64,7 +64,8 @@ Q_SIGNALS:
protected:
QAbstractSkeleton(QAbstractSkeletonPrivate &dd, Qt3DCore::QNode *parent = nullptr);
- void sceneChangeEvent(const QSceneChangePtr &change) override;
+ // TODO Unused remove in Qt6
+ void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override;
private:
Q_DECLARE_PRIVATE(QAbstractSkeleton)
diff --git a/src/core/transforms/qskeletonloader.cpp b/src/core/transforms/qskeletonloader.cpp
index d5296ecc9..b1a311a0c 100644
--- a/src/core/transforms/qskeletonloader.cpp
+++ b/src/core/transforms/qskeletonloader.cpp
@@ -68,6 +68,27 @@ void QSkeletonLoaderPrivate::setStatus(QSkeletonLoader::Status status)
}
}
+void QSkeletonLoaderPrivate::setRootJoint(QJoint *rootJoint)
+{
+ Q_Q(QSkeletonLoader);
+ if (rootJoint == m_rootJoint)
+ return;
+
+ if (m_rootJoint)
+ unregisterDestructionHelper(m_rootJoint);
+
+ if (rootJoint && !rootJoint->parent())
+ rootJoint->setParent(q);
+
+ m_rootJoint = rootJoint;
+
+ // Ensures proper bookkeeping
+ if (m_rootJoint)
+ registerPrivateDestructionHelper(m_rootJoint, &QSkeletonLoaderPrivate::setRootJoint);
+
+ emit q->rootJointChanged(m_rootJoint);
+}
+
/*!
\qmltype SkeletonLoader
\inqmlmodule Qt3D.Core
@@ -217,39 +238,12 @@ void QSkeletonLoader::setCreateJointsEnabled(bool createJoints)
void QSkeletonLoader::setRootJoint(QJoint *rootJoint)
{
Q_D(QSkeletonLoader);
- if (rootJoint == d->m_rootJoint)
- return;
-
- if (d->m_rootJoint)
- d->unregisterDestructionHelper(d->m_rootJoint);
-
- if (rootJoint && !rootJoint->parent())
- rootJoint->setParent(this);
-
- d->m_rootJoint = rootJoint;
-
- // Ensures proper bookkeeping
- if (d->m_rootJoint)
- d->registerDestructionHelper(d->m_rootJoint, &QSkeletonLoader::setRootJoint, d->m_rootJoint);
-
- emit rootJointChanged(d->m_rootJoint);
+ d->setRootJoint(rootJoint);
}
/*! \internal */
void QSkeletonLoader::sceneChangeEvent(const QSceneChangePtr &change)
{
- Q_D(QSkeletonLoader);
- if (change->type() == Qt3DCore::PropertyUpdated) {
- auto propertyChange = qSharedPointerCast<QStaticPropertyUpdatedChangeBase>(change);
- if (propertyChange->propertyName() == QByteArrayLiteral("status")) {
- const auto e = qSharedPointerCast<Qt3DCore::QPropertyUpdatedChange>(change);
- d->setStatus(static_cast<QSkeletonLoader::Status>(e->value().toInt()));
- } else if (propertyChange->propertyName() == QByteArrayLiteral("rootJoint")) {
- auto typedChange = qSharedPointerCast<QJointChange>(propertyChange);
- auto rootJoint = std::move(typedChange->data);
- setRootJoint(rootJoint.release());
- }
- }
QAbstractSkeleton::sceneChangeEvent(change);
}
diff --git a/src/core/transforms/qskeletonloader_p.h b/src/core/transforms/qskeletonloader_p.h
index 5c415745b..6bd4e1eef 100644
--- a/src/core/transforms/qskeletonloader_p.h
+++ b/src/core/transforms/qskeletonloader_p.h
@@ -70,6 +70,7 @@ public:
QSkeletonLoaderPrivate();
void setStatus(QSkeletonLoader::Status status);
+ void setRootJoint(QJoint *rootJoint);
Q_DECLARE_PUBLIC(QSkeletonLoader)
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/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/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; }
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
diff --git a/src/extras/defaults/qabstractspritesheet.cpp b/src/extras/defaults/qabstractspritesheet.cpp
index 640e600c7..2cf134f7c 100644
--- a/src/extras/defaults/qabstractspritesheet.cpp
+++ b/src/extras/defaults/qabstractspritesheet.cpp
@@ -100,7 +100,7 @@ QAbstractSpriteSheet::~QAbstractSpriteSheet()
}
/*!
- \property QAbstractSpriteSheet::texture
+ \property Qt3DExtras::QAbstractSpriteSheet::texture
Holds the current texture used by the material.
*/
diff --git a/src/extras/defaults/qforwardrenderer.cpp b/src/extras/defaults/qforwardrenderer.cpp
index f1306e787..1268ab03d 100644
--- a/src/extras/defaults/qforwardrenderer.cpp
+++ b/src/extras/defaults/qforwardrenderer.cpp
@@ -47,6 +47,7 @@
#include <Qt3DRender/qfilterkey.h>
#include <Qt3DRender/qfrustumculling.h>
#include <Qt3DRender/qrendersurfaceselector.h>
+#include <Qt3DRender/qdebugoverlay.h>
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,15 @@ 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);
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 +150,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 +206,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 +367,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/extras/defaults/qt3dwindow.cpp b/src/extras/defaults/qt3dwindow.cpp
index b373127b0..f555308a6 100644
--- a/src/extras/defaults/qt3dwindow.cpp
+++ b/src/extras/defaults/qt3dwindow.cpp
@@ -237,7 +237,7 @@ void Qt3DWindow::showEvent(QShowEvent *e)
void Qt3DWindow::resizeEvent(QResizeEvent *)
{
Q_D(Qt3DWindow);
- d->m_defaultCamera->setAspectRatio(float(width()) / float(height()));
+ d->m_defaultCamera->setAspectRatio(float(width()) / std::max(1.f, static_cast<float>(height())));
}
/*!
diff --git a/src/extras/extras.pro b/src/extras/extras.pro
index 396c9aa91..172e98881 100644
--- a/src/extras/extras.pro
+++ b/src/extras/extras.pro
@@ -3,6 +3,7 @@ MODULE = 3dextras
QT += core-private 3dcore 3dcore-private 3drender 3drender-private 3dinput 3dlogic
DEFINES += QT3DEXTRAS_LIBRARY
+DEFINES += BUILD_QT3D_MODULE
load(qt_module)
diff --git a/src/extras/shaders/es2/distancefieldtext.frag b/src/extras/shaders/es2/distancefieldtext.frag
index d2db2e306..b7563e397 100644
--- a/src/extras/shaders/es2/distancefieldtext.frag
+++ b/src/extras/shaders/es2/distancefieldtext.frag
@@ -33,5 +33,5 @@ void main()
FP float maxAlpha = threshold + range;
FP float distVal = texture2D(distanceFieldTexture, texCoord).r;
- gl_FragColor = color * smoothstep(minAlpha, maxAlpha, distVal);
+ gl_FragColor = vec4(color.rgb, color.a * smoothstep(minAlpha, maxAlpha, distVal));
}
diff --git a/src/extras/shaders/gl3/distancefieldtext.frag b/src/extras/shaders/gl3/distancefieldtext.frag
index 23dff8e0f..998fa6e79 100644
--- a/src/extras/shaders/gl3/distancefieldtext.frag
+++ b/src/extras/shaders/gl3/distancefieldtext.frag
@@ -34,6 +34,6 @@ void main()
float maxAlpha = threshold + range;
float distVal = texture(distanceFieldTexture, texCoord).r;
- fragColor = color * smoothstep(minAlpha, maxAlpha, distVal);
- gl_FragDepth = gl_FragCoord.z - zValue * 0.00001;
+ fragColor = vec4(color.rgb, color.a * smoothstep(minAlpha, maxAlpha, distVal));
+ gl_FragDepth = gl_FragCoord.z - zValue * 0.000001;
}
diff --git a/src/extras/text/qtext2dentity.cpp b/src/extras/text/qtext2dentity.cpp
index aa4785fe7..897672782 100644
--- a/src/extras/text/qtext2dentity.cpp
+++ b/src/extras/text/qtext2dentity.cpp
@@ -217,9 +217,6 @@ struct RenderData {
void QText2DEntityPrivate::setCurrentGlyphRuns(const QVector<QGlyphRun> &runs)
{
- if (runs.isEmpty())
- return;
-
// For each distinct texture, we need a separate DistanceFieldTextRenderer,
// for which we need vertex and index data
QHash<Qt3DRender::QAbstractTexture*, RenderData> renderData;
@@ -294,6 +291,11 @@ void QText2DEntityPrivate::setCurrentGlyphRuns(const QVector<QGlyphRun> &runs)
}
}
+ // de-ref all glyphs for previous QGlyphRuns
+ for (int i = 0; i < m_currentGlyphRuns.size(); i++)
+ m_glyphCache->derefGlyphs(m_currentGlyphRuns[i]);
+ m_currentGlyphRuns = runs;
+
// make sure we have the correct number of DistanceFieldTextRenderers
// TODO: we might keep one renderer at all times, so we won't delete and
// re-allocate one every time the text changes from an empty to a non-empty string
@@ -314,11 +316,6 @@ void QText2DEntityPrivate::setCurrentGlyphRuns(const QVector<QGlyphRun> &runs)
for (auto it = renderData.begin(); it != renderData.end(); ++it) {
m_renderers[rendererIdx++]->setGlyphData(it.key(), it.value().vertex, it.value().index);
}
-
- // de-ref all glyphs for previous QGlyphRuns
- for (int i = 0; i < m_currentGlyphRuns.size(); i++)
- m_glyphCache->derefGlyphs(m_currentGlyphRuns[i]);
- m_currentGlyphRuns = runs;
}
void QText2DEntityPrivate::clearCurrentGlyphRuns()
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/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 <Qt3DInput/qkeyboarddevice.h>
#include <Qt3DInput/qkeyboardhandler.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <QtCore/QVariant>
#include <Qt3DInput/private/inputhandler_p.h>
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<QT_PREPEND_NAMESPACE (QWheelEvent)> &events)
{
@@ -153,8 +159,8 @@ void MouseDevice::updateMouseEvents(const QList<QT_PREPEND_NAMESPACE(QMouseEvent
m_mouseState.leftPressed = e.buttons() & (Qt::LeftButton);
m_mouseState.centerPressed = e.buttons() & (Qt::MiddleButton);
m_mouseState.rightPressed = e.buttons() & (Qt::RightButton);
- bool pressed = m_mouseState.leftPressed || m_mouseState.centerPressed || m_mouseState.rightPressed;
- if (m_wasPressed && pressed) {
+ const bool pressed = m_mouseState.leftPressed || m_mouseState.centerPressed || m_mouseState.rightPressed;
+ if (m_updateAxesContinuously || (m_wasPressed && pressed)) {
m_mouseState.xAxis += m_sensitivity * (e.screenPos().x() - m_previousPos.x());
m_mouseState.yAxis += m_sensitivity * (m_previousPos.y() - e.screenPos().y());
}
@@ -172,6 +178,7 @@ void MouseDevice::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTi
return;
m_sensitivity = node->sensitivity();
+ 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/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/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 <Qt3DInput/qmousehandler.h>
#include <Qt3DInput/qmousedevice.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DInput/private/inputmanagers_p.h>
#include <Qt3DInput/private/inputhandler_p.h>
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 <Qt3DInput/qphysicaldevicecreatedchange.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
diff --git a/src/input/frontend/qaction.cpp b/src/input/frontend/qaction.cpp
index c835062a2..8cceaab51 100644
--- a/src/input/frontend/qaction.cpp
+++ b/src/input/frontend/qaction.cpp
@@ -41,7 +41,6 @@
#include "qaction_p.h"
#include <Qt3DInput/qabstractactioninput.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qnodecreatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
@@ -149,6 +148,11 @@ QVector<QAbstractActionInput *> 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<QActionData>::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/qactioninput.cpp b/src/input/frontend/qactioninput.cpp
index 9f32f57cc..f013147f2 100644
--- a/src/input/frontend/qactioninput.cpp
+++ b/src/input/frontend/qactioninput.cpp
@@ -181,7 +181,7 @@ QAbstractPhysicalDevice *QActionInput::sourceDevice() const
/*!
\qmlsignal Qt3D.Input::ActionInput::buttonsChanged(const QVector<int> &buttons)
- This signal is emitted when the buttons associated with the action input is changed.
+ This signal is emitted when the \a buttons associated with the action input is changed.
The corresponding handler is \c onbuttonsChanged
*/
diff --git a/src/input/frontend/qaxis.cpp b/src/input/frontend/qaxis.cpp
index b6018c887..d76135fd7 100644
--- a/src/input/frontend/qaxis.cpp
+++ b/src/input/frontend/qaxis.cpp
@@ -40,7 +40,6 @@
#include "qaxis_p.h"
#include <Qt3DInput/qabstractaxisinput.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qnodecreatedchange.h>
QT_BEGIN_NAMESPACE
@@ -168,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<QAxisData>::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 7e9930f66..a7bb14441 100644
--- a/src/input/frontend/qaxisaccumulator.cpp
+++ b/src/input/frontend/qaxisaccumulator.cpp
@@ -42,7 +42,6 @@
#include <Qt3DInput/qaxis.h>
#include <Qt3DCore/qnodecreatedchange.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -290,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 257a5be8c..1ec1f8ead 100644
--- a/src/input/frontend/qkeyboarddevice.cpp
+++ b/src/input/frontend/qkeyboarddevice.cpp
@@ -41,7 +41,6 @@
#include "qkeyboarddevice_p.h"
#include <Qt3DInput/qkeyboardhandler.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qscene_p.h>
@@ -310,16 +309,11 @@ QKeyboardDevice::QKeyboardDevice(QKeyboardDevicePrivate &dd, QNode *parent)
{
}
-/*! \internal */
-void QKeyboardDevice::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change)
+// TODO Unused remove in Qt6
+void QKeyboardDevice::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &)
{
- Q_D(QKeyboardDevice);
- Qt3DCore::QPropertyUpdatedChangePtr e = qSharedPointerCast<Qt3DCore::QPropertyUpdatedChange>(change);
- if (e->type() == Qt3DCore::PropertyUpdated && e->propertyName() == QByteArrayLiteral("activeInput")) {
- Qt3DCore::QNodeId activeInputId = e->value().value<Qt3DCore::QNodeId>();
- setActiveInput(qobject_cast<QKeyboardHandler *>(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..df2f47020 100644
--- a/src/input/frontend/qkeyboarddevice.h
+++ b/src/input/frontend/qkeyboarddevice.h
@@ -71,6 +71,7 @@ public:
protected:
explicit QKeyboardDevice(QKeyboardDevicePrivate &dd, QNode *parent = nullptr);
+ // TODO Unused remove in Qt6
void sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change) override;
Q_SIGNALS:
diff --git a/src/input/frontend/qkeyboardhandler.cpp b/src/input/frontend/qkeyboardhandler.cpp
index aff136a04..92ce39c31 100644
--- a/src/input/frontend/qkeyboardhandler.cpp
+++ b/src/input/frontend/qkeyboardhandler.cpp
@@ -41,7 +41,6 @@
#include "qkeyboardhandler_p.h"
#include <Qt3DInput/qkeyboarddevice.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -238,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<QKeyboardHandlerData>::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/qkeyevent.cpp b/src/input/frontend/qkeyevent.cpp
index a70a2970b..efbddc771 100644
--- a/src/input/frontend/qkeyevent.cpp
+++ b/src/input/frontend/qkeyevent.cpp
@@ -160,7 +160,7 @@ QKeyEvent::~QKeyEvent()
/*!
\qmlmethod bool Qt3D.Input::KeyEvent::matches(StandardKey key)
- Returns \c true if the key event matches the given standard key; otherwise
+ Returns \c true if the key event matches the given standard \a key; otherwise
returns \c false.
\sa QKeySequence::StandardKey
@@ -174,7 +174,7 @@ QKeyEvent::~QKeyEvent()
See \l [CPP] {Qt::Key}{Qt.Key} for the list of keyboard codes.
- \sa {QKeyEvent::key}
+ \b {See also} \l [QtGui] {QKeyEvent::key()}.
*/
/*!
@@ -194,7 +194,7 @@ QKeyEvent::~QKeyEvent()
This property holds the keyboard modifier flags that existed immediately
before the event occurred.
- \sa {QKeyEvent::modifiers}
+ \b {See also} \l [QtGui] {QKeyEvent::modifiers()}.
*/
/*!
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/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, typename QtEventClass>
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<typename EventClass::Modifiers>(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<QWheelEvent> 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/src/input/frontend/qmousehandler.cpp b/src/input/frontend/qmousehandler.cpp
index 944ca391a..89d76a057 100644
--- a/src/input/frontend/qmousehandler.cpp
+++ b/src/input/frontend/qmousehandler.cpp
@@ -42,7 +42,6 @@
#include <Qt3DInput/qmousedevice.h>
#include <Qt3DInput/qmouseevent.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <QtCore/QTimer>
QT_BEGIN_NAMESPACE
@@ -198,21 +197,21 @@ void QMouseHandlerPrivate::mouseEvent(const QMouseEventPtr &event)
\qmlsignal Qt3D.Input::MouseHandler::wheel(MouseEvent mouse)
This signal is emitted when the mouse wheel is used with the event details
- being contained within \a wheel
+ being contained within \a mouse.
*/
/*!
\fn Qt3DInput::QMouseHandler::clicked(Qt3DInput::QMouseEvent *mouse)
This signal is emitted when a mouse button is clicked with the event details
- being contained within \a mouse
+ being contained within \a mouse.
*/
/*!
\fn Qt3DInput::QMouseHandler::doubleClicked(Qt3DInput::QMouseEvent *mouse)
This signal is emitted when a mouse button is double clicked with the event
- details being contained within \a mouse
+ details being contained within \a mouse.
*/
/*!
@@ -299,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/input/frontend/qphysicaldevicecreatedchange.cpp b/src/input/frontend/qphysicaldevicecreatedchange.cpp
index c14770d80..905633b7f 100644
--- a/src/input/frontend/qphysicaldevicecreatedchange.cpp
+++ b/src/input/frontend/qphysicaldevicecreatedchange.cpp
@@ -54,7 +54,7 @@ QPhysicalDeviceCreatedChangeBasePrivate::QPhysicalDeviceCreatedChangeBasePrivate
}
/*!
- \class QPhysicalDeviceCreatedChangeBase
+ \class Qt3DInput::QPhysicalDeviceCreatedChangeBase
\inmodule Qt3DInput
\brief Base class for handling changes in physical devices.
*/
diff --git a/src/input/input.pro b/src/input/input.pro
index 938e77643..9596d092a 100644
--- a/src/input/input.pro
+++ b/src/input/input.pro
@@ -1,6 +1,7 @@
TARGET = Qt3DInput
DEFINES += QT3DINPUT_LIBRARY
+DEFINES += BUILD_QT3D_MODULE
MODULE = 3dinput
MODULE_PLUGIN_TYPES = 3dinputdevices
diff --git a/src/logic/callbackjob.cpp b/src/logic/callbackjob.cpp
index 5c04d8838..5dfc74f02 100644
--- a/src/logic/callbackjob.cpp
+++ b/src/logic/callbackjob.cpp
@@ -51,7 +51,7 @@ CallbackJob::CallbackJob()
: QAspectJob()
, m_logicManager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::Callback, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::Callback, 0)
}
void CallbackJob::setManager(Manager *manager)
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<QNode *> nodes = m_scene->lookupNodes(m_nodeIds);
for (QNode *node : nodes) {
QFrameAction *frameAction = qobject_cast<QFrameAction *>(node);
diff --git a/src/logic/logic.pro b/src/logic/logic.pro
index 0fa0f8d55..ac744a6bb 100644
--- a/src/logic/logic.pro
+++ b/src/logic/logic.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DLogic
MODULE = 3dlogic
+DEFINES += BUILD_QT3D_MODULE
QT = core-private gui-private 3dcore 3dcore-private
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/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()
diff --git a/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp b/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp
index 19b06a8b0..2c8bb14c3 100644
--- a/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp
+++ b/src/plugins/geometryloaders/gltf/gltfgeometryloader.cpp
@@ -48,6 +48,7 @@
#include <Qt3DRender/QGeometry>
#include <Qt3DRender/private/renderlogging_p.h>
+#include <Qt3DCore/private/qloadgltf_p.h>
QT_BEGIN_NAMESPACE
@@ -102,10 +103,7 @@ bool GLTFGeometryLoader::load(QIODevice *ioDev, const QString &subMesh)
{
Q_UNUSED(subMesh);
- QByteArray jsonData = ioDev->readAll();
- QJsonDocument sceneDocument = QJsonDocument::fromJson(jsonData);
-
- if (Q_UNLIKELY(!setJSON(sceneDocument))) {
+ if (Q_UNLIKELY(!setJSON(qLoadGLTF(ioDev->readAll())))) {
qCWarning(GLTFGeometryLoaderLog, "not a JSON document");
return false;
}
@@ -137,7 +135,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/plugins/renderers/dummy/dummy.pro b/src/plugins/renderers/dummy/dummy.pro
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/src/plugins/renderers/dummy/dummy.pro
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..e23476860
--- /dev/null
+++ b/src/plugins/renderers/opengl/debug/imguirenderer.cpp
@@ -0,0 +1,706 @@
+/****************************************************************************
+**
+** 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 <renderview_p.h>
+#include <renderer_p.h>
+#include <submissioncontext_p.h>
+#include <Qt3DRender/private/geometryrenderermanager_p.h>
+
+#include <QDateTime>
+#include <QGuiApplication>
+#include <QMouseEvent>
+#include <QClipboard>
+#include <QCursor>
+#include <QOpenGLExtraFunctions>
+
+#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;
+using namespace Render::OpenGL;
+
+namespace {
+
+ const QHash<int, ImGuiKey> 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(Qt3DRender::Render::OpenGL::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<const char *>(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<RenderView *> &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<double>(1000.0f / ImGui::GetIO().Framerate), static_cast<double>(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<HGeometryRenderer> inUseGeometries;
+ QSet<Qt3DCore::QNodeId> inUseTextures;
+ for (int j=0; j<renderViewsCount; j++) {
+ const auto &commands = renderViews.at(j)->commands();
+ nCommands += commands.size();
+ for (int k=0; k<commands.size(); k++) {
+ const RenderCommand &command = commands.at(k);
+ if (command.m_type != RenderCommand::Draw)
+ continue;
+ nVertices += command.m_primitiveCount;
+ nPrimitives += vertexToPrimitiveCount(command.m_primitiveType, command.m_primitiveCount);
+ inUseGeometries.insert(command.m_geometryRenderer);
+ const auto &textures = command.m_parameterPack.textures();
+ for (const auto &ns: textures)
+ inUseTextures.insert(ns.nodeId);
+ }
+ }
+
+ auto columnNumber = [](int i) {
+ if (i == 0)
+ ImGui::Text("--");
+ else
+ ImGui::Text(" %d", i);
+ ImGui::NextColumn();
+ };
+ auto column2Numbers = [](int i, int of) {
+ if (of == 0)
+ ImGui::Text("--");
+ else
+ ImGui::Text(" %d of %d", i, of);
+ ImGui::NextColumn();
+ };
+
+ ImGui::Columns(5);
+ ImGui::Separator();
+ for (auto s: {"Jobs", "RV", "Cmds", "Verts", "Prims"}) {
+ ImGui::Text("#%s", s);
+ ImGui::NextColumn();
+ }
+ for (auto s: {jobsInLastFrame, renderViewsCount, nCommands, nVertices, nPrimitives})
+ columnNumber(s);
+
+ ImGui::Columns(3);
+ ImGui::Separator();
+ for (auto s: {"Entities", "Geometries", "Textures"}) {
+ ImGui::Text("#%s", s);
+ ImGui::NextColumn();
+ }
+ columnNumber(m_renderer->nodeManagers()->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<RenderView *> &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<double>(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<GLsizei>(fb_width), static_cast<GLsizei>(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<GLsizeiptr>(cmd_list->VtxBuffer.Size) * sizeof(ImDrawVert), static_cast<const GLvoid*>(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<GLsizeiptr>(cmd_list->IdxBuffer.Size) * sizeof(ImDrawIdx), static_cast<const GLvoid*>(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<int>(pcmd->ClipRect.x), static_cast<int>(fb_height - pcmd->ClipRect.w),
+ static_cast<int>(pcmd->ClipRect.z - pcmd->ClipRect.x), static_cast<int>(pcmd->ClipRect.w - pcmd->ClipRect.y));
+ m_funcs->glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(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<GLsizei>(last_viewport[2]), static_cast<GLsizei>(last_viewport[3]));
+ m_funcs->glScissor(last_scissor_box[0], last_scissor_box[1], static_cast<GLsizei>(last_scissor_box[2]), static_cast<GLsizei>(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<size_t>(&((static_cast<TYPE *>(nullptr))->ELEMENT)))
+ m_funcs->glVertexAttribPointer(m_attribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast<GLvoid*>(OFFSETOF(ImDrawVert, pos)));
+ m_funcs->glVertexAttribPointer(m_attribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), reinterpret_cast<GLvoid*>(OFFSETOF(ImDrawVert, uv)));
+ m_funcs->glVertexAttribPointer(m_attribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), reinterpret_cast<GLvoid*>(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<float>(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<ImWchar>(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<QMouseEvent *>(event));
+ break;
+ case QEvent::Wheel:
+ this->onWheel(static_cast<QWheelEvent *>(event));
+ break;
+ case QEvent::KeyPress:
+ case QEvent::KeyRelease:
+ this->onKeyPressRelease(static_cast<QKeyEvent *>(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..f462bbd5b
--- /dev/null
+++ b/src/plugins/renderers/opengl/debug/imguirenderer_p.h
@@ -0,0 +1,137 @@
+/****************************************************************************
+**
+** 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 <QObject>
+#include <QOpenGLFunctions>
+#include <QPoint>
+#include <memory>
+
+struct ImDrawData;
+
+QT_BEGIN_NAMESPACE
+
+class QMouseEvent;
+class QWheelEvent;
+class QKeyEvent;
+class QOpenGLExtraFunctions;
+class QOpenGLShaderProgram;
+
+namespace Qt3DCore {
+class QServiceLocator;
+}
+
+namespace Qt3DRender {
+namespace Render {
+namespace OpenGL {
+class RenderView;
+class Renderer;
+}
+
+namespace Debug {
+
+#define IMGUI_PERF_LOG_SIZE 30
+
+class ImGuiRenderer : public QObject {
+ Q_OBJECT
+public:
+ ImGuiRenderer(Qt3DRender::Render::OpenGL::Renderer *renderer);
+
+ void processEvent(QEvent *event);
+ void renderDebugOverlay(const QVector<Render::OpenGL::RenderView *> &renderViews, const Render::OpenGL::RenderView *renderView, int jobsInLastFrame);
+
+ void setCapabilities(const QString &capabilities);
+
+private:
+ 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<Render::OpenGL::RenderView *> &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;
+
+ Render::OpenGL::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<float, float> m_fpsRange;
+ std::pair<float, float> 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/graphicscontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp
index a2196fa0e..16cc3ff8f 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicscontext.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext.cpp
@@ -45,37 +45,40 @@
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/shader_p.h>
#include <Qt3DRender/private/material_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
#include <Qt3DRender/private/buffer_p.h>
#include <Qt3DRender/private/attribute_p.h>
-#include <Qt3DRender/private/rendercommand_p.h>
-#include <Qt3DRender/private/renderstateset_p.h>
#include <Qt3DRender/private/rendertarget_p.h>
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/buffermanager_p.h>
#include <Qt3DRender/private/managers_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
#include <Qt3DRender/private/qbuffer_p.h>
-#include <Qt3DRender/private/renderbuffer_p.h>
+#include <Qt3DRender/private/attachmentpack_p.h>
+#include <Qt3DRender/private/qbuffer_p.h>
+#include <Qt3DRender/private/renderstateset_p.h>
#include <QOpenGLShaderProgram>
+#include <glresourcemanagers_p.h>
+#include <graphicshelperinterface_p.h>
+#include <gltexture_p.h>
+#include <rendercommand_p.h>
+#include <renderer_p.h>
+#include <renderbuffer_p.h>
+#include <glshader_p.h>
#if !defined(QT_OPENGL_ES_2)
#include <QOpenGLFunctions_2_0>
#include <QOpenGLFunctions_3_2_Core>
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLFunctions_4_3_Core>
-#include <Qt3DRender/private/graphicshelpergl2_p.h>
-#include <Qt3DRender/private/graphicshelpergl3_2_p.h>
-#include <Qt3DRender/private/graphicshelpergl3_3_p.h>
-#include <Qt3DRender/private/graphicshelpergl4_p.h>
+#include <graphicshelpergl2_p.h>
+#include <graphicshelpergl3_2_p.h>
+#include <graphicshelpergl3_3_p.h>
+#include <graphicshelpergl4_p.h>
#endif
-#include <Qt3DRender/private/graphicshelperes2_p.h>
-#include <Qt3DRender/private/graphicshelperes3_p.h>
-#include <Qt3DRender/private/graphicshelperes3_1_p.h>
-#include <Qt3DRender/private/graphicshelperes3_2_p.h>
+#include <graphicshelperes2_p.h>
+#include <graphicshelperes3_p.h>
+#include <graphicshelperes3_1_p.h>
+#include <graphicshelperes3_2_p.h>
#include <QSurface>
#include <QWindow>
@@ -117,6 +120,7 @@ QOpenGLShader::ShaderType shaderType(Qt3DRender::QShaderProgram::ShaderType type
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
namespace {
@@ -137,7 +141,6 @@ GraphicsContext::GraphicsContext()
, m_defaultFBO(0)
, m_gl(nullptr)
, m_glHelper(nullptr)
- , m_shaderCache(nullptr)
#ifdef QT_OPENGL_LIB
, m_debugLogger(nullptr)
#endif
@@ -159,7 +162,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";
@@ -237,12 +240,13 @@ void GraphicsContext::doneCurrent()
}
// Called by GL Command Thread
-QOpenGLShaderProgram *GraphicsContext::createShaderProgram(Shader *shaderNode)
+GraphicsContext::ShaderCreationInfo GraphicsContext::createShaderProgram(GLShader *shader)
{
- QScopedPointer<QOpenGLShaderProgram> 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<QShaderProgram::ShaderType>(i);
@@ -257,80 +261,77 @@ 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;
}
-// Called by GL Command Thread (can't use global glHelpers)
// That assumes that the shaderProgram in Shader stays the same
-void GraphicsContext::introspectShaderInterface(Shader *shader, QOpenGLShaderProgram *shaderProgram)
+void GraphicsContext::introspectShaderInterface(GLShader *shader)
{
- QScopedPointer<GraphicsHelperInterface> glHelper(resolveHighestOpenGLFunctions());
+ 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(glHelper->programUniformBlocks(shaderProgram->programId()));
+ shader->initializeUniformBlocks(m_glHelper->programUniformBlocks(shaderProgram->programId()));
if (m_glHelper->supportsFeature(GraphicsHelperInterface::ShaderStorageObject))
- shader->initializeShaderStorageBlocks(glHelper->programShaderStorageBlocks(shaderProgram->programId()));
+ shader->initializeShaderStorageBlocks(m_glHelper->programShaderStorageBlocks(shaderProgram->programId()));
}
// 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<Qt3DCore::QNodeId> 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<Qt3DCore::QNodeId> 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->requestCacheRebuild();
}
void GraphicsContext::activateDrawBuffers(const AttachmentPack &attachments)
@@ -1029,6 +1030,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/render/renderers/opengl/graphicshelpers/graphicscontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicscontext_p.h
index 8e4b390b6..8da1a420c 100644
--- a/src/render/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
@@ -60,18 +60,18 @@
#include <QMatrix4x4>
#include <QBitArray>
#include <QImage>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
#include <Qt3DRender/qclearbuffers.h>
#include <Qt3DRender/private/shader_p.h>
-#include <Qt3DRender/private/glbuffer_p.h>
#include <Qt3DRender/qattribute.h>
#include <Qt3DRender/qmemorybarrier.h>
#include <Qt3DRender/private/handle_types_p.h>
#include <Qt3DRender/private/qgraphicsapifilter_p.h>
-#include <Qt3DRender/private/shadercache_p.h>
#include <Qt3DRender/private/uniform_p.h>
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
#include <Qt3DRender/private/qblitframebuffer_p.h>
+#include <gl_handle_types_p.h>
+#include <glbuffer_p.h>
+#include <shaderparameterpack_p.h>
+#include <graphicshelperinterface_p.h>
#include <qmath.h>
QT_BEGIN_NAMESPACE
@@ -86,11 +86,16 @@ namespace Qt3DRender {
namespace Render {
-class GraphicsHelperInterface;
class RenderTarget;
class AttachmentPack;
class ShaderManager;
+namespace OpenGL {
+
+class GraphicsHelperInterface;
+class GLShader;
+class GLShaderManager;
+
typedef QPair<QString, int> NamedUniformLocation;
class Q_AUTOTEST_EXPORT GraphicsContext
@@ -99,9 +104,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);
@@ -110,10 +112,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; }
@@ -196,7 +203,6 @@ public:
QHash<QSurface *, GraphicsHelperInterface*> m_glHelpers;
GraphicsApiFilterData m_contextInfo;
- ShaderCache *m_shaderCache;
#ifdef QT_OPENGL_LIB
QScopedPointer<QOpenGLDebugLogger> m_debugLogger;
#endif
@@ -257,9 +263,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/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp
index 5f77dd376..3ae9ed932 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes2.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2.cpp
@@ -38,12 +38,13 @@
****************************************************************************/
#include "graphicshelperes2_p.h"
-#include <Qt3DRender/private/renderlogging_p.h>
#include <private/attachmentpack_p.h>
-#include <private/qgraphicsutils_p.h>
-#include <private/renderbuffer_p.h>
+#include <qgraphicsutils_p.h>
+#include <renderbuffer_p.h>
+#include <logging_p.h>
#include <QtGui/private/qopenglextensions_p.h>
+
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/render/renderers/opengl/graphicshelpers/graphicshelperes2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes2_p.h
index 882931ad9..9f820c72b 100644
--- a/src/render/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
@@ -51,7 +51,7 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
+#include <graphicshelperinterface_p.h>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
@@ -61,6 +61,7 @@ class QOpenGLExtensions;
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
class GraphicsHelperES2 : public GraphicsHelperInterface
{
@@ -174,9 +175,10 @@ protected:
QScopedPointer<QOpenGLExtensions> 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/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp
index 5e5d2e001..97a256b9c 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3.cpp
@@ -40,8 +40,8 @@
#include "graphicshelperes3_p.h"
#include <private/attachmentpack_p.h>
-#include <private/qgraphicsutils_p.h>
-#include <private/renderlogging_p.h>
+#include <qgraphicsutils_p.h>
+#include <logging_p.h>
#include <QOpenGLExtraFunctions>
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<ShaderUniform> 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<ShaderUniformBlock> GraphicsHelperES3::programUniformBlocks(GLuint progr
return blocks;
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp
index 9c424d962..692e0880b 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include "graphicshelperes3_1_p.h"
-#include <private/qgraphicsutils_p.h>
+#include <qgraphicsutils_p.h>
#include <QOpenGLExtraFunctions>
QT_BEGIN_NAMESPACE
@@ -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/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h
index 43d9ae7dd..408db0766 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_1_p.h
@@ -51,12 +51,13 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperes3_p.h>
+#include <graphicshelperes3_p.h>
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/render/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2.cpp
index 9d0988410..65108800b 100644
--- a/src/render/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/render/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_2_p.h
index 6b1a893d4..7a70f6269 100644
--- a/src/render/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
@@ -51,12 +51,13 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperes3_1_p.h>
+#include <graphicshelperes3_1_p.h>
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/render/renderers/opengl/graphicshelpers/graphicshelperes3_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperes3_p.h
index dc5cef10c..5c34a8abb 100644
--- a/src/render/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
@@ -52,12 +52,13 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperes2_p.h>
+#include <graphicshelperes2_p.h>
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/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp
index b9ee16acb..6989be743 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2.cpp
@@ -42,13 +42,14 @@
#include <QOpenGLFunctions_2_0>
#include <private/attachmentpack_p.h>
#include <QtOpenGLExtensions/QOpenGLExtensions>
-#include <private/qgraphicsutils_p.h>
-#include <Qt3DRender/private/renderlogging_p.h>
+#include <qgraphicsutils_p.h>
+#include <logging_p.h>
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/render/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl2_p.h
index eb85b8537..7eac312b8 100644
--- a/src/render/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
@@ -51,7 +51,7 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
+#include <graphicshelperinterface_p.h>
#ifndef QT_OPENGL_ES_2
@@ -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/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp
index f20491358..cb0a62224 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2.cpp
@@ -43,9 +43,9 @@
#include <QOpenGLFunctions_3_2_Core>
#include <QOpenGLFunctions_3_3_Core>
#include <QtOpenGLExtensions/qopenglextensions.h>
-#include <Qt3DRender/private/renderlogging_p.h>
#include <private/attachmentpack_p.h>
-#include <private/qgraphicsutils_p.h>
+#include <logging_p.h>
+#include <qgraphicsutils_p.h>
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<ShaderUniform> 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/render/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_2_p.h
index 914afc9ff..a7396dc87 100644
--- a/src/render/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
@@ -51,7 +51,7 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
+#include <graphicshelperinterface_p.h>
#include <QtCore/qscopedpointer.h>
#ifndef QT_OPENGL_ES_2
@@ -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<QOpenGLExtension_ARB_tessellation_shader> 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/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp
index ddffb38e2..f5a61aa4b 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3.cpp
@@ -42,9 +42,9 @@
#ifndef QT_OPENGL_ES_2
#include <QOpenGLFunctions_3_3_Core>
#include <QtOpenGLExtensions/qopenglextensions.h>
-#include <Qt3DRender/private/renderlogging_p.h>
#include <private/attachmentpack_p.h>
-#include <private/qgraphicsutils_p.h>
+#include <logging_p.h>
+#include <qgraphicsutils_p.h>
# ifndef QT_OPENGL_3_2
# define GL_PATCH_VERTICES 36466
@@ -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<ShaderUniform> 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/render/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl3_3_p.h
index 4dbf6fe7b..3b667420c 100644
--- a/src/render/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
@@ -51,7 +51,7 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
+#include <graphicshelperinterface_p.h>
#include <QtCore/qscopedpointer.h>
#ifndef QT_OPENGL_ES_2
@@ -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<QOpenGLExtension_ARB_tessellation_shader> 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/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp
index 60caed273..96e055870 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4.cpp
@@ -42,9 +42,9 @@
#ifndef QT_OPENGL_ES_2
#include <QOpenGLFunctions_4_3_Core>
#include <QtOpenGLExtensions/qopenglextensions.h>
-#include <Qt3DRender/private/renderlogging_p.h>
#include <private/attachmentpack_p.h>
-#include <private/qgraphicsutils_p.h>
+#include <qgraphicsutils_p.h>
+#include <logging_p.h>
# 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<ShaderUniform> 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/render/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpergl4_p.h
index d3ce0d079..1fa390806 100644
--- a/src/render/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
@@ -51,7 +51,7 @@
// We mean it.
//
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
+#include <graphicshelperinterface_p.h>
#include <QtCore/qscopedpointer.h>
#ifndef QT_OPENGL_ES_2
@@ -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/render/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h b/src/plugins/renderers/opengl/graphicshelpers/graphicshelperinterface_p.h
index 21146c32b..bbbf05ee0 100644
--- a/src/render/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
@@ -54,7 +54,7 @@
#include <QOpenGLFunctions>
#include <QOpenGLTexture>
#include <QVector>
-#include <Qt3DRender/private/shadervariables_p.h>
+#include <shadervariables_p.h>
#include <Qt3DRender/private/uniform_p.h>
#include <Qt3DRender/qmemorybarrier.h>
@@ -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/render/renderers/opengl/graphicshelpers/graphicshelpers.pri b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri
index f2f7274d7..3cfa445ce 100644
--- a/src/render/renderers/opengl/graphicshelpers/graphicshelpers.pri
+++ b/src/plugins/renderers/opengl/graphicshelpers/graphicshelpers.pri
@@ -3,7 +3,6 @@
INCLUDEPATH += $$PWD
HEADERS += \
- $$PWD/glfence_p.h \
$$PWD/graphicscontext_p.h \
$$PWD/graphicshelperinterface_p.h \
$$PWD/graphicshelperes2_p.h \
@@ -16,7 +15,8 @@ HEADERS += \
$$PWD/graphicshelpergl3_2_p.h \
$$PWD/imagesubmissioncontext_p.h \
$$PWD/submissioncontext_p.h \
- $$PWD/texturesubmissioncontext_p.h
+ $$PWD/texturesubmissioncontext_p.h \
+ $$PWD/qgraphicsutils_p.h
SOURCES += \
$$PWD/graphicscontext.cpp \
diff --git a/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp
index ca600f994..c2316d81a 100644
--- a/src/render/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext.cpp
@@ -38,10 +38,11 @@
****************************************************************************/
#include "imagesubmissioncontext_p.h"
-#include <Qt3DRender/private/graphicscontext_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
#include <Qt3DRender/private/shaderimage_p.h>
#include <Qt3DRender/qshaderimage.h>
+#include <graphicscontext_p.h>
+#include <gltexture_p.h>
+#include <logging_p.h>
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/render/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/imagesubmissioncontext_p.h
index 6d39f469b..52a0152f8 100644
--- a/src/render/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/render/backend/qgraphicsutils_p.h b/src/plugins/renderers/opengl/graphicshelpers/qgraphicsutils_p.h
index 40ff99f0e..a2a995811 100644
--- a/src/render/backend/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
@@ -52,7 +52,6 @@
//
#include <Qt3DRender/qt3drender_global.h>
-#include <Qt3DRender/private/shadervariables_p.h>
#include <QMatrix2x2>
#include <QMatrix3x3>
#include <QMatrix4x4>
@@ -60,6 +59,7 @@
#include <QVector2D>
#include <QVarLengthArray>
#include <QColor>
+#include <shadervariables_p.h>
QT_BEGIN_NAMESPACE
@@ -67,6 +67,8 @@ namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
namespace {
const int QMatrix2x2Type = qMetaTypeId<QMatrix2x2>();
@@ -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/render/renderers/opengl/graphicshelpers/submissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp
index 3166a7947..25a7d0036 100644
--- a/src/render/renderers/opengl/graphicshelpers/submissioncontext.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext.cpp
@@ -45,23 +45,25 @@
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/shader_p.h>
#include <Qt3DRender/private/material_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
#include <Qt3DRender/private/buffer_p.h>
#include <Qt3DRender/private/attribute_p.h>
-#include <Qt3DRender/private/rendercommand_p.h>
#include <Qt3DRender/private/renderstates_p.h>
#include <Qt3DRender/private/renderstateset_p.h>
#include <Qt3DRender/private/rendertarget_p.h>
-#include <Qt3DRender/private/graphicshelperinterface_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/buffermanager_p.h>
#include <Qt3DRender/private/managers_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
#include <Qt3DRender/private/qbuffer_p.h>
-#include <Qt3DRender/private/renderbuffer_p.h>
#include <Qt3DRender/private/stringtoint_p.h>
+#include <gltexture_p.h>
+#include <rendercommand_p.h>
+#include <graphicshelperinterface_p.h>
+#include <renderer_p.h>
+#include <glresourcemanagers_p.h>
+#include <renderbuffer_p.h>
+#include <glshader_p.h>
+#include <openglvertexarrayobject_p.h>
#include <QOpenGLShaderProgram>
#if !defined(QT_OPENGL_ES_2)
@@ -69,13 +71,13 @@
#include <QOpenGLFunctions_3_2_Core>
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLFunctions_4_3_Core>
-#include <Qt3DRender/private/graphicshelpergl2_p.h>
-#include <Qt3DRender/private/graphicshelpergl3_2_p.h>
-#include <Qt3DRender/private/graphicshelpergl3_3_p.h>
-#include <Qt3DRender/private/graphicshelpergl4_p.h>
+#include <graphicshelpergl2_p.h>
+#include <graphicshelpergl3_2_p.h>
+#include <graphicshelpergl3_3_p.h>
+#include <graphicshelpergl4_p.h>
#endif
-#include <Qt3DRender/private/graphicshelperes2_p.h>
-#include <Qt3DRender/private/graphicshelperes3_p.h>
+#include <graphicshelperes2_p.h>
+#include <graphicshelperes3_p.h>
#include <private/qdebug_p.h>
#include <QSurface>
@@ -97,6 +99,7 @@ QT_BEGIN_NAMESPACE
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
static QHash<unsigned int, SubmissionContext*> static_contexts;
@@ -364,7 +367,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)
@@ -461,17 +463,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;
}
@@ -532,7 +526,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_) {
@@ -540,9 +534,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;
}
}
@@ -689,8 +683,8 @@ QImage SubmissionContext::readFramebuffer(const QRect &rect)
GLint samples = 0;
m_gl->functions()->glGetIntegerv(GL_SAMPLES, &samples);
if (samples > 0 && !m_glHelper->supportsFeature(GraphicsHelperInterface::BlitFramebuffer)) {
- qWarning () << Q_FUNC_INFO << "Unable to capture multisampled framebuffer; "
- "Required feature BlitFramebuffer is missing.";
+ qCWarning(Backend) << Q_FUNC_INFO << "Unable to capture multisampled framebuffer; "
+ "Required feature BlitFramebuffer is missing.";
return img;
}
@@ -713,7 +707,7 @@ QImage SubmissionContext::readFramebuffer(const QRect &rect)
if (status != GL_FRAMEBUFFER_COMPLETE) {
gl->glDeleteRenderbuffers(1, &rb);
gl->glDeleteFramebuffers(1, &fbo);
- qWarning () << Q_FUNC_INFO << "Copy-framebuffer not complete: " << status;
+ qCWarning(Backend) << Q_FUNC_INFO << "Copy-framebuffer not complete: " << status;
return img;
}
@@ -767,7 +761,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
@@ -782,27 +775,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);
- qWarning() << "No shader program found for DNA";
- m_activeShaderDNA = 0;
+ qWarning() << "No shader program found";
return false;
}
}
@@ -818,7 +809,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);
@@ -859,7 +850,7 @@ void SubmissionContext::activateDrawBuffers(const AttachmentPack &attachments)
}
}
} else {
- qWarning() << "FBO incomplete";
+ qCWarning(Backend) << "FBO incomplete";
}
}
@@ -1161,8 +1152,6 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
// 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();
@@ -1173,9 +1162,9 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
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[namedTex.glslNameId];
+ UniformValue &texUniform = uniformValues.value(namedTex.glslNameId);
if (texUniform.valueType() == UniformValue::TextureValue) {
const int texUnit = m_textureContext.activateTexture(TextureSubmissionContext::TextureScopeMaterial, m_gl, t);
texUniform.data<int>()[namedTex.uniformArrayIndex] = texUnit;
@@ -1183,7 +1172,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
if (namedTex.glslNameId != irradianceId &&
namedTex.glslNameId != specularId) {
// Only return false if we are not dealing with env light textures
- qWarning() << "Unable to find suitable Texture Unit";
+ qCWarning(Backend) << "Unable to find suitable Texture Unit";
return false;
}
}
@@ -1198,19 +1187,19 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
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) {
- qWarning() << "Shader Image referencing invalid texture";
+ qCWarning(Backend) << "Shader Image referencing invalid texture";
continue;
} else {
- UniformValue &imgUniform = uniformValues[namedTex.glslNameId];
+ UniformValue &imgUniform = uniformValues.value(namedTex.glslNameId);
if (imgUniform.valueType() == UniformValue::ShaderImageValue) {
const int imgUnit = m_imageContext.activateImage(img, t);
imgUniform.data<int>()[namedTex.uniformArrayIndex] = imgUnit;
if (imgUnit == -1) {
- qWarning() << "Unable to bind Image to Texture";
+ qCWarning(Backend) << "Unable to bind Image to Texture";
return false;
}
}
@@ -1228,13 +1217,12 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
const QVector<BlockToSSBO> 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);
@@ -1248,7 +1236,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
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
@@ -1264,7 +1252,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
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[uniform.m_nameId];
+ const UniformValue &v = values.value(uniform.m_nameId);
// skip invalid textures/images
if ((v.valueType() == UniformValue::TextureValue ||
@@ -1281,7 +1269,7 @@ bool SubmissionContext::setParameters(ShaderParameterPack &parameterPack)
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);
@@ -1320,7 +1308,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());
@@ -1339,6 +1327,7 @@ void SubmissionContext::specifyAttribute(const Attribute *attribute,
Q_UNREACHABLE();
}
+ Q_ASSERT(!glBufferHandle.isNull());
VAOVertexAttribute attr;
attr.bufferHandle = glBufferHandle;
attr.attributeType = attributeType;
@@ -1362,28 +1351,28 @@ 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";
// 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<Qt3DCore::QNodeId, HGLBuffer>::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<Qt3DCore::QNodeId, HGLBuffer>::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();
}
@@ -1392,13 +1381,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,25 +1399,22 @@ 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));
- return m_renderer->nodeManagers()->glBufferManager()->data(m_renderBufferHash.value(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::Type type)
+HGLBuffer SubmissionContext::createGLBufferFor(Buffer *buffer)
{
- GLBuffer *b = m_renderer->nodeManagers()->glBufferManager()->getOrCreateResource(buffer->peerId());
+ GLBuffer *b = m_renderer->glResourceManagers()->glBufferManager()->getOrCreateResource(buffer->peerId());
// b.setUsagePattern(static_cast<QOpenGLBuffer::UsagePattern>(buffer->usage()));
Q_ASSERT(b);
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";
+ qCWarning(Io) << Q_FUNC_INFO << "buffer creation 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)
@@ -1447,7 +1433,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)
@@ -1490,13 +1476,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;
@@ -1587,6 +1573,7 @@ void SubmissionContext::blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId,
}
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender of namespace
diff --git a/src/render/renderers/opengl/graphicshelpers/submissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/submissioncontext_p.h
index a8700dd3a..b663e47ec 100644
--- a/src/render/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
@@ -53,15 +53,14 @@
//
-#include <Qt3DRender/private/graphicscontext_p.h>
-#include <Qt3DRender/private/texturesubmissioncontext_p.h>
-#include <Qt3DRender/private/imagesubmissioncontext_p.h>
+#include <glbuffer_p.h>
+#include <glfence_p.h>
+#include <graphicscontext_p.h>
+#include <texturesubmissioncontext_p.h>
+#include <imagesubmissioncontext_p.h>
#include <Qt3DRender/qclearbuffers.h>
-#include <Qt3DRender/private/glbuffer_p.h>
#include <Qt3DRender/qattribute.h>
#include <Qt3DRender/private/handle_types_p.h>
-#include <Qt3DRender/private/shadercache_p.h>
-#include <Qt3DRender/private/glfence_p.h>
QT_BEGIN_NAMESPACE
@@ -71,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<QString, int> NamedUniformLocation;
@@ -105,7 +107,7 @@ public:
QRectF viewport() const { return m_viewport; }
// Shaders
- bool activateShader(ProgramDNA shaderDNA);
+ bool activateShader(GLShader *shader);
QOpenGLShaderProgram *activeShader() const { return m_activeShader; }
// FBO
@@ -131,7 +133,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 &parameterPack);
@@ -172,7 +174,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);
@@ -183,7 +185,6 @@ private:
QSize m_surfaceSize;
QOpenGLShaderProgram *m_activeShader;
- ProgramDNA m_activeShaderDNA;
QHash<Qt3DCore::QNodeId, HGLBuffer> m_renderBufferHash;
QHash<Qt3DCore::QNodeId, GLuint> m_renderTargets;
@@ -228,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/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp
index 67d0f9976..4577d3d10 100644
--- a/src/render/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp
+++ b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext.cpp
@@ -39,13 +39,15 @@
#include "texturesubmissioncontext_p.h"
-#include <Qt3DRender/private/graphicscontext_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
+#include <graphicscontext_p.h>
+#include <gltexture_p.h>
+#include <logging_p.h>
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/render/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h b/src/plugins/renderers/opengl/graphicshelpers/texturesubmissioncontext_p.h
index 3c84fe558..d80f6b9e3 100644
--- a/src/render/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<ActiveTexture> 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/render/renderers/opengl/io/glbuffer.cpp b/src/plugins/renderers/opengl/io/glbuffer.cpp
index f1b860f03..27f005f01 100644
--- a/src/render/renderers/opengl/io/glbuffer.cpp
+++ b/src/plugins/renderers/opengl/io/glbuffer.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include "glbuffer_p.h"
-#include <private/graphicscontext_p.h>
+#include <graphicscontext_p.h>
#if !defined(GL_UNIFORM_BUFFER)
#define GL_UNIFORM_BUFFER 0x8A11
@@ -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/render/renderers/opengl/io/glbuffer_p.h b/src/plugins/renderers/opengl/io/glbuffer_p.h
index 731634b6b..6a2daa287 100644
--- a/src/render/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/render/renderers/opengl/io/io.pri b/src/plugins/renderers/opengl/io/io.pri
index 462978c4d..462978c4d 100644
--- a/src/render/renderers/opengl/io/io.pri
+++ b/src/plugins/renderers/opengl/io/io.pri
diff --git a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp
index 342fd3dad..52fd99f52 100644
--- a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob.cpp
+++ b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob.cpp
@@ -40,20 +40,21 @@
#include "filtercompatibletechniquejob_p.h"
#include <Qt3DRender/private/techniquemanager_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/job_common_p.h>
-#include <Qt3DRender/private/submissioncontext_p.h>
+#include <renderer_p.h>
+#include <submissioncontext_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
FilterCompatibleTechniqueJob::FilterCompatibleTechniqueJob()
: m_manager(nullptr)
, m_renderer(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::FilterCompatibleTechniques, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::FilterCompatibleTechniques, 0)
}
void FilterCompatibleTechniqueJob::setManager(TechniqueManager *manager)
@@ -89,6 +90,7 @@ void FilterCompatibleTechniqueJob::run()
}
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/jobs/filtercompatibletechniquejob_p.h b/src/plugins/renderers/opengl/jobs/filtercompatibletechniquejob_p.h
index 27b3d4ed2..7191e2933 100644
--- a/src/render/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,9 +62,12 @@ namespace Qt3DRender {
namespace Render {
class TechniqueManager;
+
+namespace OpenGL {
+
class Renderer;
-class Q_3DRENDERSHARED_PRIVATE_EXPORT FilterCompatibleTechniqueJob : public Qt3DCore::QAspectJob
+class Q_AUTOTEST_EXPORT FilterCompatibleTechniqueJob : public Qt3DCore::QAspectJob
{
public:
FilterCompatibleTechniqueJob();
@@ -84,9 +87,10 @@ private:
typedef QSharedPointer<FilterCompatibleTechniqueJob> 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/render/renderers/opengl/jobs/jobs.pri b/src/plugins/renderers/opengl/jobs/jobs.pri
index 021cd3242..d80b8bfd9 100644
--- a/src/render/renderers/opengl/jobs/jobs.pri
+++ b/src/plugins/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/materialparametergathererjob.cpp b/src/plugins/renderers/opengl/jobs/materialparametergathererjob.cpp
index 5e56e817f..1f51ceba3 100644
--- a/src/render/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;
@@ -63,7 +65,7 @@ MaterialParameterGathererJob::MaterialParameterGathererJob()
, m_techniqueFilter(nullptr)
, m_renderPassFilter(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::MaterialParameterGathering, materialParameterGathererCounter++);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::MaterialParameterGathering, materialParameterGathererCounter++)
}
// TechniqueFilter / RenderPassFilter
@@ -124,6 +126,8 @@ void MaterialParameterGathererJob::run()
}
}
+} // OpenGL
+
} // Render
} // Qt3DRender
diff --git a/src/render/renderers/opengl/jobs/materialparametergathererjob_p.h b/src/plugins/renderers/opengl/jobs/materialparametergathererjob_p.h
index 6ba060841..139267d9a 100644
--- a/src/render/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
@@ -54,8 +54,8 @@
#include <Qt3DCore/qaspectjob.h>
#include <Qt3DCore/qnodeid.h>
#include <Qt3DRender/private/handle_types_p.h>
-#include <Qt3DRender/private/renderviewjobutils_p.h>
#include <Qt3DRender/private/qt3drender_global_p.h>
+#include <renderviewjobutils_p.h>
QT_BEGIN_NAMESPACE
@@ -66,11 +66,13 @@ namespace Render {
class NodeManagers;
class TechniqueFilter;
class RenderPassFilter;
+
+namespace OpenGL {
class Renderer;
// TO be executed for each FrameGraph branch with a given RenderPassFilter/TechniqueFilter
-class Q_3DRENDERSHARED_PRIVATE_EXPORT MaterialParameterGathererJob : public Qt3DCore::QAspectJob
+class Q_AUTOTEST_EXPORT MaterialParameterGathererJob : public Qt3DCore::QAspectJob
{
public:
MaterialParameterGathererJob();
@@ -98,10 +100,12 @@ private:
typedef QSharedPointer<MaterialParameterGathererJob> MaterialParameterGathererJobPtr;
+} // OpenGL
+
} // Render
} // Qt3DRender
QT_END_NAMESPACE
-#endif // QT3DRENDER_RENDER_MATERIALPARAMETERGATHERERJOB_P_H
+#endif // QT3DRENDER_RENDER_OPENGL_MATERIALPARAMETERGATHERERJOB_P_H
diff --git a/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp
index 15154641e..468ab9342 100644
--- a/src/render/renderers/opengl/jobs/renderviewbuilderjob.cpp
+++ b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob.cpp
@@ -37,10 +37,10 @@
**
****************************************************************************/
-#include "renderviewbuilderjob_p.h"
+#include "renderviewcommandupdaterjob_p.h"
#include <Qt3DRender/private/job_common_p.h>
-#include <Qt3DRender/private/renderer_p.h>
-#include <Qt3DRender/private/renderview_p.h>
+#include <renderer_p.h>
+#include <renderview_p.h>
QT_BEGIN_NAMESPACE
@@ -48,29 +48,37 @@ namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
namespace {
int renderViewInstanceCounter = 0;
} // anonymous
-RenderViewBuilderJob::RenderViewBuilderJob()
- : Qt3DCore::QAspectJob(),
- m_renderView(nullptr)
+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::RenderViewBuilder, renderViewInstanceCounter++);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderCommandUpdater, renderViewInstanceCounter++);
}
-void RenderViewBuilderJob::run()
+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_renderView->isCompute())
- m_commands = m_renderView->buildDrawRenderCommands(m_renderables);
- else
- m_commands = m_renderView->buildComputeRenderCommands(m_renderables);
+ if (m_count == 0)
+ return;
+ // Update Render Commands (Uniform Change, Depth Change)
+ m_renderView->updateRenderCommand(m_renderables, m_offset, m_count);
}
}
+} // OpenGL
+
} // Render
} // Qt3DRender
diff --git a/src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h
index c38f788b0..13e19daf7 100644
--- a/src/render/renderers/opengl/jobs/renderviewbuilderjob_p.h
+++ b/src/plugins/renderers/opengl/jobs/renderviewbuilderjob_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 Paul Lemire
+** 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.
@@ -37,8 +37,8 @@
**
****************************************************************************/
-#ifndef QT3DRENDER_RENDER_RENDERVIEWBUILDERJOB_P_H
-#define QT3DRENDER_RENDER_RENDERVIEWBUILDERJOB_P_H
+#ifndef QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H
+#define QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDBUILDERJOB_P_H
//
// W A R N I N G
@@ -53,6 +53,7 @@
#include <Qt3DCore/qaspectjob.h>
#include <Qt3DRender/private/handle_types_p.h>
+#include <rendercommand_p.h>
QT_BEGIN_NAMESPACE
@@ -60,32 +61,37 @@ namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
class RenderView;
-class Renderer;
-class RenderCommand;
-class Q_AUTOTEST_EXPORT RenderViewBuilderJob : public Qt3DCore::QAspectJob
+class Q_AUTOTEST_EXPORT RenderViewCommandBuilderJob : public Qt3DCore::QAspectJob
{
public:
- RenderViewBuilderJob();
+ RenderViewCommandBuilderJob();
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<Entity *> &renderables) Q_DECL_NOTHROW { m_renderables = renderables; }
- QVector<RenderCommand *> &commands() Q_DECL_NOTHROW { return m_commands; }
+ inline void setEntities(const QVector<Entity *> &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;
- Renderer *m_renderer;
- int m_index;
- QVector<Entity *> m_renderables;
- QVector<RenderCommand *> m_commands;
+ QVector<Entity *> m_entities;
+ EntityRenderCommandData m_commandData;
};
-typedef QSharedPointer<RenderViewBuilderJob> RenderViewBuilderJobPtr;
+typedef QSharedPointer<RenderViewCommandBuilderJob> RenderViewCommandBuilderJobPtr;
+
+} // OpenGL
} // Render
@@ -93,4 +99,4 @@ typedef QSharedPointer<RenderViewBuilderJob> RenderViewBuilderJobPtr;
QT_END_NAMESPACE
-#endif // QT3DRENDER_RENDER_RENDERVIEWBUILDERJOB_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
new file mode 100644
index 000000000..d8a33b693
--- /dev/null
+++ b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob.cpp
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** 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 <Qt3DRender/private/job_common_p.h>
+#include <renderview_p.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+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);
+ }
+}
+
+} // OpenGL
+
+} // 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..e9f8bb10a
--- /dev/null
+++ b/src/plugins/renderers/opengl/jobs/renderviewcommandbuilderjob_p.h
@@ -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: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_RENDERVIEWCOMMANDBUILDERJOB_P_H
+#define QT3DRENDER_RENDER_OPENGL_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 <Qt3DCore/qaspectjob.h>
+#include <Qt3DRender/private/handle_types_p.h>
+#include <rendercommand_p.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+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<Entity *> &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<Entity *> m_entities;
+ EntityRenderCommandData m_commandData;
+};
+
+typedef QSharedPointer<RenderViewCommandBuilderJob> RenderViewCommandBuilderJobPtr;
+
+} // OpenGL
+
+} // Render
+
+} // Qt3DRender
+
+QT_END_NAMESPACE
+
+#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
new file mode 100644
index 000000000..79a115525
--- /dev/null
+++ b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob.cpp
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** 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 <Qt3DRender/private/job_common_p.h>
+#include <renderer_p.h>
+#include <renderview_p.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+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);
+ }
+}
+
+} // OpenGL
+
+} // 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..2fe5749ad
--- /dev/null
+++ b/src/plugins/renderers/opengl/jobs/renderviewcommandupdaterjob_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_OPENGL_RENDERVIEWCOMMANDUPDATEJOB_P_H
+#define QT3DRENDER_RENDER_OPENGL_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 <Qt3DCore/qaspectjob.h>
+#include <Qt3DRender/private/handle_types_p.h>
+#include <rendercommand_p.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+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<RenderCommand> &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<RenderCommand> m_commands;
+};
+
+typedef QSharedPointer<RenderViewCommandUpdaterJob> RenderViewCommandUpdaterJobPtr;
+
+} // OpenGL
+
+} // Render
+
+} // Qt3DRender
+
+QT_END_NAMESPACE
+
+#endif // QT3DRENDER_RENDER_OPENGL_RENDERVIEWCOMMANDUPDATEJOB_P_H
diff --git a/src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp
index 982c51216..e84ecc899 100644
--- a/src/render/renderers/opengl/jobs/renderviewinitializerjob.cpp
+++ b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob.cpp
@@ -40,9 +40,9 @@
#include "renderviewinitializerjob_p.h"
-#include <Qt3DRender/private/renderview_p.h>
-#include <Qt3DRender/private/renderer_p.h>
-#include <Qt3DRender/private/renderviewjobutils_p.h>
+#include <renderview_p.h>
+#include <renderer_p.h>
+#include <renderviewjobutils_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/job_common_p.h>
@@ -52,6 +52,7 @@ QT_BEGIN_NAMESPACE
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
namespace {
// only accessed in ctor and dtor of RenderViewJob
@@ -65,7 +66,7 @@ RenderViewInitializerJob::RenderViewInitializerJob()
, m_index(0)
, m_renderView(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderView, renderViewInstanceCounter++);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::RenderView, renderViewInstanceCounter++)
}
RenderViewInitializerJob::~RenderViewInitializerJob()
@@ -97,6 +98,7 @@ void RenderViewInitializerJob::run()
#endif
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/jobs/renderviewinitializerjob_p.h b/src/plugins/renderers/opengl/jobs/renderviewinitializerjob_p.h
index 2da43a7fd..fa69719cc 100644
--- a/src/render/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
@@ -61,8 +61,11 @@ namespace Qt3DRender {
namespace Render {
-class Renderer;
class FrameGraphNode;
+
+namespace OpenGL {
+
+class Renderer;
class RenderView;
class Q_AUTOTEST_EXPORT RenderViewInitializerJob : public Qt3DCore::QAspectJob
@@ -98,9 +101,10 @@ private:
typedef QSharedPointer<RenderViewInitializerJob> 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/render/renderers/opengl/jobs/renderviewjobutils.cpp b/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp
index cc211ba68..d4835054b 100644
--- a/src/render/renderers/opengl/jobs/renderviewjobutils.cpp
+++ b/src/plugins/renderers/opengl/jobs/renderviewjobutils.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include "renderviewjobutils_p.h"
-#include "renderlogging_p.h"
+#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/qgraphicsapifilter.h>
#include <Qt3DRender/private/sphere_p.h>
@@ -50,13 +50,10 @@
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/effect_p.h>
#include <Qt3DRender/private/renderpassfilternode_p.h>
-#include <Qt3DRender/private/renderstateset_p.h>
#include <Qt3DRender/private/rendertargetselectornode_p.h>
-#include <Qt3DRender/private/renderview_p.h>
#include <Qt3DRender/private/sortpolicy_p.h>
#include <Qt3DRender/private/techniquefilternode_p.h>
#include <Qt3DRender/private/viewportnode_p.h>
-#include <Qt3DRender/private/shadervariables_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/shaderdata_p.h>
#include <Qt3DRender/private/statesetnode_p.h>
@@ -69,6 +66,9 @@
#include <Qt3DRender/private/memorybarrier_p.h>
#include <Qt3DRender/private/blitframebuffer_p.h>
#include <Qt3DRender/private/waitfence_p.h>
+#include <Qt3DRender/private/renderstateset_p.h>
+#include <renderview_p.h>
+#include <shadervariables_p.h>
QT_BEGIN_NAMESPACE
@@ -76,6 +76,7 @@ using namespace Qt3DCore;
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
/*!
\internal
@@ -232,9 +233,15 @@ void setRenderViewConfigFromFrameGraphLeafNode(RenderView *rv, const FrameGraphN
= static_cast<const Render::RenderSurfaceSelector *>(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<Render::RenderCapture *>(
static_cast<const Render::RenderCapture *>(node));
@@ -487,7 +494,12 @@ void UniformBlockValueBuilder::buildActiveUniformNameValueMapHelper(ShaderData *
}
}
} else { // Array of scalar/vec qmlPropertyName[0]
- QString varName = blockName + QLatin1String(".") + qmlPropertyName + QLatin1String("[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);
@@ -505,7 +517,11 @@ void UniformBlockValueBuilder::buildActiveUniformNameValueMapHelper(ShaderData *
activeUniformNamesToValue.insert(varId, value);
}
} else { // Scalar / Vec
- QString varName = blockName + QLatin1Char('.') + qmlPropertyName;
+ 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";
@@ -525,11 +541,15 @@ void UniformBlockValueBuilder::buildActiveUniformNameValueMapStructHelper(Shader
const auto end = properties.end();
while (it != end) {
- const auto prefix = qmlPropertyName.isEmpty() ? QLatin1String("") : QLatin1String(".");
- buildActiveUniformNameValueMapHelper(rShaderData,
- blockName + prefix + qmlPropertyName,
- it.key(),
- it.value().value);
+ 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;
}
}
@@ -549,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/render/renderers/opengl/jobs/renderviewjobutils_p.h b/src/plugins/renderers/opengl/jobs/renderviewjobutils_p.h
index 059f6a0d5..7b5ba2bfd 100644
--- a/src/render/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
@@ -59,6 +59,7 @@
#include <Qt3DRender/private/uniform_p.h>
#include <Qt3DRender/private/handle_types_p.h>
#include <Qt3DRender/private/aligned_malloc_p.h>
+#include <shadervariables_p.h>
QT_BEGIN_NAMESPACE
@@ -71,19 +72,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);
@@ -122,7 +125,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<Qt3DCore::QNodeId, QVector<RenderPassParameterData>>;
@@ -175,9 +178,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
new file mode 100644
index 000000000..a6cd9faf7
--- /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 <Qt3DRender/private/qrendererplugin_p.h>
+#include <renderer_p.h>
+
+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::OpenGL::Renderer(renderMode);
+ }
+};
+
+QT_END_NAMESPACE
+
+#include "main.moc"
diff --git a/src/render/renderers/opengl/textures/gltexturemanager_p.h b/src/plugins/renderers/opengl/managers/gl_handle_types_p.h
index 335af136c..98af4d3b8 100644
--- a/src/render/renderers/opengl/textures/gltexturemanager_p.h
+++ b/src/plugins/renderers/opengl/managers/gl_handle_types_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB).
+** 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.
@@ -37,8 +37,8 @@
**
****************************************************************************/
-#ifndef QT3DRENDER_RENDER_GLTEXTUREMANAGER_H
-#define QT3DRENDER_RENDER_GLTEXTUREMANAGER_H
+#ifndef QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H
+#define QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H
//
// W A R N I N G
@@ -51,28 +51,30 @@
// We mean it.
//
-#include <Qt3DCore/private/qresourcemanager_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
+#include <Qt3DCore/private/qhandle_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
+
namespace Render {
-class Q_AUTOTEST_EXPORT GLTextureManager : public Qt3DCore::QResourceManager<
- GLTexture,
- Qt3DCore::QNodeId,
- Qt3DCore::NonLockingPolicy>
-{
-public:
- QHash<GLTexture *, Qt3DCore::QNodeId> texNodeIdForGLTexture;
-};
+namespace OpenGL {
+
+class GLBuffer;
+class GLTexture;
+class OpenGLVertexArrayObject;
+
+typedef Qt3DCore::QHandle<GLBuffer> HGLBuffer;
+typedef Qt3DCore::QHandle<OpenGLVertexArrayObject> HVao;
+typedef Qt3DCore::QHandle<GLTexture> HGLTexture;
+
+} // namespace OpenGL
} // namespace Render
-} // namespace Qt3DRender
-Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::GLTexture, Q_REQUIRES_CLEANUP)
+} // namespace Qt3DRender
QT_END_NAMESPACE
-#endif // QT3DRENDER_RENDER_GLTEXTUREMANAGER_H
+#endif // QT3DRENDER_RENDER_OPENGL_HANDLE_TYPES_P_H
diff --git a/src/render/renderers/opengl/renderer/rendercommand.cpp b/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp
index e60b17668..e8fd893ee 100644
--- a/src/render/renderers/opengl/renderer/rendercommand.cpp
+++ b/src/plugins/renderers/opengl/managers/glresourcemanagers.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
+** 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.
@@ -37,40 +37,38 @@
**
****************************************************************************/
-#include "rendercommand_p.h"
+#include "glresourcemanagers_p.h"
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
+
namespace Render {
-RenderCommand::RenderCommand()
- : 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)
+namespace OpenGL {
+
+GLResourceManagers::GLResourceManagers()
+ : m_glBufferManager(new GLBufferManager())
+ , m_glShaderManager(new GLShaderManager())
+ , m_glTextureManager(new GLTextureManager())
+ , m_glFenceManager(new GLFenceManager())
+ , m_vaoManager(new VAOManager())
{
- m_workGroups[0] = 0;
- m_workGroups[1] = 0;
- m_workGroups[2] = 0;
}
-} // namespace Render
-} // namespace Qt3DRender
+GLResourceManagers::~GLResourceManagers()
+{
+ delete m_vaoManager;
+ delete m_glFenceManager;
+ delete m_glTextureManager;
+ delete m_glShaderManager;
+ delete m_glBufferManager;
+}
+
+} // OpenGL
+
+} // 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..9472bc33f
--- /dev/null
+++ b/src/plugins/renderers/opengl/managers/glresourcemanagers_p.h
@@ -0,0 +1,139 @@
+/****************************************************************************
+**
+** 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_OPENGL_GLRESOURCEMANAGERS_P_H
+#define QT3DRENDER_RENDER_OPENGL_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 <Qt3DRender/private/qt3drender_global_p.h>
+#include <Qt3DCore/private/qresourcemanager_p.h>
+#include <gltexture_p.h>
+#include <glbuffer_p.h>
+#include <glfence_p.h>
+#include <openglvertexarrayobject_p.h>
+#include <glshader_p.h>
+#include <Qt3DRender/private/apishadermanager_p.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+class Q_AUTOTEST_EXPORT GLFenceManager : public QHash<Qt3DCore::QNodeId, GLFence>
+{
+};
+
+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<GLTexture *, Qt3DCore::QNodeId> texNodeIdForGLTexture;
+};
+
+class Q_AUTOTEST_EXPORT GLShaderManager : public APIShaderManager<GLShader>
+{
+public:
+ explicit GLShaderManager()
+ : APIShaderManager<GLShader>()
+ {}
+};
+
+
+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;
+};
+
+} // OpenGL
+
+} // Render
+
+} // Qt3DRender
+
+Q_DECLARE_RESOURCE_INFO(Qt3DRender::Render::OpenGL::OpenGLVertexArrayObject, Q_REQUIRES_CLEANUP)
+
+QT_END_NAMESPACE
+
+#endif // QT3DRENDER_RENDER_OPENGL_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..657eb8556
--- /dev/null
+++ b/src/plugins/renderers/opengl/opengl.pri
@@ -0,0 +1,41 @@
+QT += core-private gui-private 3dcore 3dcore-private 3drender 3drender-private opengl-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/render/backend/commandexecuter.cpp b/src/plugins/renderers/opengl/renderer/commandexecuter.cpp
index 8bccb1437..03d5d5a7f 100644
--- a/src/render/backend/commandexecuter.cpp
+++ b/src/plugins/renderers/opengl/renderer/commandexecuter.cpp
@@ -36,19 +36,19 @@
#include "commandexecuter_p.h"
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DCore/private/qabstractaspect_p.h>
#include <Qt3DCore/qbackendnode.h>
-#include <Qt3DRender/private/graphicscontext_p.h>
-#include <Qt3DRender/private/renderview_p.h>
-#include <Qt3DRender/private/rendercommand_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/geometryrenderermanager_p.h>
#include <Qt3DRender/private/stringtoint_p.h>
-#include <Qt3DRender/private/submissioncontext_p.h>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
+#include <graphicscontext_p.h>
+#include <renderview_p.h>
+#include <rendercommand_p.h>
+#include <renderer_p.h>
+#include <submissioncontext_p.h>
QT_BEGIN_NAMESPACE
@@ -242,16 +242,16 @@ 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 (auto it = uniforms.cbegin(), end = uniforms.cend(); it != end; ++it) {
+ for (int i = 0, m = uniforms.keys.size(); i < m; ++i) {
QJsonObject uniformObj;
- uniformObj.insert(QLatin1String("name"), Render::StringToInt::lookupString(it.key()));
- const Render::UniformValue::ValueType type = it.value().valueType();
+ 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")
@@ -261,7 +261,7 @@ QJsonObject parameterPackToJson(const Render::ShaderParameterPack &pack)
obj.insert(QLatin1String("uniforms"), uniformsArray);
QJsonArray texturesArray;
- const QVector<Render::ShaderParameterPack::NamedResource> &textures = pack.textures();
+ const QVector<Render::OpenGL::ShaderParameterPack::NamedResource> &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<Render::BlockToUBO> &ubos = pack.uniformBuffers();
+ const QVector<Render::OpenGL::BlockToUBO> &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<Render::BlockToSSBO> &ssbos = pack.shaderStorageBuffers();
+ const QVector<Render::OpenGL::BlockToSSBO> &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<Render::RenderView *> &views)
+void CommandExecuter::performAsynchronousCommandExecution(const QVector<Render::OpenGL::RenderView *> &views)
{
QMutexLocker lock(&m_pendingCommandsMutex);
const QVector<Qt3DCore::Debug::AsynchronousCommandReply *> shellCommands = std::move(m_pendingCommands);
@@ -334,7 +334,7 @@ void CommandExecuter::performAsynchronousCommandExecution(const QVector<Render::
QJsonObject replyObj;
QJsonArray viewArray;
- for (Render::RenderView *v : views) {
+ for (Render::OpenGL::RenderView *v : views) {
QJsonObject viewObj;
viewObj.insert(QLatin1String("viewport"), typeToJsonValue(v->viewport()));
viewObj.insert(QLatin1String("surfaceSize"), typeToJsonValue(v->surfaceSize()));
@@ -346,15 +346,15 @@ void CommandExecuter::performAsynchronousCommandExecution(const QVector<Render::
viewObj.insert(QLatin1String("clearStencilValue"), v->clearStencilValue());
QJsonArray renderCommandsArray;
- for (Render::RenderCommand *c : v->commands()) {
+ for (Render::OpenGL::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"), 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);
}
diff --git a/src/render/backend/commandexecuter_p.h b/src/plugins/renderers/opengl/renderer/commandexecuter_p.h
index 2d90bf4d6..9aea9fc2f 100644
--- a/src/render/backend/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<Render::RenderView *> &views);
+ void performAsynchronousCommandExecution(const QVector<Render::OpenGL::RenderView *> &views);
QVariant executeCommand(const QStringList &args);
private:
- Render::Renderer *m_renderer;
+ Render::OpenGL::Renderer *m_renderer;
QVector<Qt3DCore::Debug::AsynchronousCommandReply *> m_pendingCommands;
QMutex m_pendingCommandsMutex;
};
diff --git a/src/render/backend/frameprofiler_p.h b/src/plugins/renderers/opengl/renderer/frameprofiler_p.h
index b3ac3ba49..591ace53e 100644
--- a/src/render/backend/frameprofiler_p.h
+++ b/src/plugins/renderers/opengl/renderer/frameprofiler_p.h
@@ -40,12 +40,21 @@
// We mean it.
//
+#include <QOpenGLTimeMonitor>
#include <Qt3DCore/private/qthreadpooler_p.h>
#include <Qt3DCore/private/qt3dcore_global_p.h>
#include <memory>
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 {
@@ -69,13 +78,13 @@ enum RecordingType
RenderTargetUpdate
};
-#if QT_CONFIG(qt3d_profile_gl)
-
class FrameTimeRecorder
{
public:
- FrameTimeRecorder()
- {}
+ FrameTimeRecorder(Qt3DCore::QSystemInformationService *service)
+ : m_service(service)
+ {
+ }
~FrameTimeRecorder()
{
@@ -83,6 +92,7 @@ public:
void init(int eventCount)
{
+#ifdef QT3D_SUPPORTS_GL_MONITOR
if (m_monitor.isCreated()) {
m_remainingEvents = m_monitor.sampleCount();
reset();
@@ -91,28 +101,37 @@ public:
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::QThreadPooler::m_jobsStatTimer.nsecsElapsed();
+ 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();
}
@@ -120,14 +139,17 @@ public:
bool tryWriteResults()
{
+#ifdef QT3D_SUPPORTS_GL_MONITOR
if (m_monitor.isResultAvailable()) {
const QVector<GLuint64> 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::JobRunStats glRecordingStat;
+ Qt3DCore::QSystemInformationServicePrivate::JobRunStats glRecordingStat;
glRecordingStat.jobId.typeAndInstance[0] = rec.type;
glRecordingStat.jobId.typeAndInstance[1] = 0;
@@ -135,11 +157,12 @@ public:
glRecordingStat.startTime = rec.startTime;
glRecordingStat.endTime = rec.startTime + (samples.at(j + 1) - (samples.at(j)));
- Qt3DCore::QThreadPooler::addSubmissionLogStatsEntry(glRecordingStat);
+ dservice->addSubmissionLogStatsEntry(glRecordingStat);
j += 2;
}
return true;
}
+#endif
return false;
}
@@ -152,7 +175,10 @@ private:
static const int GLThreadID = 0x454;
+ Qt3DCore::QSystemInformationService *m_service;
+#ifdef QT3D_SUPPORTS_GL_MONITOR
QOpenGLTimeMonitor m_monitor;
+#endif
QVector<GLRecording> m_recordings;
int m_remainingEvents = 0;
};
@@ -160,8 +186,9 @@ private:
class FrameProfiler
{
public:
- FrameProfiler()
- : m_currentRecorder(nullptr)
+ FrameProfiler(Qt3DCore::QSystemInformationService *service)
+ : m_service(service)
+ , m_currentRecorder(nullptr)
{}
~FrameProfiler()
@@ -175,7 +202,7 @@ public:
if (!m_availableRecorders.empty()) {
m_currentRecorder = m_availableRecorders.takeFirst();
} else {
- m_recorders.push_back(new FrameTimeRecorder());
+ m_recorders.push_back(new FrameTimeRecorder(m_service));
m_currentRecorder = m_recorders.last();
}
// We record events 10 by 10
@@ -204,52 +231,36 @@ public:
}
private:
+ Qt3DCore::QSystemInformationService *m_service;
QVector<FrameTimeRecorder *> m_recorders;
QVector<FrameTimeRecorder *> m_availableRecorders;
QVector<FrameTimeRecorder *> m_busyRecorders;
FrameTimeRecorder *m_currentRecorder;
};
-#endif
class GLTimeRecorder
{
public:
- explicit GLTimeRecorder(RecordingType type)
+ explicit GLTimeRecorder(RecordingType type, FrameProfiler *profiler)
: m_type(type)
+ , m_frameProfiler(profiler)
{
-#if QT_CONFIG(qt3d_profile_gl)
- frameProfiler.startRecordEvent();
-#endif
+ if (m_frameProfiler)
+ m_frameProfiler->startRecordEvent();
}
~GLTimeRecorder()
{
-#if QT_CONFIG(qt3d_profile_gl)
- frameProfiler.recordEvent(m_type);
-#else
- Q_UNUSED(m_type);
-#endif
- }
-
- static void writeResults()
- {
-#if QT_CONFIG(qt3d_profile_gl)
- frameProfiler.writeResults();
-#endif
+ if (m_frameProfiler)
+ m_frameProfiler->recordEvent(m_type);
}
private:
-#if QT_CONFIG(qt3d_profile_gl)
- static FrameProfiler frameProfiler;
-#endif
RecordingType m_type;
+ FrameProfiler *m_frameProfiler;
};
-#if QT_CONFIG(qt3d_profile_gl)
-FrameProfiler GLTimeRecorder::frameProfiler;
-#endif
-
} // Profiling
} // Render
diff --git a/src/render/renderers/opengl/graphicshelpers/glfence_p.h b/src/plugins/renderers/opengl/renderer/glfence_p.h
index 366065048..366065048 100644
--- a/src/render/renderers/opengl/graphicshelpers/glfence_p.h
+++ b/src/plugins/renderers/opengl/renderer/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..5e92d84c2
--- /dev/null
+++ b/src/plugins/renderers/opengl/renderer/glshader.cpp
@@ -0,0 +1,321 @@
+/****************************************************************************
+**
+** 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 <QMutexLocker>
+#include <Qt3DRender/private/stringtoint_p.h>
+#include <graphicscontext_p.h>
+#include <logging_p.h>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+GLShader::GLShader()
+ : m_isLoaded(false)
+ , m_graphicsContext(nullptr)
+{
+ m_shaderCode.resize(static_cast<int>(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<QString> GLShader::uniformsNames() const
+{
+ return m_uniformsNames;
+}
+
+QVector<QString> GLShader::attributesNames() const
+{
+ return m_attributesNames;
+}
+
+QVector<QString> GLShader::uniformBlockNames() const
+{
+ return m_uniformBlockNames;
+}
+
+QVector<QString> GLShader::storageBlockNames() const
+{
+ return m_shaderStorageBlockNames;
+}
+
+QVector<QByteArray> GLShader::shaderCode() const
+{
+ return m_shaderCode;
+}
+
+QHash<QString, ShaderUniform> 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<QString, int> &fragOutputs)
+{
+ {
+ QMutexLocker lock(&m_mutex);
+ m_fragOutputs = fragOutputs;
+ }
+// updateDNA();
+}
+
+const QHash<QString, int> GLShader::fragOutputs() const
+{
+ QMutexLocker lock(&m_mutex);
+ return m_fragOutputs;
+}
+
+void GLShader::initializeUniforms(const QVector<ShaderUniform> &uniformsDescription)
+{
+ m_uniforms = uniformsDescription;
+ m_uniformsNames.resize(uniformsDescription.size());
+ m_uniformsNamesIds.reserve(uniformsDescription.size());
+ m_standardUniformNamesIds.reserve(5);
+ QHash<QString, ShaderUniform> activeUniformsInDefaultBlock;
+
+ static const QVector<int> 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<ShaderAttribute> &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<ShaderUniformBlock> &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<ShaderUniform>::const_iterator uniformsIt = m_uniforms.cbegin();
+ const QVector<ShaderUniform>::const_iterator uniformsEnd = m_uniforms.cend();
+
+ QVector<QString>::const_iterator uniformNamesIt = m_uniformsNames.cbegin();
+ const QVector<QString>::const_iterator uniformNamesEnd = m_attributesNames.cend();
+
+ QHash<QString, ShaderUniform> 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<ShaderStorageBlock> &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] << "}";
+ }
+}
+
+} // OpenGL
+
+} // 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..6bd5400af
--- /dev/null
+++ b/src/plugins/renderers/opengl/renderer/glshader_p.h
@@ -0,0 +1,164 @@
+/****************************************************************************
+**
+** 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_OPENGL_GLSHADER_P_H
+#define QT3DRENDER_RENDER_OPENGL_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 <shadervariables_p.h>
+#include <shaderparameterpack_p.h>
+#include <Qt3DRender/qshaderprogram.h>
+#include <QMutex>
+
+
+QT_BEGIN_NAMESPACE
+
+class QOpenGLShaderProgram;
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+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<QString, int> &fragOutputs);
+ const QHash<QString, int> fragOutputs() const;
+
+ inline QVector<int> uniformsNamesIds() const { return m_uniformsNamesIds; }
+ inline QVector<int> standardUniformNameIds() const { return m_standardUniformNamesIds; }
+ inline QVector<int> uniformBlockNamesIds() const { return m_uniformBlockNamesIds; }
+ inline QVector<int> storageBlockNamesIds() const { return m_shaderStorageBlockNamesIds; }
+ inline QVector<int> attributeNamesIds() const { return m_attributeNamesIds; }
+
+ QVector<QString> uniformsNames() const;
+ QVector<QString> attributesNames() const;
+ QVector<QString> uniformBlockNames() const;
+ QVector<QString> storageBlockNames() const;
+
+ inline QVector<ShaderUniform> uniforms() const { return m_uniforms; }
+ inline QVector<ShaderAttribute> attributes() const { return m_attributes; }
+ inline QVector<ShaderUniformBlock> uniformBlocks() const { return m_uniformBlocks; }
+ inline QVector<ShaderStorageBlock> storageBlocks() const { return m_shaderStorageBlocks; }
+
+ QHash<QString, ShaderUniform> 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<QByteArray> shaderCode) { m_shaderCode = shaderCode; }
+ QVector<QByteArray> shaderCode() const;
+
+private:
+ bool m_isLoaded;
+ QOpenGLShaderProgram m_shader;
+ GraphicsContext *m_graphicsContext;
+
+ QVector<QString> m_uniformsNames;
+ QVector<int> m_uniformsNamesIds;
+ QVector<int> m_standardUniformNamesIds;
+ QVector<ShaderUniform> m_uniforms;
+
+ QVector<QString> m_attributesNames;
+ QVector<int> m_attributeNamesIds;
+ QVector<ShaderAttribute> m_attributes;
+
+ QVector<QString> m_uniformBlockNames;
+ QVector<int> m_uniformBlockNamesIds;
+ QVector<ShaderUniformBlock> m_uniformBlocks;
+ QHash<int, QHash<QString, ShaderUniform> > m_uniformBlockIndexToShaderUniforms;
+
+ QVector<QString> m_shaderStorageBlockNames;
+ QVector<int> m_shaderStorageBlockNamesIds;
+ QVector<ShaderStorageBlock> m_shaderStorageBlocks;
+
+ QHash<QString, int> m_fragOutputs;
+ QVector<QByteArray> m_shaderCode;
+
+ // Private so that only GraphicContext can call it
+ void initializeUniforms(const QVector<ShaderUniform> &uniformsDescription);
+ void initializeAttributes(const QVector<ShaderAttribute> &attributesDescription);
+ void initializeUniformBlocks(const QVector<ShaderUniformBlock> &uniformBlockDescription);
+ void initializeShaderStorageBlocks(const QVector<ShaderStorageBlock> &shaderStorageBlockDescription);
+
+ friend class GraphicsContext;
+
+ mutable QMutex m_mutex;
+ QMetaObject::Connection m_contextConnection;
+};
+
+} // OpenGL
+
+} // Render
+
+} // Qt3DRender
+
+QT_END_NAMESPACE
+
+#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
new file mode 100644
index 000000000..0d6ef1211
--- /dev/null
+++ b/src/plugins/renderers/opengl/renderer/logging.cpp
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** 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 {
+
+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)
+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 OpenGL
+
+} // 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..69c125195
--- /dev/null
+++ b/src/plugins/renderers/opengl/renderer/logging_p.h
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** 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 <QLoggingCategory>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+namespace OpenGL {
+
+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 OpenGL
+
+} // namespace Render
+
+} // namespace Qt3DRender
+
+QT_END_NAMESPACE
+
+#endif // QT3DRENDER_RENDER_OPENGL_RENDERLOGGING_P_H
diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp
index f5d0a64f5..b43815f98 100644
--- a/src/render/renderers/opengl/renderer/openglvertexarrayobject.cpp
+++ b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject.cpp
@@ -38,15 +38,16 @@
****************************************************************************/
#include "openglvertexarrayobject_p.h"
-#include <Qt3DRender/private/submissioncontext_p.h>
-#include <Qt3DRender/private/renderer_p.h>
-#include <Qt3DRender/private/nodemanagers_p.h>
+#include <submissioncontext_p.h>
+#include <renderer_p.h>
+#include <glresourcemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
OpenGLVertexArrayObject::OpenGLVertexArrayObject()
: m_ctx(nullptr)
@@ -71,7 +72,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);
}
}
@@ -133,7 +134,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 +142,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;
}
@@ -159,6 +160,7 @@ void OpenGLVertexArrayObject::saveVertexAttribute(const SubmissionContext::VAOVe
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/renderer/openglvertexarrayobject_p.h b/src/plugins/renderers/opengl/renderer/openglvertexarrayobject_p.h
index 4896df9bf..ff58b3074 100644
--- a/src/render/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
@@ -52,7 +52,7 @@
//
#include <QtGui/qopenglvertexarrayobject.h>
-#include <Qt3DRender/private/submissioncontext_p.h>
+#include <submissioncontext_p.h>
QT_BEGIN_NAMESPACE
@@ -60,11 +60,14 @@ namespace Qt3DRender {
namespace Render {
class GeometryManager;
-class ShaderManager;
-typedef QPair<HGeometry, HShader> VAOIdentifier;
+typedef QPair<HGeometry, Qt3DCore::QNodeId> VAOIdentifier;
-class OpenGLVertexArrayObject
+namespace OpenGL {
+
+class GLShaderManager;
+
+class Q_AUTOTEST_EXPORT OpenGLVertexArrayObject
{
public:
OpenGLVertexArrayObject();
@@ -77,7 +80,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(); }
@@ -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
new file mode 100644
index 000000000..d4da1a41b
--- /dev/null
+++ b/src/plugins/renderers/opengl/renderer/rendercommand.cpp
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** 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 {
+namespace OpenGL {
+
+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 OpenGL
+} // namespace Render
+} // namespace Qt3DRender
+
+QT_END_NAMESPACE
diff --git a/src/render/renderers/opengl/renderer/rendercommand_p.h b/src/plugins/renderers/opengl/renderer/rendercommand_p.h
index 61cc6d17d..123ff232b 100644
--- a/src/render/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
@@ -53,7 +53,9 @@
//
#include <qglobal.h>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
+#include <shaderparameterpack_p.h>
+#include <gl_handle_types_p.h>
+#include <renderviewjobutils_p.h>
#include <Qt3DRender/private/handle_types_p.h>
#include <Qt3DRender/qgeometryrenderer.h>
#include <QOpenGLShaderProgram>
@@ -69,6 +71,11 @@ namespace Qt3DRender {
namespace Render {
class RenderStateSet;
+using RenderStateSetPtr = QSharedPointer<RenderStateSet>;
+
+namespace OpenGL {
+
+class GLShader;
class Q_AUTOTEST_EXPORT RenderCommand
{
@@ -76,16 +83,18 @@ 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.
- 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
@@ -93,7 +102,6 @@ public:
float m_depth;
int m_changeCost;
- uint m_shaderDna;
enum CommandType {
Draw,
@@ -121,10 +129,58 @@ 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
+{
+ QVector<Entity *> entities;
+ QVector<RenderCommand> commands;
+ QVector<RenderPassParameterData> 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<EntityRenderCommandData>;
+
+} // namespace OpenGL
+
} // namespace Render
} // namespace Qt3DRender
QT_END_NAMESPACE
-#endif // QT3DRENDER_RENDER_RENDERCOMMAND_H
+#endif // QT3DRENDER_RENDER_OPENGL_RENDERCOMMAND_H
diff --git a/src/render/renderers/opengl/renderer/renderer.cpp b/src/plugins/renderers/opengl/renderer/renderer.cpp
index 1c28b737b..d01f22847 100644
--- a/src/render/renderers/opengl/renderer/renderer.cpp
+++ b/src/plugins/renderers/opengl/renderer/renderer.cpp
@@ -54,21 +54,15 @@
#include <Qt3DRender/private/renderstates_p.h>
#include <Qt3DRender/private/cameraselectornode_p.h>
#include <Qt3DRender/private/framegraphvisitor_p.h>
-#include <Qt3DRender/private/graphicscontext_p.h>
#include <Qt3DRender/private/cameralens_p.h>
-#include <Qt3DRender/private/rendercommand_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/material_p.h>
#include <Qt3DRender/private/renderpassfilternode_p.h>
-#include <Qt3DRender/private/renderqueue_p.h>
#include <Qt3DRender/private/shader_p.h>
#include <Qt3DRender/private/buffer_p.h>
-#include <Qt3DRender/private/glbuffer_p.h>
-#include <Qt3DRender/private/renderstateset_p.h>
#include <Qt3DRender/private/technique_p.h>
#include <Qt3DRender/private/renderthread_p.h>
-#include <Qt3DRender/private/renderview_p.h>
#include <Qt3DRender/private/scenemanager_p.h>
#include <Qt3DRender/private/techniquefilternode_p.h>
#include <Qt3DRender/private/viewportnode_p.h>
@@ -77,31 +71,43 @@
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/buffermanager_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
#include <Qt3DRender/private/geometryrenderermanager_p.h>
#include <Qt3DRender/private/techniquemanager_p.h>
-#include <Qt3DRender/private/openglvertexarrayobject_p.h>
#include <Qt3DRender/private/platformsurfacefilter_p.h>
#include <Qt3DRender/private/loadbufferjob_p.h>
#include <Qt3DRender/private/rendercapture_p.h>
#include <Qt3DRender/private/updatelevelofdetailjob_p.h>
#include <Qt3DRender/private/buffercapture_p.h>
#include <Qt3DRender/private/offscreensurfacehelper_p.h>
-#include <Qt3DRender/private/renderviewbuilder_p.h>
-#include <Qt3DRender/private/setfence_p.h>
#include <Qt3DRender/private/subtreeenabler_p.h>
#include <Qt3DRender/private/qshaderprogrambuilder_p.h>
#include <Qt3DRender/private/qshaderprogram_p.h>
+#include <Qt3DRender/private/filterentitybycomponentjob_p.h>
+#ifndef Q_OS_INTEGRITY
+#include <imguirenderer_p.h>
+#endif
#include <Qt3DRender/qcameralens.h>
#include <Qt3DCore/private/qeventfilterservice_p.h>
#include <Qt3DCore/private/qabstractaspectjobmanager_p.h>
#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p.h>
+#include <Qt3DCore/private/qsysteminformationservice_p_p.h>
+#include <Qt3DRender/private/resourceaccessor_p.h>
+#include <Qt3DRender/private/renderlogging_p.h>
+#include <Qt3DRender/private/renderstateset_p.h>
+#include <Qt3DRender/private/setfence_p.h>
-#if QT_CONFIG(qt3d_profile_jobs)
-#include <Qt3DCore/private/aspectcommanddebugger_p.h>
-#endif
+#include <glbuffer_p.h>
+#include <graphicscontext_p.h>
+#include <rendercommand_p.h>
+#include <renderqueue_p.h>
+#include <renderview_p.h>
+#include <gltexture_p.h>
+#include <openglvertexarrayobject_p.h>
+#include <renderviewbuilder_p.h>
+#include <glresourcemanagers_p.h>
+#include <commandexecuter_p.h>
#include <QStack>
#include <QOffscreenSurface>
@@ -114,20 +120,10 @@
#include <QUrl>
#include <QOffscreenSurface>
#include <QWindow>
-
-#include <QtGui/private/qopenglcontext_p.h>
-
-// For Debug purposes only
#include <QThread>
-
-#if QT_CONFIG(qt3d_profile_jobs)
-#include <Qt3DCore/private/qthreadpooler_p.h>
-#include <Qt3DRender/private/job_common_p.h>
-#include <Qt3DRender/private/commandexecuter_p.h>
-#endif
-
-#include <Qt3DRender/private/frameprofiler_p.h>
+#include <QtGui/private/qopenglcontext_p.h>
+#include "frameprofiler_p.h"
QT_BEGIN_NAMESPACE
@@ -138,6 +134,82 @@ using namespace Qt3DCore;
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
+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<Entity *> 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<Entity *> 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
@@ -174,7 +246,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)
@@ -186,31 +257,36 @@ Renderer::Renderer(QRenderAspect::RenderType type)
, m_calculateBoundingVolumeJob(Render::CalculateBoundingVolumeJobPtr::create())
, m_updateWorldBoundingVolumeJob(Render::UpdateWorldBoundingVolumeJobPtr::create())
, m_updateTreeEnabledJob(Render::UpdateTreeEnabledJobPtr::create())
- , m_sendRenderCaptureJob(Render::SendRenderCaptureJobPtr::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_filterCompatibleTechniqueJob(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_sendTextureChangesToFrontendJob(SynchronizerPostFramePtr::create([] {},
- [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_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_shouldSwapBuffers(true)
- #if QT_CONFIG(qt3d_profile_jobs)
+ , m_glResourceManagers(nullptr)
, m_commandExecuter(new Qt3DRender::Debug::CommandExecuter(this))
- #endif
+ , 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
@@ -238,6 +314,10 @@ Renderer::Renderer(QRenderAspect::RenderType type)
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;
@@ -254,10 +334,14 @@ Renderer::~Renderer()
delete m_renderQueue;
delete m_defaultRenderStateSet;
- delete m_shaderCache;
+ delete m_glResourceManagers;
if (!m_ownedContext)
QObject::disconnect(m_contextConnection);
+
+#ifndef Q_OS_INTEGRITY
+ delete m_imGuiRenderer;
+#endif
}
void Renderer::dumpInfo() const
@@ -287,9 +371,16 @@ 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);
@@ -299,13 +390,16 @@ void Renderer::setNodeManagers(NodeManagers *managers)
m_pickBoundingVolumeJob->setManagers(m_nodesManager);
m_rayCastingJob->setManagers(m_nodesManager);
m_updateWorldBoundingVolumeJob->setManager(m_nodesManager->renderNodesManager());
- m_sendRenderCaptureJob->setManagers(m_nodesManager);
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)
@@ -339,7 +433,8 @@ QOpenGLContext *Renderer::shareContext() const
void Renderer::loadShader(Shader *shader, HShader shaderHandle)
{
Q_UNUSED(shader);
- m_dirtyShaders.push_back(shaderHandle);
+ if (!m_dirtyShaders.contains(shaderHandle))
+ m_dirtyShaders.push_back(shaderHandle);
}
void Renderer::setOpenGLContext(QOpenGLContext *context)
@@ -357,6 +452,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<RenderBackendResourceAccessor> 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
@@ -388,12 +516,16 @@ 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
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,
@@ -412,9 +544,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);
@@ -432,6 +561,9 @@ void Renderer::initialize()
m_waitForInitializationToBeCompleted.release(1);
// Allow the aspect manager to proceed
m_vsyncFrameAdvanceService->proceedToNextFrame();
+
+ // Force initial refresh
+ markDirty(AllDirty, nullptr);
}
/*!
@@ -466,6 +598,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;
}
/*!
@@ -504,26 +642,31 @@ void Renderer::releaseGraphicsResources()
if (context->thread() == QThread::currentThread() && context->makeCurrent(offscreenSurface)) {
// Clean up the graphics context and any resources
- const QVector<HGLTexture> activeTexturesHandles = m_nodesManager->glTextureManager()->activeHandles();
+ const QVector<HGLTexture> 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<HGLBuffer> activeBuffers = m_nodesManager->glBufferManager()->activeHandles();
+ const QVector<HGLBuffer> 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 shaders
+ const QVector<GLShader *> shaders = m_glResourceManagers->glShaderManager()->takeActiveResources();
+ qDeleteAll(shaders);
+
// Do the same thing with VAOs
- const QVector<HVao> activeVaos = m_nodesManager->vaoManager()->activeHandles();
+ const QVector<HVao> 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();
}
+ m_frameProfiler.reset();
context->doneCurrent();
} else {
qWarning() << "Failed to make context current: OpenGL resources will not be destroyed";
@@ -652,25 +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<Render::RenderView *> renderViews = m_renderQueue->nextFrameQueue();
-
-#if QT_CONFIG(qt3d_profile_jobs)
- // Save start of frame
- JobRunStats submissionStatsPart1;
- JobRunStats submissionStatsPart2;
- submissionStatsPart1.jobId.typeAndInstance[0] = JobTypes::FrameSubmissionPart1;
- submissionStatsPart1.jobId.typeAndInstance[1] = 0;
- submissionStatsPart1.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
- submissionStatsPart1.startTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
- submissionStatsPart2.jobId.typeAndInstance[0] = JobTypes::FrameSubmissionPart2;
- submissionStatsPart2.jobId.typeAndInstance[1] = 0;
- submissionStatsPart2.threadId = reinterpret_cast<quint64>(QThread::currentThreadId());
-#endif
-
+ const QVector<Render::OpenGL::RenderView *> 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;
@@ -689,6 +824,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();
}
}
}
@@ -698,15 +840,11 @@ void Renderer::doRender(bool swapBuffers)
m_vsyncFrameAdvanceService->proceedToNextFrame();
hasCleanedQueueAndProceeded = true;
-#if QT_CONFIG(qt3d_profile_jobs)
- if (preprocessingComplete) {
- submissionStatsPart2.startTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
- submissionStatsPart1.endTime = submissionStatsPart2.startTime;
- }
-#endif
// 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);
@@ -716,33 +854,21 @@ void Renderer::doRender(bool swapBuffers)
}
}
-#if QT_CONFIG(qt3d_profile_jobs)
// Execute the pending shell commands
m_commandExecuter->performAsynchronousCommandExecution(renderViews);
-#endif
// Delete all the RenderViews which will clear the allocators
// that were used for their allocation
qDeleteAll(renderViews);
-#if QT_CONFIG(qt3d_profile_jobs)
- if (preprocessingComplete) {
- // Save submission elapsed time
- submissionStatsPart2.endTime = QThreadPooler::m_jobsStatTimer.nsecsElapsed();
- // Note this is safe since proceedToNextFrame is the one going to trigger
- // the write to the file, and this is performed after this step
- Qt3DCore::QThreadPooler::addSubmissionLogStatsEntry(submissionStatsPart1);
- Qt3DCore::QThreadPooler::addSubmissionLogStatsEntry(submissionStatsPart2);
- Profiling::GLTimeRecorder::writeResults();
- }
-#endif
+ 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
@@ -776,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:
@@ -795,6 +921,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()) {
@@ -809,6 +936,18 @@ bool Renderer::canRender() const
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
@@ -830,12 +969,7 @@ bool Renderer::isReadyToSubmit()
// Main thread
QVariant Renderer::executeCommand(const QStringList &args)
{
-#if QT_CONFIG(qt3d_profile_jobs)
return m_commandExecuter->executeCommand(args);
-#else
- Q_UNUSED(args);
-#endif
- return QVariant();
}
/*!
@@ -860,13 +994,13 @@ void Renderer::prepareCommandsSubmission(const QVector<RenderView *> &renderView
QHash<HVao, bool> updatedTable;
for (RenderView *rv: renderViews) {
- const QVector<RenderCommand *> commands = rv->commands();
- for (RenderCommand *command : commands) {
+ QVector<RenderCommand> &commands = rv->commands();
+ for (RenderCommand &command : commands) {
// Update/Create VAO
- if (command->m_type == RenderCommand::Draw) {
- Geometry *rGeometry = m_nodesManager->data<Geometry, GeometryManager>(command->m_geometry);
- GeometryRenderer *rGeometryRenderer = m_nodesManager->data<GeometryRenderer, GeometryRendererManager>(command->m_geometryRenderer);
- Shader *shader = m_nodesManager->data<Shader, ShaderManager>(command->m_shader);
+ if (command.m_type == RenderCommand::Draw) {
+ Geometry *rGeometry = m_nodesManager->data<Geometry, GeometryManager>(command.m_geometry);
+ GeometryRenderer *rGeometryRenderer = m_nodesManager->data<GeometryRenderer, GeometryRendererManager>(command.m_geometryRenderer);
+ GLShader *shader = command.m_glShader;
// We should never have inserted a command for which these are null
// in the first place
@@ -879,15 +1013,15 @@ void Renderer::prepareCommandsSubmission(const QVector<RenderView *> &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,15 +1032,15 @@ void Renderer::prepareCommandsSubmission(const QVector<RenderView *> &renderView
if (rGeometry->isDirty())
m_dirtyGeometry.push_back(rGeometry);
- if (!command->m_activeAttributes.isEmpty() && (requiresFullVAOUpdate || requiresPartialVAOUpdate)) {
- Profiling::GLTimeRecorder recorder(Profiling::VAOUpload);
+ 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
// Note: this fills m_dirtyAttributes as well
- if (updateVAOWithAttributes(rGeometry, command, shader, requiresFullVAOUpdate))
+ if (updateVAOWithAttributes(rGeometry, &command, shader, requiresFullVAOUpdate))
vao->setSpecified(true);
}
}
@@ -918,82 +1052,14 @@ void Renderer::prepareCommandsSubmission(const QVector<RenderView *> &renderView
rGeometryRenderer->unsetDirty();
// Prepare the ShaderParameterPack based on the active uniforms of the shader
- shader->prepareUniforms(command->m_parameterPack);
-
- { // Scoped to show extent
- 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
- uint primitiveCount = rGeometryRenderer->vertexCount();
- uint estimatedCount = 0;
- Attribute *indexAttribute = nullptr;
- Attribute *indirectAttribute = nullptr;
-
- const QVector<Qt3DCore::QNodeId> attributeIds = rGeometry->attributes();
- for (Qt3DCore::QNodeId attributeId : attributeIds) {
- Attribute *attribute = m_nodesManager->attributeManager()->lookupResource(attributeId);
- switch (attribute->attributeType()) {
- case QAttribute::IndexAttribute:
- indexAttribute = attribute;
- break;
- case QAttribute::DrawIndirectAttribute:
- indirectAttribute = attribute;
- break;
- case QAttribute::VertexAttribute: {
- if (command->m_activeAttributes.contains(attribute->nameId()))
- estimatedCount = qMax(attribute->count(), estimatedCount);
- break;
- }
- default:
- Q_UNREACHABLE();
- break;
- }
- }
-
- command->m_drawIndexed = (indexAttribute != nullptr);
- command->m_drawIndirect = (indirectAttribute != nullptr);
+ shader->prepareUniforms(command.m_parameterPack);
- // 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();
- }
-
- // 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());
- } 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 = 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<Shader, ShaderManager>(command->m_shader);
+ } 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);
+ shader->prepareUniforms(command.m_parameterPack);
}
}
}
@@ -1017,13 +1083,13 @@ void Renderer::prepareCommandsSubmission(const QVector<RenderView *> &renderView
// Executed in a job
void Renderer::lookForAbandonedVaos()
{
- const QVector<HVao> activeVaos = m_nodesManager->vaoManager()->activeHandles();
- for (const HVao &handle : activeVaos) {
- OpenGLVertexArrayObject *vao = m_nodesManager->vaoManager()->data(handle);
+ const QVector<HVao> 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_nodesManager->shaderManager())) {
+ if (vao && vao->isAbandoned(m_nodesManager->geometryManager(), m_glResourceManagers->glShaderManager())) {
m_abandonedVaosMutex.lock();
m_abandonedVaos.push_back(handle);
m_abandonedVaosMutex.unlock();
@@ -1042,6 +1108,7 @@ void Renderer::lookForDirtyBuffers()
}
}
+// Called in prepareSubmission
void Renderer::lookForDownloadableBuffers()
{
m_downloadableBuffers.clear();
@@ -1049,7 +1116,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());
}
}
@@ -1106,7 +1173,7 @@ void Renderer::reloadDirtyShaders()
// If api of the renderer matches the one from the technique
if (technique->isCompatibleWithRenderer()) {
const auto passIds = technique->renderPasses();
- for (const QNodeId passId : passIds) {
+ 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);
@@ -1138,15 +1205,14 @@ 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);
}
}
}
}
-// Executed in job postFrame
+// Executed in job (in main thread when jobs are done)
void Renderer::sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager)
{
Q_ASSERT(isRunning());
@@ -1173,14 +1239,13 @@ void Renderer::sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager)
}
}
-// Executed in a job (as postFrame)
+// Executed in a job (in main thread when jobs are done)
void Renderer::sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager)
{
const QVector<QPair<Texture::TextureUpdateInfo, Qt3DCore::QNodeIdVector>> updateTextureProperties = std::move(m_updatedTextureProperties);
for (const auto &pair : updateTextureProperties) {
const Qt3DCore::QNodeIdVector targetIds = pair.second;
- for (const Qt3DCore::QNodeId targetId: targetIds) {
-
+ 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
@@ -1226,17 +1291,24 @@ void Renderer::sendSetFenceHandlesToFrontend()
}
}
-// Executed in a job
-void Renderer::sendDisablesToFrontend()
+// Executed in a job (in main thread when jobs done)
+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<SubtreeEnabler *>(fgNode);
- enabler->sendDisableToFrontend();
+ QSubtreeEnabler *frontend = static_cast<decltype(frontend)>(manager->lookupNode(nodeId));
+ frontend->setEnabled(false);
+ }
+
+ // Compute Commands
+ const QVector<HComputeCommand> activeCommands = m_nodesManager->computeJobManager()->activeHandles();
+ for (const HComputeCommand &handle :activeCommands) {
+ ComputeCommand *c = m_nodesManager->computeJobManager()->data(handle);
+ if (c->hasReachedFrameCount()) {
+ QComputeCommand *frontend = static_cast<decltype(frontend)>(manager->lookupNode(c->peerId()));
+ frontend->setEnabled(false);
+ c->resetHasReachedFrameCount();
}
}
}
@@ -1256,7 +1328,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) {
@@ -1273,7 +1345,7 @@ void Renderer::updateGLResources()
}
{
- Profiling::GLTimeRecorder recorder(Profiling::BufferUpload);
+ Profiling::GLTimeRecorder recorder(Profiling::BufferUpload, activeProfiler());
const QVector<HBuffer> dirtyBufferHandles = std::move(m_dirtyBuffers);
for (const HBuffer &handle: dirtyBufferHandles) {
Buffer *buffer = m_nodesManager->bufferManager()->data(handle);
@@ -1285,7 +1357,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();
@@ -1294,7 +1366,7 @@ void Renderer::updateGLResources()
#ifndef SHADER_LOADING_IN_COMMAND_THREAD
{
- Profiling::GLTimeRecorder recorder(Profiling::ShaderUpload);
+ Profiling::GLTimeRecorder recorder(Profiling::ShaderUpload, activeProfiler());
const QVector<HShader> dirtyShaderHandles = std::move(m_dirtyShaders);
ShaderManager *shaderManager = m_nodesManager->shaderManager();
for (const HShader &handle: dirtyShaderHandles) {
@@ -1305,13 +1377,13 @@ void Renderer::updateGLResources()
continue;
// Compile shader
- m_submissionContext->loadShader(shader, shaderManager);
+ m_submissionContext->loadShader(shader, shaderManager, m_glResourceManagers->glShaderManager());
}
}
#endif
{
- Profiling::GLTimeRecorder recorder(Profiling::TextureUpload);
+ Profiling::GLTimeRecorder recorder(Profiling::TextureUpload, activeProfiler());
const QVector<HTexture> activeTextureHandles = std::move(m_dirtyTextures);
for (const HTexture &handle: activeTextureHandles) {
Texture *texture = m_nodesManager->textureManager()->data(handle);
@@ -1328,7 +1400,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<HGLTexture> glTextureHandles = glTextureManager->activeHandles();
// Upload texture data
for (const HGLTexture &glTextureHandle : glTextureHandles) {
@@ -1355,6 +1427,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
@@ -1371,7 +1446,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
@@ -1424,7 +1499,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
@@ -1434,21 +1509,37 @@ 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()
{
- lookForDownloadableBuffers();
- const QVector<HBuffer> 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*, QByteArray>(buffer, content));
+ const QVector<Qt3DCore::QNodeId> downloadableHandles = std::move(m_downloadableBuffers);
+ for (const Qt3DCore::QNodeId &bufferId : downloadableHandles) {
+ BufferManager *bufferManager = m_nodesManager->bufferManager();
+ BufferManager::ReadLocker locker(const_cast<const BufferManager *>(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<Qt3DCore::QNodeId, QByteArray>(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<Render::RenderView *> &renderViews)
+Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<RenderView *> &renderViews)
{
QElapsedTimer timer;
quint64 queueElapsed = 0;
@@ -1464,13 +1555,14 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
uint lastBoundFBOId = m_submissionContext->boundFrameBufferObject();
QSurface *surface = nullptr;
QSurface *previousSurface = nullptr;
- for (const Render::RenderView *rv: renderViews) {
+ for (const 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
@@ -1524,7 +1616,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
// Insert Fence into command stream if needed
const Qt3DCore::QNodeIdVector insertFenceIds = renderView->insertFenceIds();
- 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.
@@ -1565,7 +1657,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
RenderStateSet *renderViewStateSet = renderView->stateSet();
{
- Profiling::GLTimeRecorder recorder(Profiling::StateUpdate);
+ Profiling::GLTimeRecorder recorder(Profiling::StateUpdate, activeProfiler());
// Set the RV state if not null,
if (renderViewStateSet != nullptr)
m_submissionContext->setCurrentStateSet(renderViewStateSet);
@@ -1576,14 +1668,14 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
// Set RenderTarget ...
// Activate RenderTarget
{
- Profiling::GLTimeRecorder recorder(Profiling::RenderTargetUpdate);
+ Profiling::GLTimeRecorder recorder(Profiling::RenderTargetUpdate, activeProfiler());
m_submissionContext->activateRenderTarget(renderView->renderTargetId(),
renderView->attachmentPack(),
lastBoundFBOId);
}
{
- Profiling::GLTimeRecorder recorder(Profiling::ClearBuffer);
+ Profiling::GLTimeRecorder recorder(Profiling::ClearBuffer, activeProfiler());
// set color, depth, stencil clear values (only if needed)
auto clearBufferTypes = renderView->clearTypes();
if (clearBufferTypes & QClearBuffers::ColorBuffer) {
@@ -1606,7 +1698,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
}
// Set the Viewport
- m_submissionContext->setViewport(renderView->viewport(), renderView->surfaceSize() * renderView->devicePixelRatio());
+ m_submissionContext->setViewport(renderView->viewport(), renderView->surfaceSize());
// Execute the render commands
if (!executeCommandsSubmission(renderView))
@@ -1617,7 +1709,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
// renderViewStateSet or m_defaultRenderStateSet)
if (!renderView->renderCaptureNodeId().isNull()) {
const QRenderCaptureRequest request = renderView->renderCaptureRequest();
- const QSize size = m_submissionContext->renderTargetSize(renderView->surfaceSize() * renderView->devicePixelRatio());
+ const QSize size = m_submissionContext->renderTargetSize(renderView->surfaceSize());
QRect rect(QPoint(0, 0), size);
if (!request.rect.isEmpty())
rect = rect.intersected(request.rect);
@@ -1632,7 +1724,8 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
Render::RenderCapture *renderCapture =
static_cast<Render::RenderCapture*>(m_nodesManager->frameGraphManager()->lookupNode(renderView->renderCaptureNodeId()));
renderCapture->addRenderCapture(request.captureId, image);
- addRenderCaptureSendRequest(renderView->renderCaptureNodeId());
+ if (!m_pendingRenderCaptureSendRequests.contains(renderView->renderCaptureNodeId()))
+ m_pendingRenderCaptureSendRequests.push_back(renderView->renderCaptureNodeId());
}
if (renderView->isDownloadBuffersEnable())
@@ -1653,6 +1746,25 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
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";
@@ -1688,7 +1800,7 @@ Renderer::ViewSubmissionResultData Renderer::submitRenderViews(const QVector<Ren
void Renderer::markDirty(BackendNodeDirtySet changes, BackendNode *node)
{
- Q_UNUSED(node);
+ Q_UNUSED(node)
m_dirtyBits.marked |= changes;
}
@@ -1705,12 +1817,11 @@ void Renderer::clearDirtyBits(BackendNodeDirtySet changes)
}
#endif
-bool Renderer::shouldRender()
+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_renderThread == nullptr // <==> we use Scene3D
|| m_dirtyBits.marked != 0
|| m_dirtyBits.remaining != 0
|| !m_lastFrameCorrect.loadRelaxed());
@@ -1725,24 +1836,52 @@ void Renderer::skipNextFrame()
m_submitRenderViewsSemaphore.release(1);
}
-// Jobs we may have to run even if no rendering will happen
-QVector<QAspectJobPtr> Renderer::preRenderingJobs()
+void Renderer::jobsDone(Qt3DCore::QAspectManager *manager)
{
- QVector<QAspectJobPtr> jobs;
+ // called in main thread once all jobs are done running
+
+ // sync captured renders to frontend
+ const QVector<Qt3DCore::QNodeId> pendingCaptureIds = std::move(m_pendingRenderCaptureSendRequests);
+ for (const Qt3DCore::QNodeId &id : qAsConst(pendingCaptureIds)) {
+ auto *backend = static_cast<Qt3DRender::Render::RenderCapture *>
+ (m_nodesManager->frameGraphManager()->lookupNode(id));
+ backend->syncRenderCapturesToFrontend(manager);
+ }
// Do we need to notify any texture about property changes?
if (m_updatedTextureProperties.size() > 0)
- jobs.push_back(m_sendTextureChangesToFrontendJob);
+ sendTextureChangesToFrontend(manager);
+
+ sendDisablesToFrontend(manager);
+}
+
+// Jobs we may have to run even if no rendering will happen
+QVector<QAspectJobPtr> 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<QAspectJobPtr> jobs;
// Do we need to notify frontend about fence change?
if (m_updatedSetFences.size() > 0)
jobs.push_back(m_sendSetFenceHandlesToFrontendJob);
- const QVector<Qt3DCore::QNodeId> pendingCaptureIds = takePendingRenderCaptureSendRequests();
- if (pendingCaptureIds.size() > 0) {
- m_sendRenderCaptureJob->setPendingCaptureRequests(pendingCaptureIds);
- jobs.push_back(m_sendRenderCaptureJob);
- }
if (m_sendBufferCaptureJob->hasRequests())
jobs.push_back(m_sendBufferCaptureJob);
@@ -1759,7 +1898,6 @@ QVector<QAspectJobPtr> Renderer::preRenderingJobs()
QVector<Qt3DCore::QAspectJobPtr> Renderer::renderBinJobs()
{
QVector<QAspectJobPtr> renderBinJobs;
-
// Create the jobs to build the frame
const QVector<QAspectJobPtr> bufferJobs = createRenderBufferJobs();
@@ -1810,7 +1948,6 @@ QVector<Qt3DCore::QAspectJobPtr> Renderer::renderBinJobs()
renderBinJobs.push_back(m_updateSkinningPaletteJob);
renderBinJobs.push_back(m_updateLevelOfDetailJob);
renderBinJobs.push_back(m_cleanupJob);
-
renderBinJobs.append(bufferJobs);
// Jobs to prepare GL Resource upload
@@ -1834,11 +1971,27 @@ QVector<Qt3DCore::QAspectJobPtr> 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)
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
@@ -1859,20 +2012,18 @@ QVector<Qt3DCore::QAspectJobPtr> 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();
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);
+ 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());
@@ -1905,27 +2056,11 @@ QVector<Qt3DCore::QAspectJobPtr> 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;
}
@@ -1958,7 +2093,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;
@@ -1992,7 +2127,7 @@ void Renderer::performDraw(RenderCommand *command)
// TO DO: Add glMulti Draw variants
if (command->m_drawIndexed) {
- Profiling::GLTimeRecorder recorder(Profiling::DrawElement);
+ Profiling::GLTimeRecorder recorder(Profiling::DrawElement, activeProfiler());
m_submissionContext->drawElementsInstancedBaseVertexBaseInstance(command->m_primitiveType,
command->m_primitiveCount,
command->m_indexAttributeDataType,
@@ -2001,7 +2136,7 @@ void Renderer::performDraw(RenderCommand *command)
command->m_indexOffset,
command->m_firstInstance);
} else {
- Profiling::GLTimeRecorder recorder(Profiling::DrawArray);
+ Profiling::GLTimeRecorder recorder(Profiling::DrawArray, activeProfiler());
m_submissionContext->drawArraysInstancedBaseInstance(command->m_primitiveType,
command->m_firstVertex,
command->m_primitiveCount,
@@ -2023,15 +2158,16 @@ void Renderer::performDraw(RenderCommand *command)
void Renderer::performCompute(const RenderView *, RenderCommand *command)
{
{
- Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate);
- m_submissionContext->activateShader(command->m_shaderDna);
+ Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate, activeProfiler());
+ GLShader *shader = m_glResourceManagers->glShaderManager()->lookupResource(command->m_shaderId);
+ m_submissionContext->activateShader(shader);
}
{
- Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate);
+ Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler());
m_submissionContext->setParameters(command->m_parameterPack);
}
{
- Profiling::GLTimeRecorder recorder(Profiling::DispatchCompute);
+ Profiling::GLTimeRecorder recorder(Profiling::DispatchCompute, activeProfiler());
m_submissionContext->dispatchCompute(command->m_workGroups[0],
command->m_workGroups[1],
command->m_workGroups[2]);
@@ -2050,9 +2186,9 @@ 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_nodesManager->vaoManager();
+ VAOManager *vaoManager = m_glResourceManagers->vaoManager();
command->m_vao = vaoManager->lookupHandle(vaoKey);
if (command->m_vao.isNull()) {
@@ -2075,7 +2211,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv)
bool allCommandsIssued = true;
// Render drawing commands
- const QVector<RenderCommand *> commands = rv->commands();
+ QVector<RenderCommand> commands = rv->commands();
// Use the graphicscontext to submit the commands to the underlying
// graphics API (OpenGL)
@@ -2084,18 +2220,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_glResourceManagers->vaoManager()->data(command.m_vao);
// something may have went wrong when initializing the VAO
if (!vao->isSpecified()) {
@@ -2104,24 +2240,25 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv)
}
{
- Profiling::GLTimeRecorder recorder(Profiling::ShaderUpdate);
+ 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;
}
}
{
- Profiling::GLTimeRecorder recorder(Profiling::VAOUpdate);
+ Profiling::GLTimeRecorder recorder(Profiling::VAOUpdate, activeProfiler());
// Bind VAO
vao->bind();
}
{
- Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate);
+ Profiling::GLTimeRecorder recorder(Profiling::UniformUpdate, activeProfiler());
//// 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,16 +2269,16 @@ 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();
{
- Profiling::GLTimeRecorder recorder(Profiling::StateUpdate);
+ 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(command->m_stateSet);
+ command.m_stateSet->merge(globalState);
+ m_submissionContext->setCurrentStateSet(localState);
} else {
m_submissionContext->setCurrentStateSet(globalState);
}
@@ -2151,7 +2288,7 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv)
// at that point
//// Draw Calls
- performDraw(command);
+ performDraw(&command);
}
} // end of RenderCommands loop
@@ -2167,8 +2304,8 @@ bool Renderer::executeCommandsSubmission(const RenderView *rv)
}
bool Renderer::updateVAOWithAttributes(Geometry *geometry,
- RenderCommand *command,
- Shader *shader,
+ const RenderCommand *command,
+ GLShader *shader,
bool forceUpdate)
{
m_dirtyAttributes.reserve(m_dirtyAttributes.size() + geometry->attributes().size());
@@ -2227,7 +2364,7 @@ bool Renderer::updateVAOWithAttributes(Geometry *geometry,
}
bool Renderer::requiresVAOAttributeUpdate(Geometry *geometry,
- RenderCommand *command) const
+ const RenderCommand *command) const
{
const auto attributeIds = geometry->attributes();
@@ -2266,23 +2403,23 @@ 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);
}
}
-}
-QList<QPair<QObject *, QMouseEvent>> Renderer::pendingPickingEvents() const
-{
- return m_pickEventFilter->pendingMouseEvents();
-}
-
-QList<QKeyEvent> Renderer::pendingKeyEvents() const
-{
- return m_pickEventFilter->pendingKeyEvents();
+ // 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<Qt3DCore::QNodeId> 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
@@ -2295,17 +2432,6 @@ SubmissionContext *Renderer::submissionContext() const
return m_submissionContext.data();
}
-void Renderer::addRenderCaptureSendRequest(Qt3DCore::QNodeId nodeId)
-{
- if (!m_pendingRenderCaptureSendRequests.contains(nodeId))
- m_pendingRenderCaptureSendRequests.push_back(nodeId);
-}
-
-const QVector<Qt3DCore::QNodeId> Renderer::takePendingRenderCaptureSendRequests()
-{
- return std::move(m_pendingRenderCaptureSendRequests);
-}
-
// Returns a vector of jobs to be performed for dirty buffers
// 1 dirty buffer == 1 job, all job can be performed in parallel
QVector<Qt3DCore::QAspectJobPtr> Renderer::createRenderBufferJobs() const
@@ -2327,6 +2453,7 @@ QVector<Qt3DCore::QAspectJobPtr> Renderer::createRenderBufferJobs() const
return dirtyBuffersJobs;
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/renderer/renderer.pri b/src/plugins/renderers/opengl/renderer/renderer.pri
index 849bac702..3e3f83c86 100644
--- a/src/render/renderers/opengl/renderer/renderer.pri
+++ b/src/plugins/renderers/opengl/renderer/renderer.pri
@@ -7,7 +7,10 @@ SOURCES += \
$$PWD/renderqueue.cpp \
$$PWD/renderview.cpp \
$$PWD/renderviewbuilder.cpp \
- $$PWD/shaderparameterpack.cpp
+ $$PWD/shaderparameterpack.cpp \
+ $$PWD/glshader.cpp \
+ $$PWD/logging.cpp \
+ $$PWD/commandexecuter.cpp
HEADERS += \
$$PWD/openglvertexarrayobject_p.h \
@@ -18,6 +21,10 @@ 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 \
+ $$PWD/glfence_p.h \
+ $$PWD/logging_p.h \
+ $$PWD/commandexecuter_p.h \
+ $$PWD/frameprofiler_p.h
diff --git a/src/render/renderers/opengl/renderer/renderer_p.h b/src/plugins/renderers/opengl/renderer/renderer_p.h
index 0af0481a3..4a6a26d93 100644
--- a/src/render/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
@@ -54,7 +54,6 @@
#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DRender/qtechnique.h>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
#include <Qt3DRender/private/handle_types_p.h>
#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DCore/qaspectjob.h>
@@ -62,7 +61,6 @@
#include <Qt3DRender/private/pickboundingvolumejob_p.h>
#include <Qt3DRender/private/raycastingjob_p.h>
#include <Qt3DRender/private/rendersettings_p.h>
-#include <Qt3DRender/private/renderviewinitializerjob_p.h>
#include <Qt3DRender/private/expandboundingvolumejob_p.h>
#include <Qt3DRender/private/updateworldtransformjob_p.h>
#include <Qt3DRender/private/calcboundingvolumejob_p.h>
@@ -71,17 +69,22 @@
#include <Qt3DRender/private/updateworldboundingvolumejob_p.h>
#include <Qt3DRender/private/updatetreeenabledjob_p.h>
#include <Qt3DRender/private/platformsurfacefilter_p.h>
-#include <Qt3DRender/private/sendrendercapturejob_p.h>
#include <Qt3DRender/private/sendbuffercapturejob_p.h>
#include <Qt3DRender/private/genericlambdajob_p.h>
#include <Qt3DRender/private/updatemeshtrianglelistjob_p.h>
-#include <Qt3DRender/private/filtercompatibletechniquejob_p.h>
#include <Qt3DRender/private/updateskinningpalettejob_p.h>
#include <Qt3DRender/private/updateentitylayersjob_p.h>
-#include <Qt3DRender/private/renderercache_p.h>
-#include <Qt3DRender/private/texture_p.h>
-#include <Qt3DRender/private/glfence_p.h>
#include <Qt3DRender/private/shaderbuilder_p.h>
+#include <Qt3DRender/private/lightgatherer_p.h>
+#include <Qt3DRender/private/texture_p.h>
+#include <shaderparameterpack_p.h>
+#include <renderviewinitializerjob_p.h>
+#include <filtercompatibletechniquejob_p.h>
+#include <renderercache_p.h>
+#include <logging_p.h>
+#include <gl_handle_types_p.h>
+#include <glfence_p.h>
+#include <renderercache_p.h>
#include <QHash>
#include <QMatrix4x4>
@@ -124,24 +127,22 @@ class QAbstractShapeMesh;
struct GraphicsApiFilterData;
class QSceneImporter;
-#if QT_CONFIG(qt3d_profile_jobs)
namespace Debug {
class CommandExecuter;
}
-#endif
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;
@@ -149,15 +150,36 @@ class RenderStateSet;
class VSyncFrameAdvanceService;
class PickEventFilter;
class NodeManagers;
-class ShaderCache;
+class ResourceAccessor;
class UpdateLevelOfDetailJob;
typedef QSharedPointer<UpdateLevelOfDetailJob> UpdateLevelOfDetailJobPtr;
+template<typename T, typename ... Ts>
+class FilterEntityByComponentJob;
+template<typename T, typename ... Ts>
+using FilterEntityByComponentJobPtr = QSharedPointer<FilterEntityByComponentJob<T, Ts...>>;
+using ComputableEntityFilterPtr = FilterEntityByComponentJobPtr<Render::ComputeCommand, Render::Material>;
+using RenderableEntityFilterPtr = FilterEntityByComponentJobPtr<Render::GeometryRenderer, Render::Material>;
+
using SynchronizerJobPtr = GenericLambdaJobPtr<std::function<void()>>;
using SynchronizerPostFramePtr = GenericLambdaJobAndPostFramePtr<std::function<void ()>, std::function<void (Qt3DCore::QAspectManager *)>>;
-class Q_3DRENDERSHARED_PRIVATE_EXPORT Renderer : public AbstractRenderer
+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:
explicit Renderer(QRenderAspect::RenderType type);
@@ -168,6 +190,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;
@@ -198,8 +221,9 @@ public:
#if defined(QT_BUILD_INTERNAL)
void clearDirtyBits(BackendNodeDirtySet changes) override;
#endif
- bool shouldRender() override;
+ bool shouldRender() const override;
void skipNextFrame() override;
+ void jobsDone(Qt3DCore::QAspectManager *manager) override;
QVector<Qt3DCore::QAspectJobPtr> preRenderingJobs() override;
QVector<Qt3DCore::QAspectJobPtr> renderBinJobs() override;
@@ -224,8 +248,13 @@ public:
inline SynchronizerPostFramePtr introspectShadersJob() const { return m_introspectShaderJob; }
inline Qt3DCore::QAspectJobPtr bufferGathererJob() const { return m_bufferGathererJob; }
inline Qt3DCore::QAspectJobPtr textureGathererJob() const { return m_textureGathererJob; }
- inline Qt3DCore::QAspectJobPtr sendTextureChangesToFrontendJob() const { return m_sendTextureChangesToFrontendJob; }
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;
@@ -235,6 +264,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;
@@ -243,6 +273,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,
@@ -253,25 +284,27 @@ public:
void prepareCommandsSubmission(const QVector<RenderView *> &renderViews);
bool executeCommandsSubmission(const RenderView *rv);
bool updateVAOWithAttributes(Geometry *geometry,
- RenderCommand *command,
- Shader *shader,
+ const RenderCommand *command,
+ GLShader *shader,
bool forceUpdate);
bool requiresVAOAttributeUpdate(Geometry *geometry,
- RenderCommand *command) const;
+ 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<RenderBackendResourceAccessor> resourceAccessor() const override;
+
+
const GraphicsApiFilterData *contextInfo() const;
SubmissionContext *submissionContext() const;
inline RenderStateSet *defaultRenderState() const { return m_defaultRenderStateSet; }
- QList<QPair<QObject*, QMouseEvent>> pendingPickingEvents() const;
- QList<QKeyEvent> pendingKeyEvents() const;
-
- void addRenderCaptureSendRequest(Qt3DCore::QNodeId nodeId);
- const QVector<Qt3DCore::QNodeId> takePendingRenderCaptureSendRequests();
-
void enqueueRenderView(RenderView *renderView, int submitOrder);
bool isReadyToSubmit();
@@ -290,7 +323,7 @@ public:
QSurface *surface;
};
- ViewSubmissionResultData submitRenderViews(const QVector<Render::RenderView *> &renderViews);
+ ViewSubmissionResultData submitRenderViews(const QVector<RenderView *> &renderViews);
RendererCache *cache() { return &m_cache; }
void setScreen(QScreen *scr) override;
@@ -303,6 +336,7 @@ public:
private:
#endif
bool canRender() const;
+ Profiling::FrameProfiler *activeProfiler() const;
Qt3DCore::QServiceLocator *m_services;
NodeManagers *m_nodesManager;
@@ -337,8 +371,8 @@ private:
QAtomicInt m_exposed;
struct DirtyBits {
- BackendNodeDirtySet marked = {}; // marked dirty since last job build
- BackendNodeDirtySet remaining = {}; // remaining dirty after jobs have finished
+ BackendNodeDirtySet marked; // marked dirty since last job build
+ BackendNodeDirtySet remaining; // remaining dirty after jobs have finished
};
DirtyBits m_dirtyBits;
@@ -346,7 +380,6 @@ private:
QOpenGLContext *m_glContext;
QOpenGLContext *m_shareContext;
mutable QMutex m_shareContextMutex;
- ShaderCache *m_shaderCache;
PickBoundingVolumeJobPtr m_pickBoundingVolumeJob;
RayCastingJobPtr m_rayCastingJob;
@@ -361,13 +394,15 @@ private:
CalculateBoundingVolumeJobPtr m_calculateBoundingVolumeJob;
UpdateWorldBoundingVolumeJobPtr m_updateWorldBoundingVolumeJob;
UpdateTreeEnabledJobPtr m_updateTreeEnabledJob;
- SendRenderCaptureJobPtr m_sendRenderCaptureJob;
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<Qt3DCore::QNodeId> m_pendingRenderCaptureSendRequests;
@@ -380,11 +415,12 @@ private:
SynchronizerJobPtr m_bufferGathererJob;
SynchronizerJobPtr m_vaoGathererJob;
SynchronizerJobPtr m_textureGathererJob;
- SynchronizerPostFramePtr m_sendTextureChangesToFrontendJob;
SynchronizerJobPtr m_sendSetFenceHandlesToFrontendJob;
- SynchronizerJobPtr m_sendDisablesToFrontendJob;
SynchronizerPostFramePtr m_introspectShaderJob;
SynchronizerJobPtr m_syncLoadingJobs;
+ SynchronizerJobPtr m_cacheRenderableEntitiesJob;
+ SynchronizerJobPtr m_cacheComputableEntitiesJob;
+ SynchronizerJobPtr m_cacheLightsJob;
void lookForAbandonedVaos();
void lookForDirtyBuffers();
@@ -394,30 +430,30 @@ private:
void sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager);
void sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager);
void sendSetFenceHandlesToFrontend();
- void sendDisablesToFrontend();
+ void sendDisablesToFrontend(Qt3DCore::QAspectManager *manager);
QMutex m_abandonedVaosMutex;
QVector<HVao> m_abandonedVaos;
QVector<HBuffer> m_dirtyBuffers;
- QVector<HBuffer> m_downloadableBuffers;
+ QVector<Qt3DCore::QNodeId> m_downloadableBuffers;
QVector<HShader> m_dirtyShaders;
QVector<HTexture> m_dirtyTextures;
QVector<QPair<Texture::TextureUpdateInfo, Qt3DCore::QNodeIdVector>> m_updatedTextureProperties;
QVector<QPair<Qt3DCore::QNodeId, GLFence>> m_updatedSetFences;
- QVector<Qt3DCore::QNodeId> m_updatedDisables;
+ QVector<Qt3DCore::QNodeId> m_updatedDisableSubtreeEnablers;
Qt3DCore::QNodeIdVector m_textureIdsToCleanup;
QVector<ShaderBuilderUpdate> m_shaderBuilderUpdates;
bool m_ownedContext;
OffscreenSurfaceHelper *m_offscreenHelper;
+ GLResourceManagers *m_glResourceManagers;
QMutex m_offscreenSurfaceMutex;
-#if QT_CONFIG(qt3d_profile_jobs)
QScopedPointer<Qt3DRender::Debug::CommandExecuter> m_commandExecuter;
- friend class Qt3DRender::Debug::CommandExecuter;
-#endif
+
+ mutable QScopedPointer<Qt3DRender::Render::Profiling::FrameProfiler> m_frameProfiler;
#ifdef QT_BUILD_INTERNAL
friend class ::tst_Renderer;
@@ -429,11 +465,19 @@ private:
QVector<FrameGraphNode *> m_frameGraphLeaves;
QScreen *m_screen = nullptr;
+ QSharedPointer<ResourceAccessor> m_scene2DResourceAccessor;
+
+ Debug::ImGuiRenderer *m_imGuiRenderer;
+ QList<QPair<QObject *, QMouseEvent>> m_frameMouseEvents;
+ QList<QKeyEvent> m_frameKeyEvents;
+ QMutex m_frameEventsMutex;
+ 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/render/renderers/opengl/renderer/renderercache_p.h b/src/plugins/renderers/opengl/renderer/renderercache_p.h
index 0e9c5d3cd..6b3946002 100644
--- a/src/render/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
@@ -54,8 +54,9 @@
#include <Qt3DRender/QFrameGraphNode>
#include <Qt3DRender/private/entity_p.h>
-#include <Qt3DRender/private/renderviewjobutils_p.h>
+#include <renderviewjobutils_p.h>
#include <Qt3DRender/private/lightsource_p.h>
+#include <rendercommand_p.h>
QT_BEGIN_NAMESPACE
@@ -63,18 +64,24 @@ namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
struct RendererCache
{
struct LeafNodeData
{
QVector<Entity *> filterEntitiesByLayer;
MaterialParameterGathererData materialParameterGatherer;
- QVector<LightSource> gatheredLights;
- QVector<Entity *> renderableEntities;
- QVector<Entity *> computeEntities;
- EnvironmentLight* environmentLight;
+ EntityRenderCommandData renderCommandData;
};
+ // Shared amongst all RV cache
+ QVector<Entity *> renderableEntities;
+ QVector<Entity *> computeEntities;
+ QVector<LightSource> gatheredLights;
+ EnvironmentLight* environmentLight;
+
+ // Per RV cache
QHash<FrameGraphNode *, LeafNodeData> leafNodeCache;
QMutex *mutex() { return &m_mutex; }
@@ -83,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/render/renderers/opengl/renderer/renderqueue.cpp b/src/plugins/renderers/opengl/renderer/renderqueue.cpp
index bd9d3ee59..15b89da30 100644
--- a/src/render/renderers/opengl/renderer/renderqueue.cpp
+++ b/src/plugins/renderers/opengl/renderer/renderqueue.cpp
@@ -38,7 +38,7 @@
****************************************************************************/
#include "renderqueue_p.h"
-#include <Qt3DRender/private/renderview_p.h>
+#include <renderview_p.h>
#include <QThread>
QT_BEGIN_NAMESPACE
@@ -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/render/renderers/opengl/renderer/renderqueue_p.h b/src/plugins/renderers/opengl/renderer/renderqueue_p.h
index e565115f2..0dcf7b8ee 100644
--- a/src/render/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/render/renderers/opengl/renderer/renderview.cpp b/src/plugins/renderers/opengl/renderer/renderview.cpp
index aa9f4d1a5..f18f1a06a 100644
--- a/src/render/renderers/opengl/renderer/renderview.cpp
+++ b/src/plugins/renderers/opengl/renderer/renderview.cpp
@@ -50,17 +50,14 @@
#include <Qt3DRender/private/layerfilternode_p.h>
#include <Qt3DRender/private/qparameter_p.h>
#include <Qt3DRender/private/cameralens_p.h>
-#include <Qt3DRender/private/rendercommand_p.h>
#include <Qt3DRender/private/effect_p.h>
#include <Qt3DRender/private/entity_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/layer_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/renderpassfilternode_p.h>
#include <Qt3DRender/private/renderpass_p.h>
#include <Qt3DRender/private/geometryrenderer_p.h>
-#include <Qt3DRender/private/renderstateset_p.h>
#include <Qt3DRender/private/techniquefilternode_p.h>
#include <Qt3DRender/private/viewportnode_p.h>
#include <Qt3DRender/private/buffermanager_p.h>
@@ -68,6 +65,13 @@
#include <Qt3DRender/private/rendercapture_p.h>
#include <Qt3DRender/private/buffercapture_p.h>
#include <Qt3DRender/private/stringtoint_p.h>
+#include <Qt3DRender/private/renderlogging_p.h>
+#include <Qt3DRender/private/renderstateset_p.h>
+#include <rendercommand_p.h>
+#include <renderer_p.h>
+#include <graphicscontext_p.h>
+#include <submissioncontext_p.h>
+#include <glresourcemanagers_p.h>
#include <Qt3DCore/qentity.h>
#include <QtGui/qsurface.h>
#include <algorithm>
@@ -81,6 +85,7 @@ QT_BEGIN_NAMESPACE
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
namespace {
@@ -119,29 +124,29 @@ RenderView::StandardUniformsNameToTypeHash RenderView::initializeStandardUniform
{
RenderView::StandardUniformsNameToTypeHash setters;
- setters.insert(StringToInt::lookupId(QLatin1String("modelMatrix")), ModelMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("viewMatrix")), ViewMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("projectionMatrix")), ProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("modelView")), ModelViewMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("viewProjectionMatrix")), ViewProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("modelViewProjection")), ModelViewProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("mvp")), ModelViewProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseModelMatrix")), InverseModelMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseViewMatrix")), InverseViewMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseProjectionMatrix")), InverseProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseModelView")), InverseModelViewMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseViewProjectionMatrix")), InverseViewProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseModelViewProjection")), InverseModelViewProjectionMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("modelNormalMatrix")), ModelNormalMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("modelViewNormal")), ModelViewNormalMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("viewportMatrix")), ViewportMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("inverseViewportMatrix")), InverseViewportMatrix);
- setters.insert(StringToInt::lookupId(QLatin1String("aspectRatio")), AspectRatio);
- setters.insert(StringToInt::lookupId(QLatin1String("exposure")), Exposure);
- setters.insert(StringToInt::lookupId(QLatin1String("gamma")), Gamma);
- setters.insert(StringToInt::lookupId(QLatin1String("time")), Time);
- setters.insert(StringToInt::lookupId(QLatin1String("eyePosition")), EyePosition);
- setters.insert(StringToInt::lookupId(QLatin1String("skinningPalette[0]")), SkinningPalette);
+ 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;
}
@@ -211,7 +216,7 @@ UniformValue RenderView::standardUniformValue(RenderView::StandardUniform standa
return UniformValue(Matrix4x4(viewportMatrix.inverted()));
}
case AspectRatio:
- return float(m_surfaceSize.width()) / float(m_surfaceSize.height());
+ 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:
@@ -238,15 +243,19 @@ 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)
, m_frustumCulling(false)
+ , m_showDebugOverlay(false)
, m_memoryBarrier(QMemoryBarrier::None)
, m_environmentLight(nullptr)
{
@@ -280,10 +289,6 @@ RenderView::RenderView()
RenderView::~RenderView()
{
delete m_stateSet;
- for (RenderCommand *command : qAsConst(m_commands)) {
- delete command->m_stateSet;
- delete command;
- }
}
namespace {
@@ -291,7 +296,7 @@ namespace {
template<int SortType>
struct AdjacentSubRangeFinder
{
- static bool adjacentSubRange(RenderCommand *, RenderCommand *)
+ static bool adjacentSubRange(const RenderCommand &, const RenderCommand &)
{
Q_UNREACHABLE();
return false;
@@ -301,47 +306,47 @@ struct AdjacentSubRangeFinder
template<>
struct AdjacentSubRangeFinder<QSortPolicy::StateChangeCost>
{
- 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<QSortPolicy::BackToFront>
{
- 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<QSortPolicy::Material>
{
- 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_glShader == b.m_glShader;
}
};
template<>
struct AdjacentSubRangeFinder<QSortPolicy::FrontToBack>
{
- 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<QSortPolicy::Texture>
{
- 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<ShaderParameterPack::NamedResource> texturesA = a->m_parameterPack.textures();
- QVector<ShaderParameterPack::NamedResource> texturesB = b->m_parameterPack.textures();
+ QVector<ShaderParameterPack::NamedResource> texturesA = a.m_parameterPack.textures();
+ QVector<ShaderParameterPack::NamedResource> texturesB = b.m_parameterPack.textures();
if (texturesB.size() > texturesA.size())
qSwap(texturesA, texturesB);
@@ -356,7 +361,7 @@ struct AdjacentSubRangeFinder<QSortPolicy::Texture>
};
template<typename Predicate>
-int advanceUntilNonAdjacent(const QVector<RenderCommand *> &commands,
+int advanceUntilNonAdjacent(const QVector<RenderCommand> &commands,
const int beg, const int end, Predicate pred)
{
int i = beg + 1;
@@ -369,7 +374,7 @@ int advanceUntilNonAdjacent(const QVector<RenderCommand *> &commands,
}
-using CommandIt = QVector<RenderCommand *>::iterator;
+using CommandIt = QVector<RenderCommand>::iterator;
template<int SortType>
struct SubRangeSorter
@@ -387,8 +392,8 @@ struct SubRangeSorter<QSortPolicy::StateChangeCost>
{
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;
});
}
};
@@ -398,8 +403,8 @@ struct SubRangeSorter<QSortPolicy::BackToFront>
{
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;
});
}
};
@@ -409,9 +414,9 @@ struct SubRangeSorter<QSortPolicy::Material>
{
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;
+ // First we sort by shader
+ std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) {
+ return a.m_glShader > b.m_glShader;
});
}
};
@@ -421,8 +426,8 @@ struct SubRangeSorter<QSortPolicy::FrontToBack>
{
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;
});
}
};
@@ -432,9 +437,9 @@ struct SubRangeSorter<QSortPolicy::Texture>
{
static void sortSubRange(CommandIt begin, const CommandIt end)
{
- std::stable_sort(begin, end, [] (RenderCommand *a, RenderCommand *b) {
- QVector<ShaderParameterPack::NamedResource> texturesA = a->m_parameterPack.textures();
- QVector<ShaderParameterPack::NamedResource> texturesB = b->m_parameterPack.textures();
+ std::stable_sort(begin, end, [] (const RenderCommand &a, const RenderCommand &b) {
+ QVector<ShaderParameterPack::NamedResource> texturesA = a.m_parameterPack.textures();
+ QVector<ShaderParameterPack::NamedResource> texturesB = b.m_parameterPack.textures();
const int originalTextureASize = texturesA.size();
@@ -453,7 +458,7 @@ struct SubRangeSorter<QSortPolicy::Texture>
}
};
-int findSubRange(const QVector<RenderCommand *> &commands,
+int findSubRange(const QVector<RenderCommand> &commands,
const int begin, const int end,
const QSortPolicy::SortType sortType)
{
@@ -468,20 +473,22 @@ int findSubRange(const QVector<RenderCommand *> &commands,
return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder<QSortPolicy::FrontToBack>::adjacentSubRange);
case QSortPolicy::Texture:
return advanceUntilNonAdjacent(commands, begin, end, AdjacentSubRangeFinder<QSortPolicy::Texture>::adjacentSubRange);
+ case QSortPolicy::Uniform:
+ return end;
default:
Q_UNREACHABLE();
return end;
}
}
-void sortByMaterial(QVector<RenderCommand *> &commands, int begin, const int end)
+void sortByMaterial(QVector<RenderCommand> &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<QSortPolicy::Material>::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;
@@ -489,7 +496,7 @@ void sortByMaterial(QVector<RenderCommand *> &commands, int begin, const int end
}
}
-void sortCommandRange(QVector<RenderCommand *> &commands, int begin, const int end, const int level,
+void sortCommandRange(QVector<RenderCommand> &commands, int begin, const int end, const int level,
const QVector<Qt3DRender::QSortPolicy::SortType> &sortingTypes)
{
if (level >= sortingTypes.size())
@@ -514,6 +521,8 @@ void sortCommandRange(QVector<RenderCommand *> &commands, int begin, const int e
case QSortPolicy::Texture:
SubRangeSorter<QSortPolicy::Texture>::sortSubRange(commands.begin() + begin, commands.begin() + end);
break;
+ case QSortPolicy::Uniform:
+ break;
default:
Q_UNREACHABLE();
}
@@ -532,31 +541,37 @@ void sortCommandRange(QVector<RenderCommand *> &commands, int begin, const int e
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
+ // 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;
- 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_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();
+ 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::iterator it = uniforms.begin();
- const PackUniformHash::iterator end = uniforms.end();
+ PackUniformHash &uniforms = m_commands[j].m_parameterPack.m_uniforms;
- while (it != end) {
+ 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
@@ -564,12 +579,17 @@ void RenderView::sort()
// 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 UniformValue refValue = cachedUniforms.value(it.key());
- if (it.value() == refValue) {
- it = uniforms.erase(it);
+ 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 {
- cachedUniforms.insert(it.key(), it.value());
- ++it;
+ // Record updated value so that subsequent comparison
+ // for the next command will be made againts latest
+ // uniform value
+ cachedUniforms.insert(uniformNameId, newValue);
+ ++u;
}
}
++j;
@@ -619,20 +639,17 @@ void RenderView::addClearBuffers(const ClearBuffers *cb) {
}
// If we are there, we know that entity had a GeometryRenderer + Material
-QVector<RenderCommand *> RenderView::buildDrawRenderCommands(const QVector<Entity *> &entities) const
+EntityRenderCommandData RenderView::buildDrawRenderCommands(const QVector<Entity *> &entities,
+ int offset, int count) 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);
+ GLShaderManager *glShaderManager = m_renderer->glResourceManagers()->glShaderManager();
+ EntityRenderCommandData commands;
- QVector<RenderCommand *> commands;
- commands.reserve(entities.size());
+ commands.reserve(count);
- for (Entity *entity : entities) {
+ for (int i = 0; i < count; ++i) {
+ const int idx = offset + i;
+ Entity *entity = entities.at(idx);
GeometryRenderer *geometryRenderer = nullptr;
HGeometryRenderer geometryRendererHandle = entity->componentHandle<GeometryRenderer>();
@@ -645,135 +662,241 @@ QVector<RenderCommand *> RenderView::buildDrawRenderCommands(const QVector<Entit
const HMaterial materialHandle = entity->componentHandle<Material>();
const QVector<RenderPassParameterData> 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 = new RenderCommand();
- command->m_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 = 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 = 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_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<Qt3DCore::QNodeId> 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;
+ }
+ }
- // 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<LightSource> 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;
- });
- }
+ 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();
+ }
- 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);
+ // 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));
}
}
}
- // We reset the local data once we are done with it
- m_localData.setLocalData(nullptr);
-
return commands;
}
-QVector<RenderCommand *> RenderView::buildComputeRenderCommands(const QVector<Entity *> &entities) const
+EntityRenderCommandData RenderView::buildComputeRenderCommands(const QVector<Entity *> &entities,
+ int offset, int count) 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<RenderCommand *> commands;
- commands.reserve(entities.size());
- for (Entity *entity : entities) {
+ 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;
- if ((computeJob = entity->renderComponent<ComputeCommand>()) != nullptr
+ HComputeCommand computeCommandHandle = entity->componentHandle<ComputeCommand>();
+ 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<Material>();
const QVector<RenderPassParameterData> 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 = new RenderCommand();
+ RenderCommand command = {};
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());
// 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_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);
- 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<LightSource>(),
- nullptr);
- commands.append(command);
+ 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<LightSource> 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()
@@ -844,7 +967,7 @@ void RenderView::setStandardUniformValue(ShaderParameterPack &uniformPack,
}
void RenderView::setUniformBlockValue(ShaderParameterPack &uniformPack,
- Shader *shader,
+ GLShader *shader,
const ShaderUniformBlock &block,
const UniformValue &value) const
{
@@ -865,7 +988,7 @@ void RenderView::setUniformBlockValue(ShaderParameterPack &uniformPack,
}
void RenderView::setShaderStorageValue(ShaderParameterPack &uniformPack,
- Shader *shader,
+ GLShader *shader,
const ShaderStorageBlock &block,
const UniformValue &value) const
{
@@ -883,7 +1006,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();
@@ -908,7 +1031,6 @@ void RenderView::setDefaultUniformBlockShaderDataValue(ShaderParameterPack &unif
}
void RenderView::setShaderAndUniforms(RenderCommand *command,
- RenderPass *rPass,
ParameterInfoList &parameters,
Entity *entity,
const QVector<LightSource> &activeLightSources,
@@ -924,163 +1046,161 @@ 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<Shader, ShaderManager, HShader>(rPass->shaderProgram());
- Shader *shader = m_manager->data<Shader, ShaderManager>(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<int> uniformNamesIds = shader->uniformsNamesIds();
- const QVector<int> uniformBlockNamesIds = shader->uniformBlockNamesIds();
- const QVector<int> shaderStorageBlockNamesIds = shader->storageBlockNamesIds();
- const QVector<int> 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
+ 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<int> uniformNamesIds = shader->uniformsNamesIds();
+ const QVector<int> standardUniformNamesIds = shader->standardUniformNameIds();
+ const QVector<int> uniformBlockNamesIds = shader->uniformBlockNamesIds();
+ const QVector<int> shaderStorageBlockNamesIds = shader->storageBlockNamesIds();
+ const QVector<int> 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<QString, int> 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()) {
-
- // 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 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<Parameter, ParameterManager>(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<Qt3DCore::QNodeId>())) != 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
+ 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<Parameter, ParameterManager>(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<Qt3DCore::QNodeId>())) != 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;
-
- ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(light->shaderData());
- if (!shaderData)
- continue;
+ // Lights
- if (lightIdx == MAX_LIGHTS)
- break;
+ 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;
- // 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;
- }
- }
+ ShaderData *shaderData = m_manager->shaderDataManager()->lookupResource(light->shaderData());
+ if (!shaderData)
+ continue;
- if (uniformNamesIds.contains(LIGHT_COUNT_NAME_ID))
- setUniformValue(command->m_parameterPack, LIGHT_COUNT_NAME_ID, UniformValue(qMax((environmentLight ? 0 : 1), lightIdx)));
+ if (lightIdx == MAX_LIGHTS)
+ break;
- // 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
@@ -1113,6 +1233,7 @@ void RenderView::setIsDownloadBuffersEnable(bool isDownloadBuffersEnable)
m_isDownloadBuffersEnable = isDownloadBuffersEnable;
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/renderer/renderview_p.h b/src/plugins/renderers/opengl/renderer/renderview_p.h
index 71582336a..9d4e09df3 100644
--- a/src/render/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
@@ -55,7 +55,6 @@
#include <Qt3DRender/qparameter.h>
#include <Qt3DRender/qclearbuffers.h>
#include <Qt3DRender/qlayerfilter.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/clearbuffers_p.h>
#include <Qt3DRender/private/cameralens_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
@@ -69,8 +68,9 @@
#include <Qt3DRender/private/aligned_malloc_p.h>
+#include <renderer_p.h>
// TODO: Move out once this is all refactored
-#include <Qt3DRender/private/renderviewjobutils_p.h>
+#include <renderviewjobutils_p.h>
#include <QVector>
#include <QSurface>
@@ -85,31 +85,21 @@ 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<ShaderUniform, QVariant> ActivePropertyContent;
typedef QPair<QString, ActivePropertyContent > 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;
@@ -200,6 +190,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 &parameters) Q_DECL_NOTHROW { m_parameters = parameters; }
@@ -226,10 +218,19 @@ public:
RenderPassList passesAndParameters(ParameterInfoList *parameter, Entity *node, bool useDefaultMaterials = true);
- QVector<RenderCommand *> buildDrawRenderCommands(const QVector<Entity *> &entities) const;
- QVector<RenderCommand *> buildComputeRenderCommands(const QVector<Entity *> &entities) const;
- void setCommands(QVector<RenderCommand *> &commands) Q_DECL_NOTHROW { m_commands = commands; }
- QVector<RenderCommand *> commands() const Q_DECL_NOTHROW { return m_commands; }
+ EntityRenderCommandData buildDrawRenderCommands(const QVector<Entity *> &entities,
+ int offset, int count) const;
+ EntityRenderCommandData buildComputeRenderCommands(const QVector<Entity *> &entities,
+ int offset, int count) const;
+
+
+ void updateRenderCommand(EntityRenderCommandData *renderCommandData,
+ int offset, int count);
+
+
+ void setCommands(const QVector<RenderCommand> &commands) Q_DECL_NOTHROW { m_commands = commands; }
+ QVector<RenderCommand> &commands() { return m_commands; }
+ QVector<RenderCommand> commands() const { return m_commands; }
void setAttachmentPack(const AttachmentPack &pack) { m_attachmentPack = pack; }
const AttachmentPack &attachmentPack() const { return m_attachmentPack; }
@@ -290,7 +291,6 @@ public:
private:
void setShaderAndUniforms(RenderCommand *command,
- RenderPass *pass,
ParameterInfoList &parameters,
Entity *entity,
const QVector<LightSource> &activeLightSources,
@@ -325,15 +325,13 @@ 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<Qt3DCore::QNodeId> m_insertFenceIds;
QVector<QWaitFenceData> 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<RenderCommand *> m_commands;
+ QVector<RenderCommand> m_commands;
mutable QVector<LightSource> m_lightSources;
EnvironmentLight *m_environmentLight;
@@ -380,22 +378,23 @@ 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;
};
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
QT_END_NAMESPACE
-#endif // QT3DRENDER_RENDER_RENDERVIEW_H
+#endif // QT3DRENDER_RENDER_OPENGL_ENDERVIEW_H
diff --git a/src/render/renderers/opengl/renderer/renderviewbuilder.cpp b/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp
index 83fab301a..1e16209c6 100644
--- a/src/render/renderers/opengl/renderer/renderviewbuilder.cpp
+++ b/src/plugins/renderers/opengl/renderer/renderviewbuilder.cpp
@@ -46,22 +46,78 @@ 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
// depending on the platform/CPU/nbr of cores
-const int RenderViewBuilder::m_optimalParallelJobCount = std::max(std::min(4, QThread::idealThreadCount()), 2);
+const int RenderViewBuilder::m_optimalParallelJobCount = QThread::idealThreadCount();
namespace {
-class SyncRenderViewCommandBuilders
+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 SyncRenderViewCommandBuilders(const RenderViewInitializerJobPtr &renderViewJob,
- const QVector<RenderViewBuilderJobPtr> &renderViewBuilderJobs,
- Renderer *renderer)
+ explicit SyncPreCommandBuilding(RenderViewInitializerJobPtr renderViewInitializerJob,
+ const QVector<RenderViewCommandBuilderJobPtr> &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<RenderViewCommandBuilderJobPtr> m_renderViewCommandBuilderJobs;
+ Renderer *m_renderer;
+ FrameGraphNode *m_leafNode;
+};
+
+class SyncRenderViewPostCommandUpdate
+{
+public:
+ explicit SyncRenderViewPostCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob,
+ const QVector<RenderViewCommandUpdaterJobPtr> &renderViewCommandUpdateJobs,
+ Renderer *renderer)
: m_renderViewJob(renderViewJob)
- , m_renderViewBuilderJobs(renderViewBuilderJobs)
+ , m_renderViewCommandUpdaterJobs(renderViewCommandUpdateJobs)
, m_renderer(renderer)
{}
@@ -70,20 +126,16 @@ public:
// Append all the commands and sort them
RenderView *rv = m_renderViewJob->renderView();
- int totalCommandCount = 0;
- for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs))
- totalCommandCount += renderViewCommandBuilder->commands().size();
-
- QVector<RenderCommand *> commands;
- commands.reserve(totalCommandCount);
+ const EntityRenderCommandDataPtr commandData = m_renderViewCommandUpdaterJobs.first()->renderables();
- // Reduction
- for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs))
- commands += std::move(renderViewCommandBuilder->commands());
- rv->setCommands(commands);
+ if (commandData) {
+ const QVector<RenderCommand> commands = std::move(commandData->commands);
+ rv->setCommands(commands);
- // Sort the commands
- rv->sort();
+ // 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());
@@ -91,15 +143,15 @@ public:
private:
RenderViewInitializerJobPtr m_renderViewJob;
- QVector<RenderViewBuilderJobPtr> m_renderViewBuilderJobs;
+ QVector<RenderViewCommandUpdaterJobPtr> 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 +172,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<MaterialParameterGathererJobPtr> &materialGathererJobs,
- const QVector<RenderViewBuilderJobPtr> &renderViewBuilderJobs)
+ explicit SyncRenderViewPostInitialization(const RenderViewInitializerJobPtr &renderViewJob,
+ const FrustumCullingJobPtr &frustumCullingJob,
+ const FilterLayerEntityJobPtr &filterEntityByLayerJob,
+ const FilterProximityDistanceJobPtr &filterProximityJob,
+ const QVector<MaterialParameterGathererJobPtr> &materialGathererJobs,
+ const QVector<RenderViewCommandUpdaterJobPtr> &renderViewCommandUpdaterJobs,
+ const QVector<RenderViewCommandBuilderJobPtr> &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 +208,10 @@ public:
materialGatherer->setTechniqueFilter(const_cast<TechniqueFilter *>(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 +224,31 @@ private:
FilterLayerEntityJobPtr m_filterEntityByLayerJob;
FilterProximityDistanceJobPtr m_filterProximityJob;
QVector<MaterialParameterGathererJobPtr> m_materialGathererJobs;
- QVector<RenderViewBuilderJobPtr> m_renderViewBuilderJobs;
+ QVector<RenderViewCommandUpdaterJobPtr> m_renderViewCommandUpdaterJobs;
+ QVector<RenderViewCommandBuilderJobPtr> m_renderViewCommandBuilderJobs;
};
-class SyncRenderCommandBuilding
+class SyncRenderViewPreCommandUpdate
{
public:
- explicit SyncRenderCommandBuilding(const RenderViewInitializerJobPtr &renderViewJob,
- const FrustumCullingJobPtr &frustumCullingJob,
- const FilterProximityDistanceJobPtr &filterProximityJob,
- const QVector<MaterialParameterGathererJobPtr> &materialGathererJobs,
- const QVector<RenderViewBuilderJobPtr> &renderViewBuilderJobs,
- Renderer *renderer,
- FrameGraphNode *leafNode)
+ explicit SyncRenderViewPreCommandUpdate(const RenderViewInitializerJobPtr &renderViewJob,
+ const FrustumCullingJobPtr &frustumCullingJob,
+ const FilterProximityDistanceJobPtr &filterProximityJob,
+ const QVector<MaterialParameterGathererJobPtr> &materialGathererJobs,
+ const QVector<RenderViewCommandUpdaterJobPtr> &renderViewCommandUpdaterJobs,
+ const QVector<RenderViewCommandBuilderJobPtr> &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 +258,44 @@ public:
RenderView *rv = m_renderViewJob->renderView();
if (!rv->noDraw()) {
- QVector<Entity *> renderableEntities;
- const bool isDraw = !rv->isCompute();
- QMutexLocker lock(m_renderer->cache()->mutex());
- const auto& cacheData = m_renderer->cache()->leafNodeCache.value(m_leafNode);
+ ///////// CACHE LOCKED ////////////
+ // Retrieve Data from Cache
+ RendererCache *cache = m_renderer->cache();
+ QMutexLocker lock(cache->mutex());
+ Q_ASSERT(cache->leafNodeCache.contains(m_leafNode));
- if (isDraw)
- renderableEntities = cacheData.renderableEntities;
- else
- renderableEntities = cacheData.computeEntities;
-
- const QVector<Entity *> filteredEntities = cacheData.filterEntitiesByLayer;
- QVector<LightSource> lightSources = cacheData.gatheredLights;
- rv->setEnvironmentLight(cacheData.environmentLight);
+ 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<Entity *> filteredEntities = dataCacheForLeaf.filterEntitiesByLayer;
+ QVector<Entity *> renderableEntities = isDraw ? cache->renderableEntities : cache->computeEntities;
+ QVector<LightSource> 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
@@ -229,22 +313,52 @@ public:
if (rv->frustumCulling())
renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_frustumCullingJob->visibleEntities());
// Filter out entities which didn't satisfy proximity filtering
- renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_filterProximityJob->filteredEntities());
+ if (!rv->proximityFilterIds().empty())
+ renderableEntities = RenderViewBuilder::entitiesInSubset(renderableEntities, m_filterProximityJob->filteredEntities());
}
- // Split among the number of command builders
- int i = 0;
- const int m = RenderViewBuilder::optimalJobCount() - 1;
- const int packetSize = renderableEntities.size() / RenderViewBuilder::optimalJobCount();
- while (i < m) {
- const RenderViewBuilderJobPtr renderViewCommandBuilder = m_renderViewBuilderJobs.at(i);
- renderViewCommandBuilder->setRenderables(renderableEntities.mid(i * packetSize, packetSize));
- ++i;
+ // 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;
}
- 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);
+
+ // 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);
}
}
}
@@ -254,9 +368,11 @@ private:
FrustumCullingJobPtr m_frustumCullingJob;
FilterProximityDistanceJobPtr m_filterProximityJob;
QVector<MaterialParameterGathererJobPtr> m_materialGathererJobs;
- QVector<RenderViewBuilderJobPtr> m_renderViewBuilderJobs;
+ QVector<RenderViewCommandUpdaterJobPtr> m_renderViewCommandUpdaterJobs;
+ QVector<RenderViewCommandBuilderJobPtr> m_renderViewCommandBuilderJobs;
Renderer *m_renderer;
FrameGraphNode *m_leafNode;
+ bool m_fullRebuild;
};
class SetClearDrawBufferIndex
@@ -335,84 +451,6 @@ private:
FrameGraphNode *m_leafNode;
};
-class SyncLightsGatherer
-{
-public:
- explicit SyncLightsGatherer(LightGathererPtr gatherJob,
- Renderer *renderer,
- FrameGraphNode *leafNode)
- : m_gatherJob(gatherJob)
- , m_renderer(renderer)
- , m_leafNode(leafNode)
- {
- }
-
- void operator()()
- {
- QMutexLocker lock(m_renderer->cache()->mutex());
- RendererCache::LeafNodeData &dataCacheForLeaf = m_renderer->cache()->leafNodeCache[m_leafNode];
- dataCacheForLeaf.gatheredLights = m_gatherJob->lights();
- dataCacheForLeaf.environmentLight = m_gatherJob->takeEnvironmentLight();
- }
-
-private:
- LightGathererPtr m_gatherJob;
- Renderer *m_renderer;
- FrameGraphNode *m_leafNode;
-};
-
-class SyncRenderableEntities
-{
-public:
- explicit SyncRenderableEntities(RenderableEntityFilterPtr gatherJob,
- Renderer *renderer,
- FrameGraphNode *leafNode)
- : m_gatherJob(gatherJob)
- , m_renderer(renderer)
- , m_leafNode(leafNode)
- {
- }
-
- void operator()()
- {
- 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());
- }
-
-private:
- RenderableEntityFilterPtr m_gatherJob;
- Renderer *m_renderer;
- FrameGraphNode *m_leafNode;
-};
-
-class SyncComputableEntities
-{
-public:
- explicit SyncComputableEntities(ComputableEntityFilterPtr gatherJob,
- Renderer *renderer,
- FrameGraphNode *leafNode)
- : m_gatherJob(gatherJob)
- , m_renderer(renderer)
- , m_leafNode(leafNode)
- {
- }
-
- void operator()()
- {
- 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());
- }
-
-private:
- ComputableEntityFilterPtr m_gatherJob;
- Renderer *m_renderer;
- FrameGraphNode *m_leafNode;
-};
-
} // anonymous
RenderViewBuilder::RenderViewBuilder(Render::FrameGraphNode *leafNode, int renderViewIndex, Renderer *renderer)
@@ -421,13 +459,11 @@ RenderViewBuilder::RenderViewBuilder(Render::FrameGraphNode *leafNode, int rende
, m_renderer(renderer)
, m_layerCacheNeedsToBeRebuilt(false)
, m_materialGathererCacheNeedsToBeRebuilt(false)
- , 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())
@@ -444,54 +480,49 @@ FilterLayerEntityJobPtr RenderViewBuilder::filterEntityByLayerJob() const
return m_filterEntityByLayerJob;
}
-LightGathererPtr RenderViewBuilder::lightGathererJob() const
+FrustumCullingJobPtr RenderViewBuilder::frustumCullingJob() const
{
- return m_lightGathererJob;
+ return m_frustumCullingJob;
}
-RenderableEntityFilterPtr RenderViewBuilder::renderableEntityFilterJob() const
+QVector<RenderViewCommandUpdaterJobPtr> RenderViewBuilder::renderViewCommandUpdaterJobs() const
{
- return m_renderableEntityFilterJob;
+ return m_renderViewCommandUpdaterJobs;
}
-ComputableEntityFilterPtr RenderViewBuilder::computableEntityFilterJob() const
+QVector<RenderViewCommandBuilderJobPtr> RenderViewBuilder::renderViewCommandBuilderJobs() const
{
- return m_computableEntityFilterJob;
+ return m_renderViewCommandBuilderJobs;
}
-FrustumCullingJobPtr RenderViewBuilder::frustumCullingJob() const
+QVector<MaterialParameterGathererJobPtr> RenderViewBuilder::materialGathererJobs() const
{
- return m_frustumCullingJob;
+ return m_materialGathererJobs;
}
-QVector<RenderViewBuilderJobPtr> RenderViewBuilder::renderViewBuilderJobs() const
+SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostInitializationJob() const
{
- return m_renderViewBuilderJobs;
+ return m_syncRenderViewPostInitializationJob;
}
-QVector<MaterialParameterGathererJobPtr> RenderViewBuilder::materialGathererJobs() const
+SynchronizerJobPtr RenderViewBuilder::syncPreFrustumCullingJob() const
{
- return m_materialGathererJobs;
+ return m_syncPreFrustumCullingJob;
}
-SynchronizerJobPtr RenderViewBuilder::syncRenderViewInitializationJob() const
+SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandBuildingJob() const
{
- return m_syncRenderViewInitializationJob;
+ return m_syncRenderViewPreCommandBuildingJob;
}
-SynchronizerJobPtr RenderViewBuilder::syncFrustumCullingJob() const
+SynchronizerJobPtr RenderViewBuilder::syncRenderViewPreCommandUpdateJob() const
{
- return m_syncFrustumCullingJob;
+ return m_syncRenderViewPreCommandUpdateJob;
}
-SynchronizerJobPtr RenderViewBuilder::syncRenderCommandBuildingJob() const
+SynchronizerJobPtr RenderViewBuilder::syncRenderViewPostCommandUpdateJob() const
{
- return m_syncRenderCommandBuildingJob;
-}
-
-SynchronizerJobPtr RenderViewBuilder::syncRenderViewCommandBuildersJob() const
-{
- return m_syncRenderViewCommandBuildersJob;
+ return m_syncRenderViewPostCommandUpdateJob;
}
SynchronizerJobPtr RenderViewBuilder::setClearDrawBufferIndexJob() const
@@ -517,37 +548,21 @@ FilterProximityDistanceJobPtr RenderViewBuilder::filterProximityJob() const
void RenderViewBuilder::prepareJobs()
{
// Init what we can here
- EntityManager *entityManager = m_renderer->nodeManagers()->renderNodesManager();
m_filterProximityJob->setManager(m_renderer->nodeManagers());
m_frustumCullingJob->setRoot(m_renderer->sceneRoot());
- if (m_lightsCacheNeedsToBeRebuilt) {
- m_lightGathererJob = Render::LightGathererPtr::create();
- m_lightGathererJob->setManager(entityManager);
-
- m_cacheLightsJob = SynchronizerJobPtr::create(SyncLightsGatherer(m_lightGathererJob, m_renderer, m_leafNode),
- JobTypes::EntityComponentTypeFiltering);
- m_cacheLightsJob->addDependency(m_lightGathererJob);
- }
-
- if (m_renderableCacheNeedsToBeRebuilt) {
- m_renderableEntityFilterJob = RenderableEntityFilterPtr::create();
- m_renderableEntityFilterJob->setManager(entityManager);
-
- m_cacheRenderableEntitiesJob = SynchronizerJobPtr::create(
- SyncRenderableEntities(m_renderableEntityFilterJob, m_renderer, m_leafNode),
- JobTypes::EntityComponentTypeFiltering);
- m_cacheRenderableEntitiesJob->addDependency(m_renderableEntityFilterJob);
- }
-
- if (m_computableCacheNeedsToBeRebuilt) {
- m_computableEntityFilterJob = ComputableEntityFilterPtr::create();
- m_computableEntityFilterJob->setManager(entityManager);
+ if (m_renderCommandCacheNeedsToBeRebuilt) {
- m_cacheComputableEntitiesJob = SynchronizerJobPtr::create(
- SyncComputableEntities(m_computableEntityFilterJob, m_renderer, m_leafNode),
- JobTypes::EntityComponentTypeFiltering);
- m_cacheComputableEntitiesJob->addDependency(m_computableEntityFilterJob);
+ m_renderViewCommandBuilderJobs.reserve(RenderViewBuilder::m_optimalParallelJobCount);
+ for (auto i = 0; i < RenderViewBuilder::m_optimalParallelJobCount; ++i) {
+ auto renderViewCommandBuilder = Render::OpenGL::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);
@@ -556,12 +571,11 @@ void RenderViewBuilder::prepareJobs()
// 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::OpenGL::RenderViewCommandUpdaterJobPtr::create();
+ renderViewCommandUpdater->setRenderer(m_renderer);
+ m_renderViewCommandUpdaterJobs.push_back(renderViewCommandUpdater);
}
if (m_materialGathererCacheNeedsToBeRebuilt) {
@@ -571,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));
@@ -582,7 +596,7 @@ void RenderViewBuilder::prepareJobs()
m_syncMaterialGathererJob = SynchronizerJobPtr::create(SyncMaterialParameterGatherer(m_materialGathererJobs,
m_renderer,
m_leafNode),
- JobTypes::SyncMaterialGatherer);
+ JobTypes::SyncMaterialGatherer);
}
if (m_layerCacheNeedsToBeRebuilt) {
@@ -594,34 +608,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<Qt3DCore::QAspectJobPtr> RenderViewBuilder::buildJobHierachy() const
{
QVector<Qt3DCore::QAspectJobPtr> jobs;
- jobs.reserve(m_materialGathererJobs.size() + m_renderViewBuilderJobs.size() + 11);
+ jobs.reserve(m_materialGathererJobs.size() + m_renderViewCommandUpdaterJobs.size() + 11);
// Set dependencies
@@ -629,97 +646,97 @@ QVector<Qt3DCore::QAspectJobPtr> 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());
-
- for (const auto &renderViewCommandBuilder : qAsConst(m_renderViewBuilderJobs)) {
- renderViewCommandBuilder->addDependency(m_syncRenderCommandBuildingJob);
- m_syncRenderViewCommandBuildersJob->addDependency(renderViewCommandBuilder);
+ 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_syncRenderViewCommandBuildersJob);
+ m_renderer->frameCleanupJob()->addDependency(m_syncRenderViewPostCommandUpdateJob);
m_renderer->frameCleanupJob()->addDependency(m_setClearDrawBufferIndexJob);
// Add jobs
jobs.push_back(m_renderViewJob); // Step 1
- if (m_lightsCacheNeedsToBeRebuilt) {
- jobs.push_back(m_lightGathererJob); // Step 1
- jobs.push_back(m_cacheLightsJob);
- m_syncRenderCommandBuildingJob->addDependency(m_cacheLightsJob);
- }
+ jobs.push_back(m_syncRenderViewPostInitializationJob); // Step 2
- if (m_renderableCacheNeedsToBeRebuilt) {
- jobs.push_back(m_renderableEntityFilterJob); // Step 1
- jobs.push_back(m_cacheRenderableEntitiesJob);
- m_syncRenderCommandBuildingJob->addDependency(m_cacheRenderableEntitiesJob);
- }
+ if (m_renderCommandCacheNeedsToBeRebuilt) { // Step 3
+ m_syncRenderViewPreCommandBuildingJob->addDependency(m_renderer->cacheComputableEntitiesJob());
+ m_syncRenderViewPreCommandBuildingJob->addDependency(m_renderer->cacheRenderableEntitiesJob());
+ m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncRenderViewPostInitializationJob);
- 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);
- }
+ if (m_materialGathererCacheNeedsToBeRebuilt)
+ m_syncRenderViewPreCommandBuildingJob->addDependency(m_syncMaterialGathererJob);
- jobs.push_back(m_syncRenderViewInitializationJob); // Step 2
+ 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;
}
@@ -754,34 +771,14 @@ bool RenderViewBuilder::materialGathererCacheNeedsToBeRebuilt() const
return m_materialGathererCacheNeedsToBeRebuilt;
}
-void RenderViewBuilder::setRenderableCacheNeedsToBeRebuilt(bool needsToBeRebuilt)
-{
- m_renderableCacheNeedsToBeRebuilt = needsToBeRebuilt;
-}
-
-bool RenderViewBuilder::renderableCacheNeedsToBeRebuilt() const
-{
- return m_renderableCacheNeedsToBeRebuilt;
-}
-
-void RenderViewBuilder::setComputableCacheNeedsToBeRebuilt(bool needsToBeRebuilt)
-{
- m_computableCacheNeedsToBeRebuilt = needsToBeRebuilt;
-}
-
-bool RenderViewBuilder::computableCacheNeedsToBeRebuilt() const
+void RenderViewBuilder::setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt)
{
- return m_computableCacheNeedsToBeRebuilt;
+ m_renderCommandCacheNeedsToBeRebuilt = needsToBeRebuilt;
}
-void RenderViewBuilder::setLightGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt)
+bool RenderViewBuilder::renderCommandCacheNeedsToBeRebuilt() const
{
- m_lightsCacheNeedsToBeRebuilt = needsToBeRebuilt;
-}
-
-bool RenderViewBuilder::lightGathererCacheNeedsToBeRebuilt() const
-{
- return m_lightsCacheNeedsToBeRebuilt;
+ return m_renderCommandCacheNeedsToBeRebuilt;
}
int RenderViewBuilder::optimalJobCount()
@@ -800,6 +797,8 @@ QVector<Entity *> RenderViewBuilder::entitiesInSubset(const QVector<Entity *> &e
return intersection;
}
+} // OpenGL
+
} // Render
} // Qt3DRender
diff --git a/src/render/renderers/opengl/renderer/renderviewbuilder_p.h b/src/plugins/renderers/opengl/renderer/renderviewbuilder_p.h
index e223a5f1e..98202670e 100644
--- a/src/render/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
@@ -53,16 +53,16 @@
#include <functional>
#include <Qt3DCore/qaspectjob.h>
-#include <Qt3DRender/private/filterentitybycomponentjob_p.h>
#include <Qt3DRender/private/filterlayerentityjob_p.h>
#include <Qt3DRender/private/genericlambdajob_p.h>
-#include <Qt3DRender/private/materialparametergathererjob_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
-#include <Qt3DRender/private/renderviewbuilderjob_p.h>
-#include <Qt3DRender/private/renderview_p.h>
#include <Qt3DRender/private/frustumcullingjob_p.h>
-#include <Qt3DRender/private/lightgatherer_p.h>
#include <Qt3DRender/private/filterproximitydistancejob_p.h>
+#include <renderviewcommandbuilderjob_p.h>
+#include <renderviewcommandupdaterjob_p.h>
+#include <materialparametergathererjob_p.h>
+#include <renderviewbuilderjob_p.h>
+#include <renderview_p.h>
QT_BEGIN_NAMESPACE
@@ -70,11 +70,11 @@ namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
class Renderer;
using SynchronizerJobPtr = GenericLambdaJobPtr<std::function<void()>>;
-using ComputableEntityFilterPtr = FilterEntityByComponentJobPtr<Render::ComputeCommand, Render::Material>;
-using RenderableEntityFilterPtr = FilterEntityByComponentJobPtr<Render::GeometryRenderer, Render::Material>;
class Q_AUTOTEST_EXPORT RenderViewBuilder
{
@@ -83,16 +83,15 @@ public:
RenderViewInitializerJobPtr renderViewJob() const;
FilterLayerEntityJobPtr filterEntityByLayerJob() const;
- LightGathererPtr lightGathererJob() const;
- RenderableEntityFilterPtr renderableEntityFilterJob() const;
- ComputableEntityFilterPtr computableEntityFilterJob() const;
FrustumCullingJobPtr frustumCullingJob() const;
- QVector<RenderViewBuilderJobPtr> renderViewBuilderJobs() const;
+ QVector<RenderViewCommandBuilderJobPtr> renderViewCommandBuilderJobs() const;
+ QVector<RenderViewCommandUpdaterJobPtr> renderViewCommandUpdaterJobs() const;
QVector<MaterialParameterGathererJobPtr> 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;
@@ -108,15 +107,8 @@ public:
bool layerCacheNeedsToBeRebuilt() const;
void setMaterialGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt);
bool materialGathererCacheNeedsToBeRebuilt() const;
-
- void setRenderableCacheNeedsToBeRebuilt(bool needsToBeRebuilt);
- bool renderableCacheNeedsToBeRebuilt() const;
-
- void setComputableCacheNeedsToBeRebuilt(bool needsToBeRebuilt);
- bool computableCacheNeedsToBeRebuilt() const;
-
- void setLightGathererCacheNeedsToBeRebuilt(bool needsToBeRebuilt);
- bool lightGathererCacheNeedsToBeRebuilt() const;
+ void setRenderCommandCacheNeedsToBeRebuilt(bool needsToBeRebuilt);
+ bool renderCommandCacheNeedsToBeRebuilt() const;
static int optimalJobCount();
static QVector<Entity *> entitiesInSubset(const QVector<Entity *> &entities, const QVector<Entity *> &subset);
@@ -127,39 +119,34 @@ private:
Renderer *m_renderer;
bool m_layerCacheNeedsToBeRebuilt;
bool m_materialGathererCacheNeedsToBeRebuilt;
- bool m_lightsCacheNeedsToBeRebuilt;
- bool m_renderableCacheNeedsToBeRebuilt;
- bool m_computableCacheNeedsToBeRebuilt;
+ bool m_renderCommandCacheNeedsToBeRebuilt;
RenderViewInitializerJobPtr m_renderViewJob;
FilterLayerEntityJobPtr m_filterEntityByLayerJob;
- LightGathererPtr m_lightGathererJob;
- RenderableEntityFilterPtr m_renderableEntityFilterJob;
- ComputableEntityFilterPtr m_computableEntityFilterJob;
FrustumCullingJobPtr m_frustumCullingJob;
- QVector<RenderViewBuilderJobPtr> m_renderViewBuilderJobs;
+ QVector<RenderViewCommandBuilderJobPtr> m_renderViewCommandBuilderJobs;
+ QVector<RenderViewCommandUpdaterJobPtr> m_renderViewCommandUpdaterJobs;
QVector<MaterialParameterGathererJobPtr> 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;
FilterProximityDistanceJobPtr m_filterProximityJob;
- SynchronizerJobPtr m_cacheRenderableEntitiesJob;
- SynchronizerJobPtr m_cacheComputableEntitiesJob;
- SynchronizerJobPtr m_cacheLightsJob;
-
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/render/renderers/opengl/renderer/shaderparameterpack.cpp b/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp
index 39ecf19ee..c51595bb7 100644
--- a/src/render/renderers/opengl/renderer/shaderparameterpack.cpp
+++ b/src/plugins/renderers/opengl/renderer/shaderparameterpack.cpp
@@ -39,7 +39,7 @@
#include "shaderparameterpack_p.h"
-#include <Qt3DRender/private/graphicscontext_p.h>
+#include <graphicscontext_p.h>
#include <Qt3DRender/private/texture_p.h>
#include <QOpenGLShaderProgram>
@@ -52,10 +52,10 @@ QT_BEGIN_NAMESPACE
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
ShaderParameterPack::~ShaderParameterPack()
{
- m_uniforms.clear();
}
void ShaderParameterPack::setUniform(const int glslNameId, const UniformValue &val)
@@ -105,6 +105,7 @@ void ShaderParameterPack::setSubmissionUniform(const ShaderUniform &uniform)
m_submissionUniforms.push_back(uniform);
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/renderer/shaderparameterpack_p.h b/src/plugins/renderers/opengl/renderer/shaderparameterpack_p.h
index 39cbcd724..31ef4f7ea 100644
--- a/src/render/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
@@ -57,8 +57,8 @@
#include <QOpenGLShaderProgram>
#include <Qt3DCore/qnodeid.h>
#include <Qt3DRender/private/renderlogging_p.h>
-#include <Qt3DRender/private/shadervariables_p.h>
#include <Qt3DRender/private/uniform_p.h>
+#include <shadervariables_p.h>
QT_BEGIN_NAMESPACE
@@ -66,6 +66,7 @@ class QOpenGLShaderProgram;
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
class GraphicsContext;
@@ -75,17 +76,66 @@ struct BlockToUBO {
bool m_needsUpdate;
QHash<QString, QVariant> 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)
-typedef QHash<int, UniformValue> PackUniformHash;
+struct PackUniformHash
+{
+ QVector<int> keys;
+ QVector<UniformValue> 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
{
@@ -156,13 +206,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/render/renderers/opengl/renderer/shadervariables_p.h b/src/plugins/renderers/opengl/renderer/shadervariables_p.h
index e0fa07dff..94ea9b7e0 100644
--- a/src/render/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,9 +77,9 @@ 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 ShaderUniform
+struct Q_AUTOTEST_EXPORT ShaderUniform
{
ShaderUniform()
: m_nameId(-1)
@@ -103,9 +105,9 @@ struct 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 ShaderUniformBlock
+struct Q_AUTOTEST_EXPORT ShaderUniformBlock
{
ShaderUniformBlock()
: m_nameId(-1)
@@ -122,9 +124,9 @@ struct 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 ShaderStorageBlock
+struct Q_AUTOTEST_EXPORT ShaderStorageBlock
{
ShaderStorageBlock()
: m_nameId(-1)
@@ -141,7 +143,9 @@ struct 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/render/renderers/opengl/textures/gltexture.cpp b/src/plugins/renderers/opengl/textures/gltexture.cpp
index 1b5a972ec..11b43e085 100644
--- a/src/render/renderers/opengl/textures/gltexture.cpp
+++ b/src/plugins/renderers/opengl/textures/gltexture.cpp
@@ -52,8 +52,8 @@
#include <Qt3DRender/qtextureimagedata.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/qabstracttexture_p.h>
-#include <Qt3DRender/private/renderbuffer_p.h>
#include <Qt3DRender/private/qtextureimagedata_p.h>
+#include <renderbuffer_p.h>
#if !defined(QT_OPENGL_ES_2)
#include <QOpenGLFunctions_3_1>
@@ -66,6 +66,7 @@ using namespace Qt3DCore;
namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
namespace {
@@ -232,11 +233,9 @@ void GLTexture::loadTextureDataFromImages()
GLTexture::TextureUpdateInfo GLTexture::createOrUpdateGLTexture()
{
TextureUpdateInfo textureInfo;
- m_properties.status = QAbstractTexture::Error;
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) {
@@ -269,17 +268,17 @@ GLTexture::TextureUpdateInfo GLTexture::createOrUpdateGLTexture()
// 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;
+ // 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
@@ -768,6 +767,7 @@ void GLTexture::introspectPropertiesFromSharedTextureId()
gl->glBindTexture(m_properties.target, 0);
}
+} // namespace OpenGL
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/renderers/opengl/textures/gltexture_p.h b/src/plugins/renderers/opengl/textures/gltexture_p.h
index ca851712d..576ef5001 100644
--- a/src/render/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 APITexture, class APITextureImage>
+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/render/renderers/opengl/textures/renderbuffer.cpp b/src/plugins/renderers/opengl/textures/renderbuffer.cpp
index 19d8cfcd7..05d6bd1fa 100644
--- a/src/render/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/render/renderers/opengl/textures/renderbuffer_p.h b/src/plugins/renderers/opengl/textures/renderbuffer_p.h
index 7dc62492a..16fc90e67 100644
--- a/src/render/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/renderers/opengl/textures/textures.pri b/src/plugins/renderers/opengl/textures/textures.pri
index 42ffff7eb..e17abfbb3 100644
--- a/src/render/renderers/opengl/textures/textures.pri
+++ b/src/plugins/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/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/plugins/renderplugins/scene2d/scene2d.pro b/src/plugins/renderplugins/scene2d/scene2d.pro
index 2cb07756b..9f6ea4cf9 100644
--- a/src/plugins/renderplugins/scene2d/scene2d.pro
+++ b/src/plugins/renderplugins/scene2d/scene2d.pro
@@ -1,5 +1,6 @@
TARGET = scene2d
QT += core-private 3dcore 3dcore-private 3drender 3drender-private 3dextras 3dquickscene2d 3dquickscene2d-private
+DEFINES += BUILD_QT3D_MODULE
HEADERS += \
scene2dplugin.h
diff --git a/src/plugins/sceneparsers/assimp/assimp.pro b/src/plugins/sceneparsers/assimp/assimp.pro
index f761db12e..e514b7d6f 100644
--- a/src/plugins/sceneparsers/assimp/assimp.pro
+++ b/src/plugins/sceneparsers/assimp/assimp.pro
@@ -1,5 +1,6 @@
TARGET = assimpsceneimport
QT += core-private 3dcore 3dcore-private 3drender 3drender-private 3dextras 3danimation
+DEFINES += BUILD_QT3D_MODULE
include(../../../3rdparty/assimp/assimp_dependency.pri)
diff --git a/src/plugins/sceneparsers/gltf/gltf.pro b/src/plugins/sceneparsers/gltf/gltf.pro
index 8f0cc2fe0..46cc4069f 100644
--- a/src/plugins/sceneparsers/gltf/gltf.pro
+++ b/src/plugins/sceneparsers/gltf/gltf.pro
@@ -1,5 +1,6 @@
TARGET = gltfsceneimport
QT += core-private 3dcore 3dcore-private 3drender 3drender-private 3dextras
+DEFINES += BUILD_QT3D_MODULE
HEADERS += \
gltfimporter.h
diff --git a/src/plugins/sceneparsers/gltf/gltfimporter.cpp b/src/plugins/sceneparsers/gltf/gltfimporter.cpp
index 1a33973da..860dec3e7 100644
--- a/src/plugins/sceneparsers/gltf/gltfimporter.cpp
+++ b/src/plugins/sceneparsers/gltf/gltfimporter.cpp
@@ -108,6 +108,7 @@
#include <Qt3DExtras/qtorusmesh.h>
#include <private/qurlhelper_p.h>
+#include <private/qloadgltf_p.h>
/**
* glTF 2.0 conformance report
@@ -410,10 +411,7 @@ void GLTFImporter::setSource(const QUrl &source)
QFile f(path);
f.open(QIODevice::ReadOnly);
- QByteArray jsonData = f.readAll();
- QJsonDocument sceneDocument = QJsonDocument::fromJson(jsonData);
-
- if (Q_UNLIKELY(!setJSON(sceneDocument))) {
+ if (Q_UNLIKELY(!setJSON(qLoadGLTF(f.readAll())))) {
qCWarning(GLTFImporterLog, "not a JSON document");
return;
}
@@ -428,9 +426,7 @@ void GLTFImporter::setSource(const QUrl &source)
*/
void GLTFImporter::setData(const QByteArray& data, const QString &basePath)
{
- QJsonDocument sceneDocument = QJsonDocument::fromJson(data);
-
- if (Q_UNLIKELY(!setJSON(sceneDocument))) {
+ if (Q_UNLIKELY(!setJSON(qLoadGLTF(data)))) {
qCWarning(GLTFImporterLog, "not a JSON document");
return;
}
diff --git a/src/plugins/sceneparsers/gltfexport/gltfexport.pro b/src/plugins/sceneparsers/gltfexport/gltfexport.pro
index 9da330605..0decf20b8 100644
--- a/src/plugins/sceneparsers/gltfexport/gltfexport.pro
+++ b/src/plugins/sceneparsers/gltfexport/gltfexport.pro
@@ -1,5 +1,6 @@
TARGET = gltfsceneexport
QT += core-private 3dcore 3dcore-private 3drender 3drender-private 3dextras
+DEFINES += BUILD_QT3D_MODULE
HEADERS += \
gltfexporter.h
diff --git a/src/quick3d/imports/animation/importsanimation.pro b/src/quick3d/imports/animation/importsanimation.pro
index 734c5186b..a5eab0e9a 100644
--- a/src/quick3d/imports/animation/importsanimation.pro
+++ b/src/quick3d/imports/animation/importsanimation.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = quick3danimationplugin
TARGETPATH = Qt3D/Animation
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += core-private qml qml-private 3dcore 3drender 3danimation 3dquick 3dquickrender 3dquickanimation 3dquick-private 3dquickanimation-private
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/importscore.pro b/src/quick3d/imports/core/importscore.pro
index 9ba6ac66d..d7ac8c4b9 100644
--- a/src/quick3d/imports/core/importscore.pro
+++ b/src/quick3d/imports/core/importscore.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = quick3dcoreplugin
TARGETPATH = Qt3D/Core
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += core-private qml qml-private quick quick-private 3dcore 3dcore-private 3dquick 3dquick-private
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,11 +4,73 @@ 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"
exports: ["Qt3D.Core/AbstractSkeleton 2.10"]
@@ -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/importsextras.pro b/src/quick3d/imports/extras/importsextras.pro
index 1ac629422..ec51b17e1 100644
--- a/src/quick3d/imports/extras/importsextras.pro
+++ b/src/quick3d/imports/extras/importsextras.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = quick3dextrasplugin
TARGETPATH = Qt3D/Extras
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += core-private qml qml-private quick quick-private 3dcore 3dcore-private 3dquick 3dquick-private 3dextras 3dlogic 3dquickextras 3dquickextras-private
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" }
@@ -778,6 +821,10 @@ Module {
Parameter { name: "clearColor"; type: "QColor" }
}
Signal {
+ name: "buffersToClearChanged"
+ Parameter { type: "Qt3DRender::QClearBuffers::BufferType" }
+ }
+ Signal {
name: "cameraChanged"
Parameter { name: "camera"; type: "Qt3DCore::QEntity"; isPointer: true }
}
@@ -806,6 +853,10 @@ Module {
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/extras/qt3dquick3dextrasplugin.cpp b/src/quick3d/imports/extras/qt3dquick3dextrasplugin.cpp
index 387bf2ce6..707824182 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<Qt3DExtras::QForwardRenderer>(uri, 2, 0, "ForwardRenderer");
qmlRegisterType<Qt3DExtras::QForwardRenderer, 9>(uri, 2, 9, "ForwardRenderer");
qmlRegisterType<Qt3DExtras::QForwardRenderer, 14>(uri, 2, 14, "ForwardRenderer");
+ qmlRegisterType<Qt3DExtras::QForwardRenderer, 15>(uri, 2, 15, "ForwardRenderer");
// Entities
qmlRegisterType<Qt3DExtras::QSkyboxEntity>(uri, 2, 0, "SkyboxEntity");
diff --git a/src/quick3d/imports/input/importsinput.pro b/src/quick3d/imports/input/importsinput.pro
index ec333f992..a431e6c6e 100644
--- a/src/quick3d/imports/input/importsinput.pro
+++ b/src/quick3d/imports/input/importsinput.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = quick3dinputplugin
TARGETPATH = Qt3D/Input
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += core-private qml 3dcore 3dinput 3dinput-private 3dquickinput-private
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/input/qt3dquick3dinputplugin.cpp b/src/quick3d/imports/input/qt3dquick3dinputplugin.cpp
index 46a3021ef..3ea731885 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<Qt3DInput::QMouseHandler>(uri, 2, 0, "MouseHandler");
qmlRegisterType<Qt3DInput::QMouseDevice>(uri, 2, 0, "MouseDevice");
+ qmlRegisterType<Qt3DInput::QMouseDevice, 15>(uri, 2, 15, "MouseDevice");
qmlRegisterExtendedType<Qt3DInput::QLogicalDevice, Qt3DInput::Input::Quick::Quick3DLogicalDevice>(uri, 2, 0, "LogicalDevice");
qmlRegisterUncreatableType<Qt3DInput::QAbstractActionInput>(uri, 2, 0, "AbstractActionInput", QStringLiteral("AbstractActionInput is abstract"));
diff --git a/src/quick3d/imports/logic/importslogic.pro b/src/quick3d/imports/logic/importslogic.pro
index 2fc2accc5..74528ccb1 100644
--- a/src/quick3d/imports/logic/importslogic.pro
+++ b/src/quick3d/imports/logic/importslogic.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = quick3dlogicplugin
TARGETPATH = Qt3D/Logic
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += core-private qml 3dcore 3dlogic
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/importsrender.pro b/src/quick3d/imports/render/importsrender.pro
index 977668c40..dd43205cf 100644
--- a/src/quick3d/imports/render/importsrender.pro
+++ b/src/quick3d/imports/render/importsrender.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = quick3drenderplugin
TARGETPATH = Qt3D/Render
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += core-private qml qml-private 3dcore 3drender 3drender-private 3dquick 3dquick-private 3dquickrender-private
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" }
@@ -1666,6 +1689,30 @@ Module {
}
}
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"
exports: ["Qt3D.Render/DepthTest 2.0"]
@@ -2335,6 +2382,12 @@ Module {
exportMetaObjectRevisions: [0]
}
Component {
+ name: "Qt3DRender::QNoPicking"
+ prototype: "Qt3DRender::QFrameGraphNode"
+ exports: ["Qt3D.Render/NoPicking 2.14"]
+ exportMetaObjectRevisions: [0]
+ }
+ Component {
name: "Qt3DRender::QObjectPicker"
prototype: "Qt3DCore::QComponent"
exports: [
@@ -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" }
@@ -2654,6 +2721,46 @@ Module {
}
}
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"
Property { name: "origin"; type: "QVector3D" }
@@ -3151,6 +3258,120 @@ Module {
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"
exports: [
@@ -3400,7 +3621,8 @@ Module {
"StateChangeCost": 1,
"BackToFront": 2,
"Material": 4,
- "FrontToBack": 8
+ "FrontToBack": 8,
+ "Texture": 16
}
}
Property { name: "sortTypes"; type: "QVector<int>" }
@@ -3653,6 +3875,25 @@ Module {
}
}
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"
prototype: "Qt3DCore::QNode"
diff --git a/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp b/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp
index 947e3d2f1..e42be550d 100644
--- a/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp
+++ b/src/quick3d/imports/render/qt3dquick3drenderplugin.cpp
@@ -119,6 +119,7 @@
#include <Qt3DRender/qnopicking.h>
#include <Qt3DRender/qshaderimage.h>
#include <Qt3DRender/qsubtreeenabler.h>
+#include <Qt3DRender/qrendercapabilities.h>
#include <QtGui/qwindow.h>
@@ -169,7 +170,9 @@ void Qt3DQuick3DRenderPlugin::registerTypes(const char *uri)
// Renderer setttings
qmlRegisterType<Qt3DRender::QRenderSettings>(uri, 2, 0, "RenderSettings");
+ qmlRegisterType<Qt3DRender::QRenderSettings, 15>(uri, 2, 15, "RenderSettings");
qmlRegisterType<Qt3DRender::QPickingSettings>(uri, 2, 0, "PickingSettings");
+ qmlRegisterUncreatableType<Qt3DRender::QRenderCapabilities>(uri, 2, 15, "RenderCapabilities", "Only available as a property of RenderSettings");
// @uri Qt3D.Render
Qt3DRender::Quick::registerExtendedType<Qt3DRender::QSceneLoader, Qt3DRender::Render::Quick::Quick3DScene>("QSceneLoader", "Qt3D.Render/SceneLoader", uri, 2, 0, "SceneLoader");
@@ -184,6 +187,7 @@ void Qt3DQuick3DRenderPlugin::registerTypes(const char *uri)
Qt3DRender::Quick::registerExtendedType<Qt3DRender::QRenderPass, Qt3DRender::Render::Quick::Quick3DRenderPass>("QRenderPass", "Qt3D.Render/RenderPass", uri, 2, 0, "RenderPass");
qmlRegisterType<Qt3DRender::QShaderProgram>(uri, 2, 0, "ShaderProgram");
qmlRegisterType<Qt3DRender::QShaderProgram, 9>(uri, 2, 9, "ShaderProgram");
+ qmlRegisterType<Qt3DRender::QShaderProgram, 15>(uri, 2, 15, "ShaderProgram");
qmlRegisterType<Qt3DRender::QShaderProgramBuilder>(uri, 2, 10, "ShaderProgramBuilder");
qmlRegisterType<Qt3DRender::QShaderProgramBuilder, 13>(uri, 2, 13, "ShaderProgramBuilder");
qmlRegisterUncreatableType<Qt3DRender::QShaderData>(uri, 2, 0, "QShaderData", "Quick3D should instantiate Quick3DShaderData only");
diff --git a/src/quick3d/imports/scene2d/importsscene2d.pro b/src/quick3d/imports/scene2d/importsscene2d.pro
index cb87f4ca9..828bbcadb 100644
--- a/src/quick3d/imports/scene2d/importsscene2d.pro
+++ b/src/quick3d/imports/scene2d/importsscene2d.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = qtquickscene2dplugin
TARGETPATH = QtQuick/Scene2D
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += qml quick 3dcore 3drender 3drender-private 3dinput 3dlogic 3dquickscene2d 3dquickscene2d-private
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/importsscene3d.pro b/src/quick3d/imports/scene3d/importsscene3d.pro
index e29f7b831..6bf4f5d91 100644
--- a/src/quick3d/imports/scene3d/importsscene3d.pro
+++ b/src/quick3d/imports/scene3d/importsscene3d.pro
@@ -2,6 +2,7 @@ CXX_MODULE = qml
TARGET = qtquickscene3dplugin
TARGETPATH = QtQuick/Scene3D
IMPORT_VERSION = 2.$$QT_MINOR_VERSION
+DEFINES += BUILD_QT3D_MODULE
QT += qml quick 3dcore 3drender 3drender-private
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" }
@@ -47,9 +58,30 @@ Module {
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 }
+ }
+ }
}
diff --git a/src/quick3d/imports/scene3d/scene3ditem.cpp b/src/quick3d/imports/scene3d/scene3ditem.cpp
index f3f7acd71..f824d2c4e 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)
@@ -154,6 +159,7 @@ Scene3DItem::Scene3DItem(QQuickItem *parent)
, m_disableClearWindow(false)
, m_cameraAspectRatioMode(AutomaticAspectRatio)
, m_compositingMode(FBO)
+ , m_dummySurface(nullptr)
{
setFlag(QQuickItem::ItemHasContents, true);
setAcceptedMouseButtons(Qt::MouseButtonMask);
@@ -427,12 +433,26 @@ void Scene3DItem::applyRootEntityChange()
bool Scene3DItem::needsRender()
{
+ // We need the dirty flag which is connected to the change arbiter
+ // receiving updates to know whether something in the scene has changed
+
+ // Ideally we would use shouldRender() alone but given that it becomes true
+ // only after the arbiter has sync the changes and might be reset before
+ // process jobs is completed, we cannot fully rely on it. It would require
+ // splitting processFrame in 2 parts.
+
+ // We only use it for cases where Qt3D render may require several loops of
+ // the simulation to fully process a frame (e.g shaders are loaded in frame
+ // n and we can only build render commands for the new shader at frame n +
+ // This is where renderer->shouldRender() comes into play as it knows
+ // whether some states remain dirty or not (even after processFrame is
+ // called)
+
auto renderAspectPriv = static_cast<QRenderAspectPrivate*>(QRenderAspectPrivate::get(m_renderAspect));
const bool dirty = m_dirty
|| (renderAspectPriv
&& renderAspectPriv->m_renderer
- && renderAspectPriv->m_renderer->settings()
- && renderAspectPriv->m_renderer->settings()->renderPolicy() == QRenderSettings::Always);
+ && renderAspectPriv->m_renderer->shouldRender());
m_dirty = false;
return dirty;
}
@@ -454,8 +474,12 @@ bool Scene3DItem::needsRender()
// processFrame will block and wait for renderer to have been finished
void Scene3DItem::onBeforeSync()
{
- // Has anything in the 3D scene actually changed that requires us to render?
- if (!needsRender())
+ static bool dontRenderWhenHidden = !qgetenv("QT3D_SCENE3D_STOP_RENDER_HIDDEN").isEmpty();
+
+ // 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() && dontRenderWhenHidden)
return;
Q_ASSERT(QThread::currentThread() == thread());
@@ -498,6 +522,7 @@ void Scene3DItem::onBeforeSync()
// start rendering before this function has been called
// We add in a safety to skip such frames as this could otherwise
// make Qt3D enter a locked state
+ m_renderer->setSkipFrame(!needsRender());
m_renderer->allowRender();
// Note: it's too early to request an update at this point as
@@ -546,7 +571,7 @@ void Scene3DItem::setWindowSurface(QObject *rootObject)
/*!
\qmlmethod void Scene3D::setItemAreaAndDevicePixelRatio(size area, real devicePixelRatio)
- \brief \TODO
+ Sets the item area to \a area and the pixel ratio to \a devicePixelRatio.
*/
void Scene3DItem::setItemAreaAndDevicePixelRatio(QSize area, qreal devicePixelRatio)
{
@@ -569,25 +594,45 @@ bool Scene3DItem::isHoverEnabled() const
void Scene3DItem::setCameraAspectModeHelper()
{
- switch (m_cameraAspectRatioMode) {
- case AutomaticAspectRatio:
- connect(this, &Scene3DItem::widthChanged, this, &Scene3DItem::updateCameraAspectRatio);
- connect(this, &Scene3DItem::heightChanged, this, &Scene3DItem::updateCameraAspectRatio);
- // Update the aspect ratio the first time the surface is set
- updateCameraAspectRatio();
- break;
- case UserAspectRatio:
- disconnect(this, &Scene3DItem::widthChanged, this, &Scene3DItem::updateCameraAspectRatio);
- disconnect(this, &Scene3DItem::heightChanged, this, &Scene3DItem::updateCameraAspectRatio);
- break;
+ if (m_compositingMode == FBO) {
+ switch (m_cameraAspectRatioMode) {
+ case AutomaticAspectRatio:
+ connect(this, &Scene3DItem::widthChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ connect(this, &Scene3DItem::heightChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ // Update the aspect ratio the first time the surface is set
+ updateCameraAspectRatio();
+ break;
+ case UserAspectRatio:
+ disconnect(this, &Scene3DItem::widthChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ disconnect(this, &Scene3DItem::heightChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ break;
+ }
+ } else {
+ // In Underlay mode, we rely on the window for aspect ratio and not the size of the Scene3DItem
+ switch (m_cameraAspectRatioMode) {
+ case AutomaticAspectRatio:
+ connect(window(), &QWindow::widthChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ connect(window(), &QWindow::heightChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ // Update the aspect ratio the first time the surface is set
+ updateCameraAspectRatio();
+ break;
+ case UserAspectRatio:
+ disconnect(window(), &QWindow::widthChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ disconnect(window(), &QWindow::heightChanged, this, &Scene3DItem::updateCameraAspectRatio);
+ break;
+ }
}
}
void Scene3DItem::updateCameraAspectRatio()
{
if (m_camera) {
- m_camera->setAspectRatio(static_cast<float>(width()) /
- static_cast<float>(height()));
+ if (m_compositingMode == FBO)
+ m_camera->setAspectRatio(static_cast<float>(width()) /
+ static_cast<float>(height()));
+ else
+ m_camera->setAspectRatio(static_cast<float>(window()->width()) /
+ static_cast<float>(window()->height()));
}
}
diff --git a/src/quick3d/imports/scene3d/scene3drenderer.cpp b/src/quick3d/imports/scene3d/scene3drenderer.cpp
index 98e735048..71cf6c240 100644
--- a/src/quick3d/imports/scene3d/scene3drenderer.cpp
+++ b/src/quick3d/imports/scene3d/scene3drenderer.cpp
@@ -161,7 +161,9 @@ Scene3DRenderer::Scene3DRenderer(Scene3DItem *item, Qt3DCore::QAspectEngine *asp
, m_forceRecreate(false)
, m_shouldRender(false)
, m_dirtyViews(false)
+ , m_skipFrame(false)
, m_allowRendering(0)
+ , m_compositingMode(Scene3DItem::FBO)
{
Q_CHECK_PTR(m_item);
Q_CHECK_PTR(m_item->window());
@@ -277,6 +279,19 @@ void Scene3DRenderer::beforeSynchronize()
// We could otherwise enter a deadlock state
if (!m_allowRendering.tryAcquire(std::max(m_allowRendering.available(), 1)))
return;
+
+ // In the case of OnDemand rendering, we still need to get to this
+ // point to ensure we have processed jobs for all aspects.
+ // We also still need to call render() to allow proceeding with the
+ // next frame. However it won't be performing any 3d rendering at all
+ // so we do it here and return early. This prevents a costly QtQuick
+ // SceneGraph update for nothing
+ if (m_skipFrame) {
+ m_skipFrame = false;
+ static_cast<QRenderAspectPrivate*>(QRenderAspectPrivate::get(m_renderAspect))->renderSynchronous(false);
+ return;
+ }
+
m_shouldRender = true;
// Check size / multisampling
@@ -359,6 +374,11 @@ void Scene3DRenderer::setCompositingMode(Scene3DItem::CompositingMode mode)
m_compositingMode = mode;
}
+void Scene3DRenderer::setSkipFrame(bool skip)
+{
+ m_skipFrame = skip;
+}
+
// Main Thread, Render Thread locked
void Scene3DRenderer::setScene3DViews(const QVector<Scene3DView *> views)
{
@@ -422,7 +442,8 @@ void Scene3DRenderer::render()
// Only show the node once Qt3D has rendered to it
// Avoids showing garbage on the first frame
- m_node->show();
+ if (m_node)
+ m_node->show();
}
// Reset the state used by the Qt Quick scenegraph to avoid any
diff --git a/src/quick3d/imports/scene3d/scene3drenderer_p.h b/src/quick3d/imports/scene3d/scene3drenderer_p.h
index 4f3651cd3..08a2c60a3 100644
--- a/src/quick3d/imports/scene3d/scene3drenderer_p.h
+++ b/src/quick3d/imports/scene3d/scene3drenderer_p.h
@@ -87,7 +87,7 @@ public:
void setCleanerHelper(Scene3DCleaner *cleaner);
void allowRender();
void setCompositingMode(Scene3DItem::CompositingMode mode);
-
+ void setSkipFrame(bool skip);
void setScene3DViews(const QVector<Scene3DView *> views);
public Q_SLOTS:
@@ -119,6 +119,7 @@ private:
bool m_forceRecreate;
bool m_shouldRender;
bool m_dirtyViews;
+ bool m_skipFrame;
QSemaphore m_allowRendering;
Scene3DItem::CompositingMode m_compositingMode;
QVector<Scene3DView *> m_views;
diff --git a/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp b/src/quick3d/imports/scene3d/scene3dsgmaterialshader.cpp
index 27007899d..b7dd03810 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/imports/scene3d/scene3dview.cpp b/src/quick3d/imports/scene3d/scene3dview.cpp
index 9d298b435..f38d135f0 100644
--- a/src/quick3d/imports/scene3d/scene3dview.cpp
+++ b/src/quick3d/imports/scene3d/scene3dview.cpp
@@ -278,6 +278,8 @@ QSGNode *Scene3DView::updatePaintNode(QSGNode *node, QQuickItem::UpdatePaintNode
if (m_dirtyFlags & DirtyTexture) {
fboNode->setTexture(m_texture);
m_dirtyFlags.setFlag(DirtyTexture, false);
+ // Show FBO Node at this point
+ fboNode->show();
}
if (m_dirtyFlags & DirtyNode) {
fboNode->markDirty(QSGNode::DirtyMaterial);
diff --git a/src/quick3d/quick3d/qquaternionanimation.cpp b/src/quick3d/quick3d/qquaternionanimation.cpp
index 22cc905f7..933a08ee4 100644
--- a/src/quick3d/quick3d/qquaternionanimation.cpp
+++ b/src/quick3d/quick3d/qquaternionanimation.cpp
@@ -144,7 +144,7 @@ void QQuaternionAnimation::setType(Type type)
switch (type) {
case Nlerp:
QT_WARNING_PUSH
-QT_WARNING_DISABLE_GCC(-Wcast-function-type)
+QT_WARNING_DISABLE_GCC("-Wcast-function-type")
d->interpolator = reinterpret_cast<QVariantAnimation::Interpolator>(&q_quaternionNlerpInterpolator);
QT_WARNING_POP
break;
diff --git a/src/quick3d/quick3d/quick3d.pro b/src/quick3d/quick3d/quick3d.pro
index b7edec507..7fefe2dc2 100644
--- a/src/quick3d/quick3d/quick3d.pro
+++ b/src/quick3d/quick3d/quick3d.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DQuick
MODULE = 3dquick
+DEFINES += BUILD_QT3D_MODULE
QT += core-private gui-private qml qml-private quick quick-private 3dcore 3dcore-private
diff --git a/src/quick3d/quick3danimation/quick3danimation.pro b/src/quick3d/quick3danimation/quick3danimation.pro
index 4b166327f..483f4994c 100644
--- a/src/quick3d/quick3danimation/quick3danimation.pro
+++ b/src/quick3d/quick3danimation/quick3danimation.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DQuickAnimation
MODULE = 3dquickanimation
+DEFINES += BUILD_QT3D_MODULE
QT += core core-private qml qml-private 3dcore 3drender 3danimation 3dquick 3dquick-private 3dcore-private 3drender-private
CONFIG -= precompile_header
diff --git a/src/quick3d/quick3dextras/qt3dquickwindow.cpp b/src/quick3d/quick3dextras/qt3dquickwindow.cpp
index 773e9ca94..dfe245936 100644
--- a/src/quick3d/quick3dextras/qt3dquickwindow.cpp
+++ b/src/quick3d/quick3dextras/qt3dquickwindow.cpp
@@ -276,7 +276,7 @@ void Qt3DQuickWindow::updateCameraAspectRatio()
Q_D(Qt3DQuickWindow);
if (d->m_camera) {
d->m_camera->setAspectRatio(static_cast<float>(width()) /
- static_cast<float>(height()));
+ std::max(1.f, static_cast<float>(height())));
}
}
diff --git a/src/quick3d/quick3dextras/quick3dextras.pro b/src/quick3d/quick3dextras/quick3dextras.pro
index f7c956f8a..40de4484a 100644
--- a/src/quick3d/quick3dextras/quick3dextras.pro
+++ b/src/quick3d/quick3dextras/quick3dextras.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DQuickExtras
MODULE = 3dquickextras
+DEFINES += BUILD_QT3D_MODULE
QT += core core-private qml qml-private 3dcore 3dinput 3dquick 3dquick-private 3drender 3drender-private 3dlogic 3dextras
diff --git a/src/quick3d/quick3dinput/quick3dinput.pro b/src/quick3d/quick3dinput/quick3dinput.pro
index e797f3fae..491346816 100644
--- a/src/quick3d/quick3dinput/quick3dinput.pro
+++ b/src/quick3d/quick3dinput/quick3dinput.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DQuickInput
MODULE = 3dquickinput
+DEFINES += BUILD_QT3D_MODULE
QT += core core-private qml qml-private 3dcore 3dinput 3dquick 3dquick-private 3dcore-private 3dinput-private
CONFIG -= precompile_header
diff --git a/src/quick3d/quick3drender/quick3drender.pro b/src/quick3d/quick3drender/quick3drender.pro
index 4c158a7b7..04eac6a16 100644
--- a/src/quick3d/quick3drender/quick3drender.pro
+++ b/src/quick3d/quick3drender/quick3drender.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DQuickRender
MODULE = 3dquickrender
+DEFINES += BUILD_QT3D_MODULE
QT += core core-private qml qml-private 3dcore 3drender 3dquick 3dquick-private 3dcore-private 3drender-private
CONFIG -= precompile_header
diff --git a/src/quick3d/quick3dscene2d/items/qscene2d.cpp b/src/quick3d/quick3dscene2d/items/qscene2d.cpp
index cbdc83e7d..b12adb8ed 100644
--- a/src/quick3d/quick3dscene2d/items/qscene2d.cpp
+++ b/src/quick3d/quick3dscene2d/items/qscene2d.cpp
@@ -52,6 +52,12 @@ namespace Qt3DRender {
namespace Quick {
/*!
+ \namespace Qt3DRender::Quick
+ \inmodule Qt3DScene2D
+ \brief Internal namespace to import QML types.
+*/
+
+/*!
\class Qt3DRender::Quick::QScene2D
\inheaderfile Qt3DQuickScene2D/QScene2D
\inmodule Qt3DScene2D
diff --git a/src/quick3d/quick3dscene2d/items/qscene2d.h b/src/quick3d/quick3dscene2d/items/qscene2d.h
index 2f5c1010e..38eaf7359 100644
--- a/src/quick3d/quick3dscene2d/items/qscene2d.h
+++ b/src/quick3d/quick3dscene2d/items/qscene2d.h
@@ -51,11 +51,6 @@ QT_BEGIN_NAMESPACE
namespace Qt3DRender {
-/*!
- \namespace Qt3DRender::Quick
-
- \brief Internal namespace to import QML types.
-*/
namespace Quick {
class QScene2DPrivate;
diff --git a/src/quick3d/quick3dscene2d/items/scene2d.cpp b/src/quick3d/quick3dscene2d/items/scene2d.cpp
index 981b290e2..063464b95 100644
--- a/src/quick3d/quick3dscene2d/items/scene2d.cpp
+++ b/src/quick3d/quick3dscene2d/items/scene2d.cpp
@@ -45,12 +45,12 @@
#include <QtCore/qthread.h>
#include <QtCore/qatomic.h>
#include <QtGui/qevent.h>
+#include <QtGui/QOpenGLFunctions>
#include <private/qscene2d_p.h>
#include <private/scene2d_p.h>
#include <private/scene2dmanager_p.h>
#include <private/scene2devent_p.h>
-#include <private/graphicscontext_p.h>
#include <private/texture_p.h>
#include <private/nodemanagers_p.h>
#include <private/resourceaccessor_p.h>
@@ -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<Qt3DCore::QNode *>(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<ObjectPicker>() ||
!entity->containsComponentsOfType<GeometryRenderer>()) {
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/quick3d/quick3dscene2d/quick3dscene2d.pro b/src/quick3d/quick3dscene2d/quick3dscene2d.pro
index b0596e8de..d807fe923 100644
--- a/src/quick3d/quick3dscene2d/quick3dscene2d.pro
+++ b/src/quick3d/quick3dscene2d/quick3dscene2d.pro
@@ -1,5 +1,6 @@
TARGET = Qt3DQuickScene2D
MODULE = 3dquickscene2d
+DEFINES += BUILD_QT3D_MODULE
QT += core core-private qml qml-private 3dcore 3drender 3dquick 3dquick-private 3dcore-private 3drender-private
CONFIG -= precompile_header
diff --git a/src/render/backend/abstractrenderer_p.h b/src/render/backend/abstractrenderer_p.h
index f53ba04ba..4e25d627f 100644
--- a/src/render/backend/abstractrenderer_p.h
+++ b/src/render/backend/abstractrenderer_p.h
@@ -65,12 +65,14 @@ QT_BEGIN_NAMESPACE
class QSurface;
class QSize;
class QScreen;
+class QOpenGLTexture;
namespace Qt3DCore {
class QAbstractFrameAdvanceService;
class QEventFilterService;
class QAbstractAspectJobManager;
class QServiceLocator;
+class QAspectManager;
}
namespace Qt3DRender {
@@ -86,6 +88,7 @@ class RenderSettings;
class BackendNode;
class OffscreenSurfaceHelper;
class Shader;
+class RenderBackendResourceAccessor;
class Q_3DRENDERSHARED_PRIVATE_EXPORT AbstractRenderer
{
@@ -125,6 +128,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;
@@ -151,8 +155,9 @@ public:
#if defined(QT_BUILD_INTERNAL)
virtual void clearDirtyBits(BackendNodeDirtySet changes) = 0;
#endif
- virtual bool shouldRender() = 0;
+ virtual bool shouldRender() const = 0;
virtual void skipNextFrame() = 0;
+ virtual void jobsDone(Qt3DCore::QAspectManager *manager) = 0;
virtual QVector<Qt3DCore::QAspectJobPtr> preRenderingJobs() = 0;
virtual QVector<Qt3DCore::QAspectJobPtr> renderBinJobs() = 0;
@@ -174,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<RenderBackendResourceAccessor> resourceAccessor() const = 0;
virtual void setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) = 0;
virtual QSurfaceFormat format() = 0;
diff --git a/src/render/backend/apishadermanager_p.h b/src/render/backend/apishadermanager_p.h
new file mode 100644
index 000000000..9ebf49710
--- /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 <Qt3DCore/qnodeid.h>
+#include <Qt3DRender/private/shader_p.h>
+#include <QtCore/QReadLocker>
+
+QT_BEGIN_NAMESPACE
+
+namespace Qt3DRender {
+
+namespace Render {
+
+class Shader;
+
+template<class APIShader>
+class APIShaderManager
+{
+public:
+ explicit APIShaderManager()
+ {
+ }
+
+ ~APIShaderManager()
+ {
+ }
+
+ QVector<APIShader *> 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<Qt3DCore::QNodeId> &referencedShaderNodes = m_apiShaders[apiShader];
+ referencedShaderNodes.removeAll(shader->peerId());
+
+ if (referencedShaderNodes.empty()) {
+ m_abandonedShaders.push_back(apiShader);
+ m_apiShaders.remove(apiShader);
+ }
+ }
+
+ QVector<APIShader *> takeAbandonned()
+ {
+ QWriteLocker lock(&m_readWriteLock);
+ return std::move(m_abandonedShaders);
+ }
+
+ QVector<APIShader *> takeUpdated()
+ {
+ QWriteLocker lock(&m_readWriteLock);
+ return std::move(m_updatedShaders);
+ }
+
+ QVector<Qt3DCore::QNodeId> shaderIdsForProgram(APIShader *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<QByteArray> nodeShaderCode = shaderNode->shaderCode();
+ const QVector<QByteArray> 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<Qt3DCore::QNodeId, APIShader *> m_nodeIdToAPIShader;
+ QHash<APIShader *, QVector<Qt3DCore::QNodeId>> m_apiShaders;
+
+ QVector<APIShader *> m_abandonedShaders;
+ QVector<APIShader *> m_updatedShaders;
+
+ mutable QReadWriteLock m_readWriteLock;
+};
+
+} // Render
+
+} // Qt3DRender
+
+QT_END_NAMESPACE
+
+#endif // QT3DRENDER_RENDER_APISHADERMANAGER_H
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 <Qt3DRender/qrendertargetoutput.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QVector>
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 642f6e44d..18e7af256 100644
--- a/src/render/backend/backendnode.cpp
+++ b/src/render/backend/backendnode.cpp
@@ -38,10 +38,11 @@
****************************************************************************/
#include <private/backendnode_p.h>
-#include <private/renderer_p.h>
+#include <private/abstractrenderer_p.h>
#include <private/resourceaccessor_p.h>
#include <private/nodemanagers_p.h>
#include <Qt3DCore/private/qbackendnode_p.h>
+#include <Qt3DCore/qnode.h>
QT_BEGIN_NAMESPACE
@@ -82,10 +83,9 @@ void BackendNode::markDirty(AbstractRenderer::BackendNodeDirtySet changes)
m_renderer->markDirty(changes, this);
}
-QSharedPointer<RenderBackendResourceAccessor> BackendNode::resourceAccessor()
+QSharedPointer<RenderBackendResourceAccessor> BackendNode::resourceAccessor() const
{
- Render::Renderer *r = static_cast<Render::Renderer *>(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<RenderBackendResourceAccessor> resourceAccessor();
+ QSharedPointer<RenderBackendResourceAccessor> resourceAccessor() const;
protected:
explicit BackendNode(Qt3DCore::QBackendNodePrivate &dd);
diff --git a/src/render/backend/bufferutils_p.h b/src/render/backend/bufferutils_p.h
index 2bb35fac6..ea783df0d 100644
--- a/src/render/backend/bufferutils_p.h
+++ b/src/render/backend/bufferutils_p.h
@@ -74,6 +74,8 @@ struct BufferInfo
, count(0)
, byteStride(0)
, byteOffset(0)
+ , restartEnabled(false)
+ , restartIndexValue(-1)
{}
QByteArray data;
@@ -82,6 +84,8 @@ struct BufferInfo
uint count;
uint byteStride;
uint byteOffset;
+ bool restartEnabled;
+ int restartIndexValue;
};
diff --git a/src/render/backend/cameralens.cpp b/src/render/backend/cameralens.cpp
index 85c5e9656..ab74e8b56 100644
--- a/src/render/backend/cameralens.cpp
+++ b/src/render/backend/cameralens.cpp
@@ -39,15 +39,18 @@
#include "cameralens_p.h"
#include <Qt3DRender/qcameralens.h>
+#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
-#include <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/sphere_p.h>
#include <Qt3DRender/private/computefilteredboundingvolumejob_p.h>
+#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DCore/qentity.h>
#include <Qt3DCore/qtransform.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
QT_BEGIN_NAMESPACE
@@ -62,21 +65,21 @@ namespace {
class GetBoundingVolumeWithoutCameraJob : public ComputeFilteredBoundingVolumeJob
{
public:
- GetBoundingVolumeWithoutCameraJob(CameraLens *lens,
- QNodeCommand::CommandId commandId)
- : m_lens(lens), m_commandId(commandId)
+ GetBoundingVolumeWithoutCameraJob(CameraLens *lens, QNodeId commandId)
+ : m_lens(lens), m_requestId(commandId)
{
}
protected:
- void finished(const Sphere &sphere) override
+ // called in main thread
+ void finished(Qt3DCore::QAspectManager *aspectManager, const Sphere &sphere) override
{
- m_lens->notifySceneBoundingVolume(sphere, m_commandId);
+ m_lens->processViewAllResult(aspectManager, sphere, m_requestId);
}
private:
CameraLens *m_lens;
- QNodeCommand::CommandId m_commandId;
+ QNodeId m_requestId;
};
} // namespace
@@ -114,6 +117,9 @@ Matrix4x4 CameraLens::viewMatrix(const Matrix4x4 &worldTransform)
m.lookAt(convertToQVector3D(Vector3D(position)),
convertToQVector3D(Vector3D(position + viewDirection)),
convertToQVector3D(Vector3D(upVector)));
+
+ qDebug(Jobs) << Q_FUNC_INFO << "Transform Matrix" << worldTransform << "View Matrix" << m;
+
return Matrix4x4(m);
}
@@ -131,34 +137,23 @@ void CameraLens::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTim
markDirty(AbstractRenderer::AllDirty);
}
- if (node->exposure() != m_exposure) {
+ if (!qFuzzyCompare(node->exposure(), m_exposure)) {
m_exposure = node->exposure();
markDirty(AbstractRenderer::AllDirty);
}
const QCameraLensPrivate *d = static_cast<const QCameraLensPrivate *>(QNodePrivate::get(node));
- if (d->m_pendingViewAllCommand != m_pendingViewAllCommand) {
- m_pendingViewAllCommand = d->m_pendingViewAllCommand;
-
- if (m_pendingViewAllCommand) {
- const QVariant v = m_pendingViewAllCommand.data;
- const QNodeCommand::CommandId commandId = m_pendingViewAllCommand.commandId;
-
- if (m_pendingViewAllCommand.name == QLatin1String("QueryRootBoundingVolume")) {
- const QNodeId id = v.value<QNodeId>();
- computeSceneBoundingVolume({}, id, commandId);
- } else if (m_pendingViewAllCommand.name == QLatin1String("QueryEntityBoundingVolume")) {
- const QVector<QNodeId> ids = v.value<QVector<QNodeId>>();
- if (ids.size() == 2)
- computeSceneBoundingVolume(ids[0], ids[1], commandId);
- }
- }
+ if (d->m_pendingViewAllRequest != m_pendingViewAllRequest) {
+ m_pendingViewAllRequest = d->m_pendingViewAllRequest;
+
+ if (m_pendingViewAllRequest)
+ computeSceneBoundingVolume(m_pendingViewAllRequest.entityId, m_pendingViewAllRequest.cameraId, m_pendingViewAllRequest.requestId);
}
}
void CameraLens::computeSceneBoundingVolume(QNodeId entityId,
QNodeId cameraId,
- QNodeCommand::CommandId commandId)
+ QNodeId requestId)
{
if (!m_renderer || !m_renderAspect)
return;
@@ -171,7 +166,7 @@ void CameraLens::computeSceneBoundingVolume(QNodeId entityId,
return;
Entity *camNode = nodeManagers->renderNodesManager()->lookupResource(cameraId);
- ComputeFilteredBoundingVolumeJobPtr job(new GetBoundingVolumeWithoutCameraJob(this, commandId));
+ ComputeFilteredBoundingVolumeJobPtr job(new GetBoundingVolumeWithoutCameraJob(this, requestId));
job->addDependency(m_renderer->expandBoundingVolumeJob());
job->setRoot(root);
job->setManagers(nodeManagers);
@@ -179,18 +174,18 @@ void CameraLens::computeSceneBoundingVolume(QNodeId entityId,
m_renderAspect->scheduleSingleShotJob(job);
}
-void CameraLens::notifySceneBoundingVolume(const Sphere &sphere, QNodeCommand::CommandId commandId)
+void CameraLens::processViewAllResult(QAspectManager *aspectManager, const Sphere &sphere, QNodeId commandId)
{
- if (!m_pendingViewAllCommand || m_pendingViewAllCommand.commandId != commandId)
+ if (!m_pendingViewAllRequest || m_pendingViewAllRequest.requestId != commandId)
return;
if (sphere.radius() > 0.f) {
- QVector<float> data = { sphere.center().x(), sphere.center().y(), sphere.center().z(),
- sphere.radius() };
- QVariant v;
- v.setValue(data);
- sendCommand(QLatin1String("ViewAll"), v, m_pendingViewAllCommand.commandId);
+ QCameraLens *lens = qobject_cast<QCameraLens *>(aspectManager->lookupNode(peerId()));
+ if (lens) {
+ QCameraLensPrivate *dlens = static_cast<QCameraLensPrivate *>(QCameraLensPrivate::get(lens));
+ dlens->processViewAllResult(m_pendingViewAllRequest.requestId, { sphere.center().x(), sphere.center().y(), sphere.center().z() }, sphere.radius());
+ }
}
- m_pendingViewAllCommand = {};
+ m_pendingViewAllRequest = {};
}
void CameraLens::setProjection(const Matrix4x4 &projection)
diff --git a/src/render/backend/cameralens_p.h b/src/render/backend/cameralens_p.h
index bd721d5e9..4afa38620 100644
--- a/src/render/backend/cameralens_p.h
+++ b/src/render/backend/cameralens_p.h
@@ -52,7 +52,6 @@
//
#include <Qt3DRender/private/backendnode_p.h>
-#include <Qt3DCore/private/qnodecommand_p.h>
#include <Qt3DCore/private/matrix4x4_p.h>
#include <Qt3DRender/private/qcameralens_p.h>
#include <QRectF>
@@ -99,7 +98,7 @@ public:
inline float exposure() const { return m_exposure; }
void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) override;
- void notifySceneBoundingVolume(const Sphere &sphere, Qt3DCore::QNodeCommand::CommandId commandId);
+ void processViewAllResult(Qt3DCore::QAspectManager *aspectManager, const Sphere &sphere, Qt3DCore::QNodeId commandId);
static bool viewMatrixForCamera(EntityManager *manager, Qt3DCore::QNodeId cameraId,
Matrix4x4 &viewMatrix, Matrix4x4 &projectionMatrix);
@@ -107,10 +106,10 @@ public:
private:
void computeSceneBoundingVolume(Qt3DCore::QNodeId entityId,
Qt3DCore::QNodeId cameraId,
- Qt3DCore::QNodeCommand::CommandId commandId);
+ Qt3DCore::QNodeId requestId);
QRenderAspect *m_renderAspect;
- CameraLensCommand m_pendingViewAllCommand;
+ CameraLensRequest m_pendingViewAllRequest;
Matrix4x4 m_projection;
float m_exposure;
};
diff --git a/src/render/backend/computecommand.cpp b/src/render/backend/computecommand.cpp
index df79dcbe8..bc82291f0 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)
@@ -98,8 +100,12 @@ void ComputeCommand::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firs
markDirty(AbstractRenderer::ComputeDirty);
}
const QComputeCommandPrivate *d = static_cast<const QComputeCommandPrivate *>(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);
}
@@ -112,14 +118,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..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();
@@ -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/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/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 <Qt3DRender/private/backendnode_p.h>
-#include <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/handle_types_p.h>
#include <Qt3DCore/qnodecreatedchange.h>
#include <Qt3DCore/private/qentity_p.h>
@@ -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/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<Layer> HLayer;
typedef Qt3DCore::QHandle<LevelOfDetail> HLevelOfDetail;
typedef Qt3DCore::QHandle<Material> HMaterial;
typedef Qt3DCore::QHandle<Matrix4x4> HMatrix;
-typedef Qt3DCore::QHandle<OpenGLVertexArrayObject> HVao;
typedef Qt3DCore::QHandle<Shader> HShader;
typedef Qt3DCore::QHandle<ShaderBuilder> HShaderBuilder;
typedef Qt3DCore::QHandle<Technique> HTechnique;
@@ -133,8 +129,6 @@ typedef Qt3DCore::QHandle<BoundingVolumeDebug> HBoundingVolumeDebug;
typedef Qt3DCore::QHandle<Light> HLight;
typedef Qt3DCore::QHandle<EnvironmentLight> HEnvironmentLight;
typedef Qt3DCore::QHandle<ComputeCommand> HComputeCommand;
-typedef Qt3DCore::QHandle<GLBuffer> HGLBuffer;
-typedef Qt3DCore::QHandle<GLTexture> HGLTexture;
typedef Qt3DCore::QHandle<RenderStateNode> HRenderState;
typedef Qt3DCore::QHandle<Armature> HArmature;
typedef Qt3DCore::QHandle<Skeleton> HSkeleton;
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 759c16f64..db12a8a7b 100644
--- a/src/render/backend/managers_p.h
+++ b/src/render/backend/managers_p.h
@@ -71,15 +71,12 @@
#include <Qt3DRender/private/parameter_p.h>
#include <Qt3DRender/private/shaderdata_p.h>
#include <Qt3DRender/private/handle_types_p.h>
-#include <Qt3DRender/private/glbuffer_p.h>
-#include <Qt3DRender/private/glfence_p.h>
#include <Qt3DRender/private/textureimage_p.h>
#include <Qt3DRender/private/attribute_p.h>
#include <Qt3DRender/private/geometry_p.h>
#include <Qt3DRender/private/objectpicker_p.h>
#include <Qt3DRender/private/raycaster_p.h>
#include <Qt3DRender/private/boundingvolumedebug_p.h>
-#include <Qt3DRender/private/openglvertexarrayobject_p.h>
#include <Qt3DRender/private/light_p.h>
#include <Qt3DRender/private/environmentlight_p.h>
#include <Qt3DRender/private/computecommand_p.h>
@@ -94,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>
@@ -103,7 +100,7 @@ public:
AttachmentManager() {}
};
-class CameraManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT CameraManager : public Qt3DCore::QResourceManager<
CameraLens,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -112,7 +109,7 @@ public:
CameraManager() {}
};
-class FilterKeyManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT FilterKeyManager : public Qt3DCore::QResourceManager<
FilterKey,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -122,7 +119,7 @@ public:
FilterKeyManager() {}
};
-class EffectManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT EffectManager : public Qt3DCore::QResourceManager<
Effect,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -131,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>
@@ -149,7 +146,7 @@ public:
class FrameGraphNode;
-class Q_AUTOTEST_EXPORT FrameGraphManager
+class Q_3DRENDERSHARED_PRIVATE_EXPORT FrameGraphManager
{
public:
FrameGraphManager() {}
@@ -164,7 +161,7 @@ private:
QHash<Qt3DCore::QNodeId, FrameGraphNode*> m_nodes;
};
-class LayerManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT LayerManager : public Qt3DCore::QResourceManager<
Layer,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -173,7 +170,7 @@ public:
LayerManager() {}
};
-class LevelOfDetailManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT LevelOfDetailManager : public Qt3DCore::QResourceManager<
LevelOfDetail,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -182,7 +179,7 @@ public:
LevelOfDetailManager() {}
};
-class MaterialManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT MaterialManager : public Qt3DCore::QResourceManager<
Material,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -191,7 +188,7 @@ public:
MaterialManager() {}
};
-class MatrixManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT MatrixManager : public Qt3DCore::QResourceManager<
Matrix4x4,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -200,16 +197,31 @@ public:
MatrixManager() {}
};
-class ShaderManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderManager : public Qt3DCore::QResourceManager<
Shader,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
{
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<Qt3DCore::QNodeId> takeShaderIdsToCleanup()
+ {
+ return std::move(m_shaderIdsToCleanup);
+ }
+
+private:
+ QVector<Qt3DCore::QNodeId> m_shaderIdsToCleanup;
};
-class ShaderBuilderManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderBuilderManager : public Qt3DCore::QResourceManager<
ShaderBuilder,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -218,7 +230,7 @@ public:
ShaderBuilderManager() {}
};
-class TextureManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT TextureManager : public Qt3DCore::QResourceManager<
Texture,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -257,7 +269,7 @@ private:
QVector<Qt3DCore::QNodeId> m_textureIdsToCleanup;
};
-class TransformManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT TransformManager : public Qt3DCore::QResourceManager<
Transform,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -266,16 +278,7 @@ public:
TransformManager() {}
};
-class VAOManager : public Qt3DCore::QResourceManager<
- OpenGLVertexArrayObject,
- VAOIdentifier,
- Qt3DCore::NonLockingPolicy>
-{
-public:
- VAOManager() {}
-};
-
-class RenderTargetManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderTargetManager : public Qt3DCore::QResourceManager<
RenderTarget,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -284,7 +287,7 @@ public:
RenderTargetManager() {}
};
-class RenderPassManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderPassManager : public Qt3DCore::QResourceManager<
RenderPass,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -294,7 +297,7 @@ public:
};
-class ParameterManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ParameterManager : public Qt3DCore::QResourceManager<
Parameter,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -303,7 +306,7 @@ public:
ParameterManager() {}
};
-class ShaderImageManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderImageManager : public Qt3DCore::QResourceManager<
ShaderImage,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -312,7 +315,7 @@ public:
ShaderImageManager() {}
};
-class ShaderDataManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderDataManager : public Qt3DCore::QResourceManager<
ShaderData,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -321,46 +324,35 @@ public:
ShaderDataManager() {}
};
-class GLBufferManager : public Qt3DCore::QResourceManager<
- GLBuffer,
- Qt3DCore::QNodeId,
- Qt3DCore::NonLockingPolicy>
-{
-};
-
-class GLFenceManager : public QHash<Qt3DCore::QNodeId, GLFence>
-{
-};
-
-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>
@@ -376,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>
@@ -385,7 +377,7 @@ public:
LightManager() {}
};
-class EnvironmentLightManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT EnvironmentLightManager : public Qt3DCore::QResourceManager<
EnvironmentLight,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -394,7 +386,7 @@ public:
EnvironmentLightManager() {}
};
-class ComputeCommandManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ComputeCommandManager : public Qt3DCore::QResourceManager<
ComputeCommand,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -403,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>
@@ -436,7 +428,7 @@ private:
QVector<HSkeleton> m_dirtyTransformSkeletons;
};
-class JointManager : public Qt3DCore::QResourceManager<
+class Q_3DRENDERSHARED_PRIVATE_EXPORT JointManager : public Qt3DCore::QResourceManager<
Joint,
Qt3DCore::QNodeId,
Qt3DCore::NonLockingPolicy>
@@ -471,7 +463,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..df660a19e 100644
--- a/src/render/backend/nodemanagers.cpp
+++ b/src/render/backend/nodemanagers.cpp
@@ -42,14 +42,11 @@
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/scenemanager_p.h>
#include <Qt3DRender/private/buffermanager_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
#include <Qt3DRender/private/geometryrenderermanager_p.h>
#include <Qt3DRender/private/techniquemanager_p.h>
#include <Qt3DRender/private/armature_p.h>
#include <Qt3DRender/private/skeleton_p.h>
-#include <private/resourceaccessor_p.h>
-#include <QOpenGLVertexArrayObject>
QT_BEGIN_NAMESPACE
@@ -62,7 +59,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 +66,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 +76,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())
@@ -98,7 +91,6 @@ NodeManagers::NodeManagers()
, m_skeletonManager(new SkeletonManager())
, m_jointManager(new JointManager())
, m_shaderImageManager(new ShaderImageManager())
- , m_resourceAccessor(new ResourceAccessor(this))
{
}
@@ -107,13 +99,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 +114,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;
@@ -149,11 +137,6 @@ NodeManagers::~NodeManagers()
delete m_shaderImageManager;
}
-QSharedPointer<ResourceAccessor> NodeManagers::resourceAccessor()
-{
- return m_resourceAccessor;
-}
-
template<>
CameraManager *NodeManagers::manager<CameraLens>() const noexcept
{
@@ -179,12 +162,6 @@ MatrixManager *NodeManagers::manager<Matrix4x4>() const noexcept
}
template<>
-VAOManager *NodeManagers::manager<OpenGLVertexArrayObject>() const noexcept
-{
- return m_vaoManager;
-}
-
-template<>
ShaderManager *NodeManagers::manager<Shader>() const noexcept
{
return m_shaderManager;
@@ -281,12 +258,6 @@ ShaderDataManager *NodeManagers::manager<ShaderData>() const noexcept
}
template<>
-GLBufferManager *NodeManagers::manager<GLBuffer>() const noexcept
-{
- return m_glBufferManager;
-}
-
-template<>
TextureImageManager *NodeManagers::manager<TextureImage>() const noexcept
{
return m_textureImageManager;
diff --git a/src/render/backend/nodemanagers_p.h b/src/render/backend/nodemanagers_p.h
index 8dda4e8ad..e6f7469de 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,10 +138,8 @@ class RenderStateNode;
class Armature;
class Skeleton;
class Joint;
-class OpenGLVertexArrayObject;
class ShaderImage;
-class ResourceAccessor;
class Q_3DRENDERSHARED_PRIVATE_EXPORT NodeManagers
{
@@ -192,13 +185,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 +201,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; }
@@ -229,14 +218,11 @@ public:
inline JointManager *jointManager() const noexcept { return m_jointManager; }
inline ShaderImageManager *shaderImageManager() const noexcept { return m_shaderImageManager; }
- QSharedPointer<ResourceAccessor> resourceAccessor();
-
private:
CameraManager *m_cameraManager;
EntityManager *m_renderNodesManager;
MaterialManager *m_materialManager;
MatrixManager *m_worldMatrixManager;
- VAOManager *m_vaoManager;
ShaderManager *m_shaderManager;
ShaderBuilderManager *m_shaderBuilderManager;
TechniqueManager *m_techniqueManager;
@@ -244,7 +230,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 +240,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;
@@ -272,8 +255,6 @@ private:
SkeletonManager *m_skeletonManager;
JointManager *m_jointManager;
ShaderImageManager *m_shaderImageManager;
-
- QSharedPointer<ResourceAccessor> m_resourceAccessor;
};
// Specializations
@@ -291,9 +272,6 @@ template<>
Q_3DRENDERSHARED_PRIVATE_EXPORT MatrixManager *NodeManagers::manager<QMatrix4x4*>() const noexcept;
template<>
-Q_3DRENDERSHARED_PRIVATE_EXPORT VAOManager *NodeManagers::manager<OpenGLVertexArrayObject>() const noexcept;
-
-template<>
Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderManager *NodeManagers::manager<Shader>() const noexcept;
template<>
@@ -342,15 +320,12 @@ template<>
Q_3DRENDERSHARED_PRIVATE_EXPORT ShaderDataManager *NodeManagers::manager<ShaderData>() const noexcept;
template<>
-Q_3DRENDERSHARED_PRIVATE_EXPORT GLBufferManager *NodeManagers::manager<GLBuffer>() const noexcept;
+Q_3DRENDERSHARED_PRIVATE_EXPORT BufferManager *NodeManagers::manager<Buffer>() const noexcept;
template<>
Q_3DRENDERSHARED_PRIVATE_EXPORT TextureImageManager *NodeManagers::manager<TextureImage>() const noexcept;
template<>
-Q_3DRENDERSHARED_PRIVATE_EXPORT BufferManager *NodeManagers::manager<Buffer>() const noexcept;
-
-template<>
Q_3DRENDERSHARED_PRIVATE_EXPORT AttributeManager *NodeManagers::manager<Attribute>() const noexcept;
template<>
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 <QObject>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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 <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <QMetaObject>
#include <QPlatformSurfaceEvent>
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/render-backend.pri b/src/render/backend/render-backend.pri
index 9510b9530..4e46aa65b 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 \
@@ -32,12 +31,12 @@ 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 \
$$PWD/segmentsvisitor_p.h \
- $$PWD/pointsvisitor_p.h
+ $$PWD/pointsvisitor_p.h \
+ $$PWD/apishadermanager_p.h
SOURCES += \
$$PWD/renderthread.cpp \
@@ -68,10 +67,3 @@ SOURCES += \
$$PWD/resourceaccessor.cpp \
$$PWD/segmentsvisitor.cpp \
$$PWD/pointsvisitor.cpp
-
-include($$QT3D_BUILD_ROOT/src/core/qt3dcore-config.pri)
-QT_FOR_CONFIG += 3dcore-private
-qtConfig(qt3d-profile-jobs): {
- HEADERS += $$PWD/commandexecuter_p.h
- SOURCES += $$PWD/commandexecuter.cpp
-}
diff --git a/src/render/backend/rendersettings.cpp b/src/render/backend/rendersettings.cpp
index 487f6e11a..3af617bfc 100644
--- a/src/render/backend/rendersettings.cpp
+++ b/src/render/backend/rendersettings.cpp
@@ -42,7 +42,7 @@
#include <Qt3DRender/QFrameGraphNode>
#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/qrendersettings_p.h>
-#include <Qt3DCore/qnodecommand.h>
+#include <Qt3DRender/private/qrendercapabilities_p.h>
QT_BEGIN_NAMESPACE
@@ -79,22 +79,26 @@ 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<QRenderSettings *>(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 (!qFuzzyCompare(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();
}
+ if (firstTime)
+ m_capabilities = QRenderCapabilitiesPrivate::get(const_cast<QRenderSettings *>(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..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();
@@ -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/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 <QThread>
-
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QtCore/QSemaphore>
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 4f70df436..ebc55c7ca 100644
--- a/src/render/backend/resourceaccessor.cpp
+++ b/src/render/backend/resourceaccessor.cpp
@@ -40,12 +40,10 @@
#include <private/qrendertargetoutput_p.h>
#include <private/nodemanagers_p.h>
-#include <private/texture_p.h>
#include <private/rendertargetoutput_p.h>
-#include <private/gltexturemanager_p.h>
#include <private/managers_p.h>
-#include <private/gltexture_p.h>
+#include <Qt3DRender/qt3drender-config.h>
#include <QtCore/qmutex.h>
QT_BEGIN_NAMESPACE
@@ -58,8 +56,8 @@ RenderBackendResourceAccessor::~RenderBackendResourceAccessor()
}
-ResourceAccessor::ResourceAccessor(NodeManagers *mgr)
- : m_glTextureManager(mgr->glTextureManager())
+ResourceAccessor::ResourceAccessor(AbstractRenderer *renderer, NodeManagers *mgr)
+ : m_renderer(renderer)
, m_textureManager(mgr->textureManager())
, m_attachmentManager(mgr->attachmentManager())
, m_entityManager(mgr->renderNodesManager())
@@ -68,35 +66,28 @@ ResourceAccessor::ResourceAccessor(NodeManagers *mgr)
}
// 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) {
+ // 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:
{
- Texture *tex = m_textureManager->lookupResource(nodeId);
- if (!tex)
+ if (m_renderer->api() != AbstractRenderer::OpenGL) {
+ qWarning() << "Renderer plugin is not compatible with Scene2D";
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<QOpenGLTexture **>(handle);
- *glTextureHandle = glTex->getGLTexture();
-
- if (type == RenderBackendResourceAccessor::OGLTextureWrite)
- *lock = glTex->externalRenderingLock();
-
- return true;
+ }
+ return m_renderer->accessOpenGLTexture(nodeId,
+ reinterpret_cast<QOpenGLTexture **>(handle),
+ lock,
+ type == RenderBackendResourceAccessor::OGLTextureRead);
}
case RenderBackendResourceAccessor::OutputAttachment: {
diff --git a/src/render/backend/resourceaccessor_p.h b/src/render/backend/resourceaccessor_p.h
index ec53a04a2..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,10 +87,10 @@ 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;
+ AbstractRenderer *m_renderer;
TextureManager *m_textureManager;
AttachmentManager *m_attachmentManager;
EntityManager *m_entityManager;
diff --git a/src/render/backend/segmentsvisitor.cpp b/src/render/backend/segmentsvisitor.cpp
index a3a5d059c..d9f2d79ec 100644
--- a/src/render/backend/segmentsvisitor.cpp
+++ b/src/render/backend/segmentsvisitor.cpp
@@ -135,34 +135,44 @@ void traverseSegmentStripIndexed(Index *indices,
bool loop)
{
uint i = 0;
+ uint stripStartIndex = 0;
+
const uint verticesStride = vertexInfo.byteStride / sizeof(Vertex);
const uint maxVerticesDataSize = qMin(vertexInfo.dataSize, 3U);
uint ndx[2];
Vector3D abc[2];
- ndx[0] = indices[0];
- uint idx = ndx[0] * verticesStride;
- for (uint j = 0; j < maxVerticesDataSize; ++j)
- abc[0][j] = vertices[idx + j];
- while (i < indexInfo.count - 1) {
- ndx[1] = indices[i + 1];
- if (ndx[0] != ndx[1]) {
- idx = ndx[1] * verticesStride;
- for (uint j = 0; j < maxVerticesDataSize; ++j)
- abc[1][j] = vertices[idx + j];
- visitor->visit(ndx[0], abc[0], ndx[1], abc[1]);
+ while (i < indexInfo.count) {
+ if (indexInfo.restartEnabled && indexInfo.restartIndexValue == static_cast<int>(indices[i])) {
+ ++i;
+ continue;
}
+ stripStartIndex = i;
+ ndx[0] = indices[stripStartIndex];
+ uint idx = ndx[0] * verticesStride;
+ for (uint j = 0; j < maxVerticesDataSize; ++j)
+ abc[0][j] = vertices[idx + j];
++i;
- ndx[0] = ndx[1];
- abc[0] = abc[1];
- }
- if (loop) {
- ndx[1] = indices[0];
- if (ndx[0] != ndx[1]) {
- idx = ndx[1] * verticesStride;
- for (uint j = 0; j < maxVerticesDataSize; ++j)
- abc[1][j] = vertices[idx + j];
- visitor->visit(ndx[0], abc[0], ndx[1], abc[1]);
+ while (i < indexInfo.count && (!indexInfo.restartEnabled || indexInfo.restartIndexValue != static_cast<int>(indices[i]))) {
+ ndx[1] = indices[i];
+ if (ndx[0] != ndx[1]) {
+ idx = ndx[1] * verticesStride;
+ for (uint j = 0; j < maxVerticesDataSize; ++j)
+ abc[1][j] = vertices[idx + j];
+ visitor->visit(ndx[0], abc[0], ndx[1], abc[1]);
+ }
+ ++i;
+ ndx[0] = ndx[1];
+ abc[0] = abc[1];
+ }
+ if (loop) {
+ ndx[1] = indices[stripStartIndex];
+ if (ndx[0] != ndx[1]) {
+ idx = ndx[1] * verticesStride;
+ for (uint j = 0; j < maxVerticesDataSize; ++j)
+ abc[1][j] = vertices[idx + j];
+ visitor->visit(ndx[0], abc[0], ndx[1], abc[1]);
+ }
}
}
}
diff --git a/src/render/backend/stringtoint.cpp b/src/render/backend/stringtoint.cpp
index 5659da394..0e0d38c9c 100644
--- a/src/render/backend/stringtoint.cpp
+++ b/src/render/backend/stringtoint.cpp
@@ -50,9 +50,18 @@ namespace Render {
namespace {
-QReadWriteLock lock;
-QHash<QString, int> map = QHash<QString, int>();
-QVector<QString> reverseMap = QVector<QString>();
+struct StringToIntCache
+{
+ QReadWriteLock lock;
+ QHash<QString, int> map = QHash<QString, int>();
+ QVector<QString> reverseMap = QVector<QString>();
+
+ static StringToIntCache& instance()
+ {
+ static StringToIntCache c;
+ return c;
+ }
+};
} // anonymous
@@ -64,20 +73,21 @@ int StringToInt::lookupId(QLatin1String str)
int StringToInt::lookupId(const QString &str)
{
+ auto& cache = StringToIntCache::instance();
int idx;
{
- QReadLocker readLocker(&lock);
- idx = map.value(str, -1);
+ QReadLocker readLocker(&cache.lock);
+ idx = cache.map.value(str, -1);
}
if (Q_UNLIKELY(idx < 0)) {
- QWriteLocker writeLocker(&lock);
- idx = map.value(str, -1);
+ QWriteLocker writeLocker(&cache.lock);
+ idx = cache.map.value(str, -1);
if (idx < 0) {
- idx = reverseMap.size();
- Q_ASSERT(map.size() == reverseMap.size());
- map.insert(str, idx);
- reverseMap.append(str);
+ idx = cache.reverseMap.size();
+ Q_ASSERT(cache.map.size() == cache.reverseMap.size());
+ cache.map.insert(str, idx);
+ cache.reverseMap.append(str);
}
}
return idx;
@@ -85,9 +95,10 @@ int StringToInt::lookupId(const QString &str)
QString StringToInt::lookupString(int idx)
{
- QReadLocker readLocker(&lock);
- if (Q_LIKELY(reverseMap.size() > idx))
- return reverseMap.at(idx);
+ auto& cache = StringToIntCache::instance();
+ QReadLocker readLocker(&cache.lock);
+ if (Q_LIKELY(cache.reverseMap.size() > idx))
+ return cache.reverseMap.at(idx);
return QString();
}
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 <QVector>
#include <QString>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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.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 <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qchangearbiter_p.h>
#include <Qt3DCore/qtransform.h>
#include <Qt3DCore/private/qtransform_p.h>
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/trianglesvisitor.cpp b/src/render/backend/trianglesvisitor.cpp
index 87ba7bde9..a58f2d20b 100644
--- a/src/render/backend/trianglesvisitor.cpp
+++ b/src/render/backend/trianglesvisitor.cpp
@@ -153,6 +153,10 @@ void traverseTriangleStripIndexed(index *indices,
uint ndx[3];
Vector3D abc[3];
while (i < indexInfo.count - 2) {
+ if (indexInfo.restartEnabled && indexInfo.restartIndexValue == static_cast<int>(indices[i + 2])) {
+ i += 3;
+ continue;
+ }
bool degenerate = false;
for (uint u = 0; u < 3; ++u) {
ndx[u] = indices[i + u];
@@ -216,6 +220,11 @@ void traverseTriangleFanIndexed(index *indices,
ndx[0] = indices[0];
uint i = 1;
while (i < indexInfo.count - 1) {
+ if (indexInfo.restartEnabled && indexInfo.restartIndexValue == static_cast<int>(indices[i + 1])) {
+ ndx[0] = indices[i + 2];
+ i += 3;
+ continue;
+ }
for (uint u = 0; u < 2; ++u) {
ndx[u + 1] = indices[i + u];
uint idx = ndx[u + 1] * verticesStride;
@@ -224,7 +233,7 @@ void traverseTriangleFanIndexed(index *indices,
}
}
visitor->visit(ndx[2], abc[2], ndx[1], abc[1], ndx[0], abc[0]);
- i += 1;
+ ++i;
}
}
diff --git a/src/render/backend/uniform_p.h b/src/render/backend/uniform_p.h
index 09575a077..eb959923a 100644
--- a/src/render/backend/uniform_p.h
+++ b/src/render/backend/uniform_p.h
@@ -56,7 +56,7 @@
#include <Qt3DCore/private/matrix4x4_p.h>
#include <Qt3DCore/private/vector3d_p.h>
#include <Qt3DCore/private/vector4d_p.h>
-
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QMatrix4x4>
#include <QVector2D>
#include <QVector3D>
@@ -105,7 +105,7 @@ enum UniformType {
Unknown
};
-class Q_AUTOTEST_EXPORT UniformValue
+class Q_3DRENDERSHARED_PRIVATE_EXPORT UniformValue
{
public:
enum ValueType {
@@ -227,9 +227,9 @@ public:
return !(*this == other);
}
private:
- // Allocate 4 floats on stack
+ // Allocate 16 floats on stack
// For larger elements, heap allocation will be used
- QVarLengthArray<float, 4> m_data;
+ QVarLengthArray<float, 16> m_data;
ValueType m_valueType = ScalarValue;
@@ -238,7 +238,7 @@ private:
};
template<>
-Q_AUTOTEST_EXPORT void UniformValue::setData<QMatrix4x4>(const QVector<QMatrix4x4> &v);
+Q_3DRENDERSHARED_PRIVATE_EXPORT void UniformValue::setData<QMatrix4x4>(const QVector<QMatrix4x4> &v);
} // namespace Render
} // namespace Qt3DRender
diff --git a/src/render/backend/visitorutils_p.h b/src/render/backend/visitorutils_p.h
index 6a5c7b4ff..14183e11b 100644
--- a/src/render/backend/visitorutils_p.h
+++ b/src/render/backend/visitorutils_p.h
@@ -149,6 +149,8 @@ void visitPrimitives(NodeManagers *manager, const GeometryRenderer *renderer, Vi
indexBufferInfo.byteOffset = indexAttribute->byteOffset();
indexBufferInfo.byteStride = indexAttribute->byteStride();
indexBufferInfo.count = indexAttribute->count();
+ indexBufferInfo.restartEnabled = renderer->primitiveRestartEnabled();
+ indexBufferInfo.restartIndexValue = renderer->restartIndexValue();
IndexExecutor executor;
executor.m_vertexBufferInfo = vertexBufferInfo;
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 <Qt3DRender/private/qcameraselector_p.h>
-#include <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
+#include <Qt3DCore/private/qchangearbiter_p.h>
#include <Qt3DCore/qentity.h>
#include <Qt3DRender/private/renderlogging_p.h>
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/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 <Qt3DRender/private/qdebugoverlay_p.h>
+#include <Qt3DRender/private/debugoverlay_p.h>
+
+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 <Qt3DRender/private/qdebugoverlay_p.h>
+#include <Qt3DRender/private/framegraphnode_p.h>
+
+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/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/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.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 <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/qframegraphnodecreatedchange.h>
diff --git a/src/render/framegraph/framegraphnode_p.h b/src/render/framegraph/framegraphnode_p.h
index 846dc8060..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();
@@ -104,7 +104,8 @@ public:
BlitFramebuffer,
SetFence,
WaitFence,
- NoPicking
+ NoPicking,
+ DebugOverlay,
};
FrameGraphNodeType nodeType() const { return m_nodeType; }
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 <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <QThreadPool>
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 <qglobal.h>
#include <Qt3DCore/qaspectjob.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QVector>
@@ -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/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/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/qblitframebuffer.cpp b/src/render/framegraph/qblitframebuffer.cpp
index 3a26e3d56..252758af4 100644
--- a/src/render/framegraph/qblitframebuffer.cpp
+++ b/src/render/framegraph/qblitframebuffer.cpp
@@ -70,6 +70,10 @@ namespace Qt3DRender {
Specifies the interpolation applied if the image is stretched.
+ \value Nearest
+ Nearest-neighbor interpolation.
+ \value Linear
+ Linear interpolation.
*/
/*!
\property Qt3DRender::QBlitFramebuffer::destination
diff --git a/src/render/framegraph/qbuffercapture.cpp b/src/render/framegraph/qbuffercapture.cpp
index 0c12a3aff..3eaa5dfd2 100644
--- a/src/render/framegraph/qbuffercapture.cpp
+++ b/src/render/framegraph/qbuffercapture.cpp
@@ -39,8 +39,8 @@
#include <Qt3DRender/qbuffercapture.h>
#include <Qt3DRender/private/qbuffercapture_p.h>
-#include <Qt3DCore/QSceneChange>
-#include <Qt3DRender/QFrameGraphNodeCreatedChange>
+#include <Qt3DCore/qscenechange.h>
+#include <Qt3DRender/qframegraphnodecreatedchange.h>
QT_BEGIN_NAMESPACE
@@ -62,6 +62,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)
{
diff --git a/src/render/jobs/sendrendercapturejob.cpp b/src/render/framegraph/qdebugoverlay.cpp
index f622c347a..d82ae88ba 100644
--- a/src/render/jobs/sendrendercapturejob.cpp
+++ b/src/render/framegraph/qdebugoverlay.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** 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.
@@ -34,53 +34,34 @@
**
****************************************************************************/
-#include "sendrendercapturejob_p.h"
-
-#include "Qt3DRender/private/renderer_p.h"
-#include "Qt3DRender/private/nodemanagers_p.h"
-#include "Qt3DRender/private/rendercapture_p.h"
-#include <Qt3DRender/private/job_common_p.h>
+#include "qdebugoverlay.h"
+#include "qdebugoverlay_p.h"
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
-namespace Render {
-
-SendRenderCaptureJob::SendRenderCaptureJob()
- : Qt3DCore::QAspectJob()
- , m_managers(nullptr)
-{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::SendRenderCapture, 0);
-}
-
-SendRenderCaptureJob::~SendRenderCaptureJob()
-{
-
-}
-
-void SendRenderCaptureJob::setPendingCaptureRequests(const QVector<Qt3DCore::QNodeId> &requests)
+/*!
+ * \internal
+ */
+QDebugOverlayPrivate::QDebugOverlayPrivate()
+ : QFrameGraphNodePrivate()
{
- m_pendingCaptures = requests;
}
-void SendRenderCaptureJob::setManagers(NodeManagers *managers)
-{
- m_managers = managers;
-}
+/*!
+ * \internal
+ */
+QDebugOverlayPrivate::~QDebugOverlayPrivate() = default;
-void SendRenderCaptureJob::run()
+/*!
+ * The constructor creates an instance with the specified \a parent.
+ */
+QDebugOverlay::QDebugOverlay(Qt3DCore::QNode *parent)
+ : QFrameGraphNode(*new QDebugOverlayPrivate, parent)
{
- for (const Qt3DCore::QNodeId id : qAsConst(m_pendingCaptures)) {
- auto *node = static_cast<Qt3DRender::Render::RenderCapture *>
- (m_managers->frameGraphManager()->lookupNode(id));
- node->sendRenderCaptures();
- }
- m_pendingCaptures.clear();
}
-} // Render
-
} // 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 <Qt3DRender/QFrameGraphNode>
+#include <QtGui/QImage>
+
+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/jobs/sendrendercapturejob_p.h b/src/render/framegraph/qdebugoverlay_p.h
index 8bc1e2fb0..f8c34655a 100644
--- a/src/render/jobs/sendrendercapturejob_p.h
+++ b/src/render/framegraph/qdebugoverlay_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** 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.
@@ -34,9 +34,8 @@
**
****************************************************************************/
-#ifndef SENDRENDERCAPTUREJOB_P_H
-#define SENDRENDERCAPTUREJOB_P_H
-
+#ifndef QDEBUGOVERLAY_P_H
+#define QDEBUGOVERLAY_P_H
//
// W A R N I N G
@@ -49,42 +48,26 @@
// We mean it.
//
-#include <Qt3DCore/qaspectjob.h>
-#include <Qt3DCore/qnodeid.h>
-#include <Qt3DRender/qt3drender_global.h>
-#include <Qt3DRender/private/qt3drender_global_p.h>
+#include <Qt3DRender/qdebugoverlay.h>
+#include <Qt3DRender/private/qframegraphnode_p.h>
+
+#include <QtCore/qmutex.h>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
-namespace Render {
-
-class NodeManagers;
-class Entity;
-
-class Q_3DRENDERSHARED_PRIVATE_EXPORT SendRenderCaptureJob : public Qt3DCore::QAspectJob
+class QDebugOverlayPrivate : public QFrameGraphNodePrivate
{
public:
- SendRenderCaptureJob();
- ~SendRenderCaptureJob();
+ QDebugOverlayPrivate();
+ ~QDebugOverlayPrivate();
- void setPendingCaptureRequests(const QVector<Qt3DCore::QNodeId> &requests);
- void setManagers(NodeManagers *managers);
-
- void run() final;
-
-private:
- NodeManagers *m_managers;
- QVector<Qt3DCore::QNodeId> m_pendingCaptures;
+ Q_DECLARE_PUBLIC(QDebugOverlay)
};
-typedef QSharedPointer<SendRenderCaptureJob> SendRenderCaptureJobPtr;
-
-} // namespace Render
-
-} // namespace Qt3DRender
+} // Qt3DRender
QT_END_NAMESPACE
-#endif // SENDRENDERCAPTUREJOB_P_H
+#endif // QDEBUGOVERLAY_P_H
diff --git a/src/render/framegraph/qframegraphnode.cpp b/src/render/framegraph/qframegraphnode.cpp
index 2390cb1c9..f49f6433a 100644
--- a/src/render/framegraph/qframegraphnode.cpp
+++ b/src/render/framegraph/qframegraphnode.cpp
@@ -49,6 +49,51 @@ using namespace Qt3DCore;
QT_BEGIN_NAMESPACE
+namespace {
+
+QString dumpNode(const Qt3DRender::QFrameGraphNode *n) {
+ QString res = QLatin1String(n->metaObject()->className());
+ if (!n->objectName().isEmpty())
+ res += QString(QLatin1String(" (%1)")).arg(n->objectName());
+ if (!n->isEnabled())
+ res += QLatin1String(" [D]");
+ return res;
+}
+
+QStringList dumpFG(const Qt3DRender::QFrameGraphNode *n, int level = 0)
+{
+ QStringList reply;
+ QString res = dumpNode(n);
+ reply += res.rightJustified(res.length() + level * 2, ' ');
+
+ const auto children = n->childNodes();
+ for (auto *child: children) {
+ auto *childFGNode = qobject_cast<Qt3DRender::QFrameGraphNode *>(child);
+ if (childFGNode != nullptr)
+ reply += dumpFG(childFGNode, level + 1);
+ }
+
+ return reply;
+}
+
+void dumpFGPaths(const Qt3DRender::QFrameGraphNode *n, QStringList &result, QStringList parents = {})
+{
+ parents += dumpNode(n);
+
+ const auto children = n->childNodes();
+ if (children.length()) {
+ for (auto *child: children) {
+ auto *childFGNode = qobject_cast<Qt3DRender::QFrameGraphNode *>(child);
+ if (childFGNode != nullptr)
+ dumpFGPaths(childFGNode, result, parents);
+ }
+ } else {
+ result << QLatin1String("[ ") + parents.join(QLatin1String(", ")) + QLatin1String(" ]");
+ }
+}
+
+}
+
namespace Qt3DRender {
QFrameGraphNodePrivate::QFrameGraphNodePrivate()
@@ -240,6 +285,20 @@ QVector<QFrameGraphNode *> QFrameGraphNodePrivate::childFrameGraphNodes() const
return result;
}
+QString QFrameGraphNodePrivate::dumpFrameGraph() const
+{
+ Q_Q(const QFrameGraphNode);
+ return dumpFG(q).join('\n');
+}
+
+QStringList QFrameGraphNodePrivate::dumpFrameGraphPaths() const
+{
+ Q_Q(const QFrameGraphNode);
+ QStringList result;
+ dumpFGPaths(q, result);
+ return result;
+}
+
/*! \internal */
QFrameGraphNode::QFrameGraphNode(QFrameGraphNodePrivate &dd, QNode *parent)
: QNode(dd, parent)
diff --git a/src/render/framegraph/qframegraphnode_p.h b/src/render/framegraph/qframegraphnode_p.h
index c03017638..4d9516b88 100644
--- a/src/render/framegraph/qframegraphnode_p.h
+++ b/src/render/framegraph/qframegraphnode_p.h
@@ -70,6 +70,9 @@ public:
static QFrameGraphNodePrivate *get(QFrameGraphNode *node) { return node->d_func(); }
static const QFrameGraphNodePrivate *get(const QFrameGraphNode *node) { return node->d_func(); }
+ QString dumpFrameGraph() const;
+ QStringList dumpFrameGraphPaths() const;
+
Q_DECLARE_PUBLIC(QFrameGraphNode)
};
diff --git a/src/render/framegraph/qrendercapture.cpp b/src/render/framegraph/qrendercapture.cpp
index cc74553b2..a10083374 100644
--- a/src/render/framegraph/qrendercapture.cpp
+++ b/src/render/framegraph/qrendercapture.cpp
@@ -36,8 +36,8 @@
#include <Qt3DRender/qrendercapture.h>
#include <Qt3DRender/private/qrendercapture_p.h>
-#include <Qt3DCore/QSceneChange>
-#include <Qt3DCore/QPropertyUpdatedChange>
+#include <Qt3DCore/qscenechange.h>
+#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DRender/qframegraphnodecreatedchange.h>
#include <QPointer>
diff --git a/src/render/framegraph/qsetfence.cpp b/src/render/framegraph/qsetfence.cpp
index 5cb82f3db..262dbd4ad 100644
--- a/src/render/framegraph/qsetfence.cpp
+++ b/src/render/framegraph/qsetfence.cpp
@@ -54,7 +54,8 @@ QSetFencePrivate::QSetFencePrivate()
}
/*!
- \class QSetFence
+ \class Qt3DRender::QSetFence
+ \inmodule Qt3DRender
\brief FrameGraphNode used to insert a fence in the graphics command stream.
Fence allow to synchronosize GPU and CPU workloads. GPU commands usually
@@ -100,7 +101,7 @@ QSetFence::QSetFence(QSetFencePrivate &dd, Qt3DCore::QNode *parent)
are supported.
*/
/*!
- \property QSetFence::handleType
+ \property Qt3DRender::QSetFence::handleType
Specifies the type of handle being used. Currently only OpenGL Fence ids
are supported.
@@ -123,12 +124,12 @@ void QSetFencePrivate::setHandleType(QSetFence::HandleType type)
}
/*!
- \qmlproperty variant AbstractFence::handle
+ \qmlproperty variant SetFence::handle
Holds the underlying fence handle wrapped in a variant.
*/
/*!
- \property QAbstractFence::handle
+ \property Qt3DRender::QSetFence::handle
Holds the underlying fence handle wrapped in a QVariant.
*/
diff --git a/src/render/framegraph/qsortpolicy.cpp b/src/render/framegraph/qsortpolicy.cpp
index a24dd5eae..5c04025b0 100644
--- a/src/render/framegraph/qsortpolicy.cpp
+++ b/src/render/framegraph/qsortpolicy.cpp
@@ -98,12 +98,14 @@ QSortPolicyPrivate::QSortPolicyPrivate()
projection of the camera-to-object-center vector onto the camera's view
vector.
- \value Material sort the objects based on their material value
+ \value Material sort the objects based on their material (shader) value.
\value FrontToBack sort the objects from front to back. The opposite of
BackToFront.
\value [since 5.14] Texture sort the objects to minimize texture changes.
+
+ \value [since 5.15] Uniform sort the objects to minimize uniform changes.
*/
/*!
@@ -123,10 +125,11 @@ QSortPolicyPrivate::QSortPolicyPrivate()
order. More accurately, the sorting key is the z component of the
projection of the camera-to-object-center vector onto the camera's view
vector.
- \li Material - sort the objects based on their material value
+ \li Material - sort the objects based on their material (shader) value.
\li FrontToBack - sort the objects from front to back. The opposite of
BackToFront.
\li [since 5.14] Texture - sort the objects to minimize texture changes.
+ \li [since 5.15] Uniform - sort the objects to minimize uniform changes.
\endlist
*/
diff --git a/src/render/framegraph/qsortpolicy.h b/src/render/framegraph/qsortpolicy.h
index a302caa8b..f5ea988e8 100644
--- a/src/render/framegraph/qsortpolicy.h
+++ b/src/render/framegraph/qsortpolicy.h
@@ -62,6 +62,7 @@ public:
Material = (1 << 2),
FrontToBack = (1 << 3),
Texture = (1 << 4),
+ Uniform = (1 << 5)
};
Q_ENUM(SortType) // LCOV_EXCL_LINE
diff --git a/src/render/framegraph/qwaitfence.cpp b/src/render/framegraph/qwaitfence.cpp
index 5195653ce..737f4e54d 100644
--- a/src/render/framegraph/qwaitfence.cpp
+++ b/src/render/framegraph/qwaitfence.cpp
@@ -56,8 +56,8 @@ QWaitFencePrivate::QWaitFencePrivate()
}
/*!
- \class QWaitFence
-
+ \class Qt3DRender::QWaitFence
+ \inmodule Qt3DRender
\brief FrameGraphNode used to wait for a fence in the graphics command
stream to become signaled.
@@ -98,7 +98,7 @@ QWaitFence::~QWaitFence()
become signaled. This is false by default.
*/
/*!
- \property QWaitFence::waitOnCPU
+ \property Qt3DRender::QWaitFence::waitOnCPU
Specifies whether the CPU should be block while waiting for the fence to
become signaled. This is false by default.
@@ -125,7 +125,7 @@ void QWaitFence::setWaitOnCPU(bool waitOnCPU)
to become signaled.
*/
/*!
- \property QWaitFence::timeout
+ \property Qt3DRender::QWaitFence::timeout
Specifies the maximum amount of time in nanoseconds to wait for the fence
to become signaled.
@@ -157,7 +157,7 @@ QWaitFence::QWaitFence(QWaitFencePrivate &dd, Qt3DCore::QNode *parent)
are supported.
*/
/*!
- \property QWaitFence::handleType
+ \property Qt3DRender::QWaitFence::handleType
Specifies the type of handle being used. Currently only OpenGL Fence ids
are supported.
@@ -183,7 +183,7 @@ void QWaitFence::setHandleType(QWaitFence::HandleType type)
Holds the underlying fence handle wrapped in a variant.
*/
/*!
- \property QWaitFence::handle
+ \property Qt3DRender::QWaitFence::handle
Holds the underlying fence handle wrapped in a QVariant.
*/
diff --git a/src/render/framegraph/rendercapture.cpp b/src/render/framegraph/rendercapture.cpp
index 68d62b6a5..73d8770a7 100644
--- a/src/render/framegraph/rendercapture.cpp
+++ b/src/render/framegraph/rendercapture.cpp
@@ -37,6 +37,8 @@
#include <Qt3DRender/private/qrendercapture_p.h>
#include <Qt3DRender/private/rendercapture_p.h>
#include <Qt3DCore/qpropertyupdatedchange.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DCore/private/qaspectjobmanager_p.h>
QT_BEGIN_NAMESPACE
@@ -99,17 +101,25 @@ void RenderCapture::addRenderCapture(int captureId, const QImage &image)
m_renderCaptureData.push_back(data);
}
-// called by send render capture job thread
-void RenderCapture::sendRenderCaptures()
+// called to send render capture in main thread
+void RenderCapture::syncRenderCapturesToFrontend(Qt3DCore::QAspectManager *manager)
{
- QMutexLocker lock(&m_mutex);
+ auto *frontend = manager->lookupNode(peerId());
+ if (!frontend)
+ return;
+ QRenderCapturePrivate *dfrontend = static_cast<QRenderCapturePrivate *>(Qt3DCore::QNodePrivate::get(frontend));
+ QMutexLocker lock(&m_mutex);
for (const RenderCaptureDataPtr &data : qAsConst(m_renderCaptureData)) {
- auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(peerId());
- e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll);
- e->setPropertyName("renderCaptureData");
- e->setValue(QVariant::fromValue(data));
- notifyObservers(e);
+ QPointer<QRenderCaptureReply> reply = dfrontend->takeReply(data.data()->captureId);
+ if (reply) {
+ dfrontend->setImage(reply, data.data()->image);
+ emit reply->completed();
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
+ emit reply->completeChanged(true);
+QT_WARNING_POP
+ }
}
m_renderCaptureData.clear();
}
diff --git a/src/render/framegraph/rendercapture_p.h b/src/render/framegraph/rendercapture_p.h
index 4560c525d..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();
@@ -66,9 +66,9 @@ public:
bool wasCaptureRequested() const;
QRenderCaptureRequest takeCaptureRequest();
void addRenderCapture(int captureId, const QImage &image);
- void sendRenderCaptures();
void syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime) override;
+ void syncRenderCapturesToFrontend(Qt3DCore::QAspectManager *manager);
private:
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 <Qt3DRender/qrendersurfaceselector.h>
#include <Qt3DRender/private/qrendersurfaceselector_p.h>
-
#include <QtGui/qwindow.h>
#include <QtGui/qscreen.h>
#include <QtGui/qoffscreensurface.h>
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 <Qt3DRender/private/renderer_p.h>
#include <Qt3DCore/private/qchangearbiter_p.h>
#include <Qt3DRender/qrendertargetselector.h>
#include <Qt3DRender/private/qrendertargetselector_p.h>
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.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 <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
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 160e1a5b5..37989df1a 100644
--- a/src/render/framegraph/subtreeenabler.cpp
+++ b/src/render/framegraph/subtreeenabler.cpp
@@ -39,7 +39,6 @@
#include "subtreeenabler_p.h"
#include <Qt3DRender/private/qsubtreeenabler_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -52,30 +51,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<const QSubtreeEnabler *>(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/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/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<class T>
-qintptr functorTypeId()
+Q3D_DECL_DEPRECATED qintptr functorTypeId()
{
return reinterpret_cast<qintptr>(&FunctorType<T>::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/frontend/qcamera.cpp b/src/render/frontend/qcamera.cpp
index 2dcec7ed6..4d4e5bf4d 100644
--- a/src/render/frontend/qcamera.cpp
+++ b/src/render/frontend/qcamera.cpp
@@ -227,7 +227,7 @@ void QCameraPrivate::updateViewMatrixAndTransform(bool doEmit)
* Rotates and moves the camera so that it's viewCenter is the center of the scene's bounding volume
* and the entire scene fits in the view port.
*
- * \note Only works if the lens is in perspective projection mode.
+ * \note Only works if the lens is in perspective or orthographic projection mode.
* \sa Qt3D.Render::Camera::projectionType
*/
@@ -235,9 +235,9 @@ void QCameraPrivate::updateViewMatrixAndTransform(bool doEmit)
* \qmlmethod void Qt3D.Render::Camera::viewEntity(Entity entity)
*
* Rotates and moves the camera so that it's viewCenter is the center of the entity's bounding volume
- * and the entire entity fits in the view port.
+ * and the entire \a entity fits in the view port.
*
- * \note Only works if the lens is in perspective projection mode.
+ * \note Only works if the lens is in perspective or orthographic projection mode.
* \sa Qt3D.Render::Camera::projectionType
*/
@@ -247,7 +247,7 @@ void QCameraPrivate::updateViewMatrixAndTransform(bool doEmit)
* Rotates and moves the camera so that it's viewCenter is \a center
* and a sphere of \a radius fits in the view port.
*
- * \note Only works if the lens is in perspective projection mode.
+ * \note Only works if the lens is in perspective or orthographic projection mode.
* \sa Qt3D.Render::Camera::projectionType
*/
@@ -823,7 +823,7 @@ void QCamera::rotateAboutViewCenter(const QQuaternion& q)
* Rotates and moves the camera so that it's viewCenter is the center of the scene's bounding volume
* and the entire scene fits in the view port.
*
- * \note Only works if the lens is in perspective projection mode.
+ * \note Only works if the lens is in perspective or orthographic projection mode.
* \sa Qt3D.Render::Camera::projectionType
*/
void QCamera::viewAll()
@@ -836,15 +836,31 @@ void QCamera::viewAll()
* Rotates and moves the camera so that it's viewCenter is \a center
* and a sphere of \a radius fits in the view port.
*
- * \note Only works if the lens is in perspective projection mode.
+ * \note Only works if the lens is in perspective or orthographic projection mode.
* \sa Qt3D.Render::Camera::projectionType
*/
void QCamera::viewSphere(const QVector3D &center, float radius)
{
Q_D(QCamera);
- if (d->m_lens->projectionType() != QCameraLens::PerspectiveProjection || radius <= 0.f)
+ if ((d->m_lens->projectionType() != QCameraLens::PerspectiveProjection &&
+ d->m_lens->projectionType() != QCameraLens::OrthographicProjection) ||
+ radius <= 0.f)
return;
- double dist = radius / std::tan(qDegreesToRadians(d->m_lens->fieldOfView()) / 2.0f);
+
+ // Ensure the sphere fits in the view port even if aspect ratio < 1 (i.e. width < height)
+ float height = (1.05f * radius) / (d->m_lens->aspectRatio() < 1.0f ? d->m_lens->aspectRatio() : 1.0f);
+ float dist = 1.0f;
+ if (d->m_lens->projectionType() == QCameraLens::PerspectiveProjection) {
+ dist = height / std::sin(qDegreesToRadians(d->m_lens->fieldOfView()) / 2.0f);
+ }
+ else if (d->m_lens->projectionType() == QCameraLens::OrthographicProjection) {
+ d->m_lens->setOrthographicProjection(-height * d->m_lens->aspectRatio(), height * d->m_lens->aspectRatio(), -height, height,
+ nearPlane(), farPlane());
+ dist = height / std::sin(qDegreesToRadians(d->m_lens->fieldOfView()) / 2.0f);
+ }
+ else {
+ dist = (d->m_viewCenter - d->m_position).length();
+ }
QVector3D dir = (d->m_viewCenter - d->m_position).normalized();
QVector3D newPos = center - (dir * dist);
setViewCenter(center);
@@ -855,7 +871,7 @@ void QCamera::viewSphere(const QVector3D &center, float radius)
* Rotates and moves the camera so that it's viewCenter is the center of the
* \a {entity}'s bounding volume and the entire entity fits in the view port.
*
- * \note Only works if the lens is in perspective projection mode.
+ * \note Only works if the lens is in perspective or orthographic projection mode.
* \sa {Qt3D.Render::Camera::projectionType}{Camera.projectionType}
*/
void QCamera::viewEntity(Qt3DCore::QEntity *entity)
diff --git a/src/render/frontend/qcameralens.cpp b/src/render/frontend/qcameralens.cpp
index cf30b714a..621b22778 100644
--- a/src/render/frontend/qcameralens.cpp
+++ b/src/render/frontend/qcameralens.cpp
@@ -232,12 +232,8 @@ QCameraLensPrivate::QCameraLensPrivate()
void QCameraLens::viewAll(Qt3DCore::QNodeId cameraId)
{
Q_D(QCameraLens);
- if (d->m_projectionType == PerspectiveProjection) {
- QVariant v;
- v.setValue(cameraId);
- d->m_pendingViewAllCommand = {QLatin1String("QueryRootBoundingVolume"),
- v,
- id()};
+ if (d->m_projectionType == PerspectiveProjection || d->m_projectionType == OrthographicProjection) {
+ d->m_pendingViewAllRequest = {Qt3DCore::QNodeId::createId(), cameraId, {}};
d->update();
}
}
@@ -245,31 +241,20 @@ void QCameraLens::viewAll(Qt3DCore::QNodeId cameraId)
void QCameraLens::viewEntity(Qt3DCore::QNodeId entityId, Qt3DCore::QNodeId cameraId)
{
Q_D(QCameraLens);
- if (d->m_projectionType == PerspectiveProjection) {
- QVector<Qt3DCore::QNodeId> ids = {entityId, cameraId};
- QVariant v;
- v.setValue(ids);
- d->m_pendingViewAllCommand = {QLatin1String("QueryEntityBoundingVolume"),
- v,
- id()};
+ if (d->m_projectionType == PerspectiveProjection || d->m_projectionType == OrthographicProjection) {
+ d->m_pendingViewAllRequest = {Qt3DCore::QNodeId::createId(), cameraId, entityId};
d->update();
}
}
-void QCameraLensPrivate::processViewAllCommand(Qt3DCore::QNodeCommand::CommandId commandId,
- const QVariant &data)
+void QCameraLensPrivate::processViewAllResult(Qt3DCore::QNodeId requestId, const QVector3D &center, float radius)
{
Q_Q(QCameraLens);
- if (!m_pendingViewAllCommand || m_pendingViewAllCommand.commandId != commandId)
+ if (!m_pendingViewAllRequest || m_pendingViewAllRequest.requestId != requestId)
return;
- QVector<float> boundingVolumeData = data.value< QVector<float> >();
- if (boundingVolumeData.size() != 4)
- return;
- QVector3D center(boundingVolumeData[0], boundingVolumeData[1], boundingVolumeData[2]);
- float radius = boundingVolumeData[3];
Q_EMIT q->viewSphere(center, radius);
- m_pendingViewAllCommand = {};
+ m_pendingViewAllRequest = {};
}
/*!
@@ -643,18 +628,7 @@ Qt3DCore::QNodeCreatedChangeBasePtr QCameraLens::createNodeCreationChange() cons
void QCameraLens::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change)
{
- Q_D(QCameraLens);
- switch (change->type()) {
- case Qt3DCore::CommandRequested: {
- Qt3DCore::QNodeCommandPtr command = qSharedPointerCast<Qt3DCore::QNodeCommand>(change);
-
- if (command->name() == QLatin1String("ViewAll"))
- d->processViewAllCommand(command->inReplyTo(), command->data());
- }
- break;
- default:
- break;
- }
+ Q_UNUSED(change)
}
} // Qt3DRender
diff --git a/src/render/frontend/qcameralens_p.h b/src/render/frontend/qcameralens_p.h
index 5c5a6a42a..eca01b890 100644
--- a/src/render/frontend/qcameralens_p.h
+++ b/src/render/frontend/qcameralens_p.h
@@ -53,7 +53,6 @@
#include <Qt3DRender/private/qt3drender_global_p.h>
#include <Qt3DCore/private/qcomponent_p.h>
-#include <Qt3DCore/private/qnodecommand_p.h>
#include "qcameralens.h"
@@ -63,21 +62,21 @@ QT_BEGIN_NAMESPACE
namespace Qt3DRender {
-struct CameraLensCommand
+struct CameraLensRequest
{
- QString name;
- QVariant data;
- Qt3DCore::QNodeCommand::CommandId commandId;
+ Qt3DCore::QNodeId requestId;
+ Qt3DCore::QNodeId cameraId;
+ Qt3DCore::QNodeId entityId;
- inline operator bool() const { return !name.isEmpty(); }
+ inline operator bool() const { return !requestId.isNull(); }
};
-inline bool operator ==(const CameraLensCommand &a, const CameraLensCommand &b) noexcept
+inline bool operator ==(const CameraLensRequest &a, const CameraLensRequest &b) noexcept
{
- return a.name == b.name && a.data == b.data && a.commandId == b.commandId;
+ return a.cameraId == b.cameraId && a.entityId == b.entityId && a.requestId == b.requestId;
}
-inline bool operator !=(const CameraLensCommand &a, const CameraLensCommand &b) noexcept
+inline bool operator !=(const CameraLensRequest &a, const CameraLensRequest &b) noexcept
{
return !(a == b);
}
@@ -123,8 +122,8 @@ public:
float m_exposure;
- CameraLensCommand m_pendingViewAllCommand;
- void processViewAllCommand(Qt3DCore::QNodeCommand::CommandId commandId, const QVariant &data);
+ CameraLensRequest m_pendingViewAllRequest;
+ void processViewAllResult(Qt3DCore::QNodeId requestId, const QVector3D &center, float radius);
private:
inline void updatePerpectiveProjection()
diff --git a/src/render/frontend/qcomputecommand.cpp b/src/render/frontend/qcomputecommand.cpp
index d0c9f5805..dfd9c2033 100644
--- a/src/render/frontend/qcomputecommand.cpp
+++ b/src/render/frontend/qcomputecommand.cpp
@@ -92,15 +92,15 @@ namespace Qt3DRender {
*/
/*!
- \qmlproperty QComputeCommand::runType
+ \qmlproperty enumeration ComputeCommand::runType
Specifies whether the compute command should be performed every frame or
manually triggered.
- \value Continuous Compute command is executed everyframe. This is the
+ \value ComputeCommand.Continuous Compute command is executed everyframe. This is the
default.
- \value Manual CompouteCommand is executed for a given number of frames and
+ \value ComputeCommand.Manual CompouteCommand is executed for a given number of frames and
then the component disables itself.
*/
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 7b888fe98..c07d4c4b1 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 <Qt3DCore/QEntity>
-#include <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
@@ -134,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/frontend/qrenderaspect.cpp b/src/render/frontend/qrenderaspect.cpp
index 271eb9c11..fc366b891 100644
--- a/src/render/frontend/qrenderaspect.cpp
+++ b/src/render/frontend/qrenderaspect.cpp
@@ -41,7 +41,7 @@
#include "qrenderaspect_p.h"
#include <Qt3DRender/private/nodemanagers_p.h>
-#include <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/scenemanager_p.h>
#include <Qt3DRender/private/geometryrenderermanager_p.h>
@@ -56,8 +56,10 @@
#include <Qt3DRender/qmesh.h>
#include <Qt3DRender/qparameter.h>
#include <Qt3DRender/qrenderpassfilter.h>
+#include <Qt3DRender/qrenderpass.h>
#include <Qt3DRender/qrendertargetselector.h>
#include <Qt3DRender/qtechniquefilter.h>
+#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qviewport.h>
#include <Qt3DRender/qrendertarget.h>
#include <Qt3DRender/qclearbuffers.h>
@@ -92,6 +94,7 @@
#include <Qt3DRender/qwaitfence.h>
#include <Qt3DRender/qshaderimage.h>
#include <Qt3DRender/qsubtreeenabler.h>
+#include <Qt3DRender/qdebugoverlay.h>
#include <Qt3DCore/qarmature.h>
#include <Qt3DCore/qjoint.h>
#include <Qt3DCore/qskeletonloader.h>
@@ -102,7 +105,7 @@
#include <Qt3DRender/private/cameralens_p.h>
#include <Qt3DRender/private/filterkey_p.h>
#include <Qt3DRender/private/entity_p.h>
-#include <Qt3DRender/private/renderer_p.h>
+#include <Qt3DRender/private/abstractrenderer_p.h>
#include <Qt3DRender/private/shaderdata_p.h>
#include <Qt3DRender/private/renderpassfilternode_p.h>
#include <Qt3DRender/private/rendertargetselectornode_p.h>
@@ -159,21 +162,25 @@
#include <Qt3DRender/private/setfence_p.h>
#include <Qt3DRender/private/waitfence_p.h>
#include <Qt3DRender/private/shaderimage_p.h>
+#include <Qt3DRender/private/debugoverlay_p.h>
#include <private/qrenderpluginfactory_p.h>
#include <private/qrenderplugin_p.h>
+#include <Qt3DRender/private/qrendererpluginfactory_p.h>
+
#include <Qt3DCore/qentity.h>
#include <Qt3DCore/qtransform.h>
#include <Qt3DCore/qnode.h>
#include <Qt3DCore/QAspectEngine>
#include <Qt3DCore/private/qservicelocator_p.h>
+#include <Qt3DCore/private/qscene_p.h>
+#include <Qt3DCore/private/qentity_p.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
-#include <QDebug>
-#include <QOffscreenSurface>
#include <QThread>
-#include <QWindow>
+#include <QOpenGLContext>
QT_BEGIN_NAMESPACE
@@ -202,11 +209,16 @@ QRenderAspectPrivate::QRenderAspectPrivate(QRenderAspect::RenderType type)
, m_nodeManagers(nullptr)
, m_renderer(nullptr)
, m_initialized(false)
+ , m_renderAfterJobs(false)
, m_renderType(type)
, m_offscreenHelper(nullptr)
{
m_instances.append(this);
loadSceneParsers();
+ if (m_renderType == QRenderAspect::Threaded && !QOpenGLContext::supportsThreadedOpenGL()) {
+ m_renderType = QRenderAspect::Synchronous;
+ m_renderAfterJobs = true;
+ }
}
/*! \internal */
@@ -239,6 +251,18 @@ void QRenderAspectPrivate::syncDirtyFrontEndNode(QNode *node, QBackendNode *back
renderBackend->syncFromFrontEnd(node, firstTime);
}
+void QRenderAspectPrivate::jobsDone()
+{
+ m_renderer->jobsDone(m_aspectManager);
+}
+
+void QRenderAspectPrivate::frameDone()
+{
+ m_renderer->setJobsInLastFrame(m_aspectManager->jobsInLastFrame());
+ if (m_renderAfterJobs)
+ m_renderer->doRender(true);
+}
+
/*! \internal */
void QRenderAspectPrivate::registerBackendTypes()
{
@@ -289,7 +313,7 @@ void QRenderAspectPrivate::registerBackendTypes()
q->registerBackendType<QParameter, true>(QSharedPointer<Render::NodeFunctor<Render::Parameter, Render::ParameterManager> >::create(m_renderer));
q->registerBackendType<QRenderPass, true>(QSharedPointer<Render::NodeFunctor<Render::RenderPass, Render::RenderPassManager> >::create(m_renderer));
q->registerBackendType<QShaderData, true>(QSharedPointer<Render::RenderShaderDataFunctor>::create(m_renderer, m_nodeManagers));
- q->registerBackendType<QShaderProgram, true>(QSharedPointer<Render::NodeFunctor<Render::Shader, Render::ShaderManager> >::create(m_renderer));
+ q->registerBackendType<QShaderProgram, true>(QSharedPointer<Render::ShaderFunctor>::create(m_renderer, m_nodeManagers->shaderManager()));
q->registerBackendType<QShaderProgramBuilder, true>(QSharedPointer<Render::NodeFunctor<Render::ShaderBuilder, Render::ShaderBuilderManager> >::create(m_renderer));
q->registerBackendType<QTechnique, true>(QSharedPointer<Render::TechniqueFunctor>::create(m_renderer, m_nodeManagers));
q->registerBackendType<QShaderImage, true>(QSharedPointer<Render::NodeFunctor<Render::ShaderImage, Render::ShaderImageManager>>::create(m_renderer));
@@ -318,6 +342,7 @@ void QRenderAspectPrivate::registerBackendTypes()
q->registerBackendType<QWaitFence, true>(QSharedPointer<Render::FrameGraphNodeFunctor<Render::WaitFence, QWaitFence> >::create(m_renderer));
q->registerBackendType<QNoPicking, true>(QSharedPointer<Render::FrameGraphNodeFunctor<Render::NoPicking, QNoPicking> >::create(m_renderer));
q->registerBackendType<QSubtreeEnabler, true>(QSharedPointer<Render::FrameGraphNodeFunctor<Render::SubtreeEnabler, QSubtreeEnabler> >::create(m_renderer));
+ q->registerBackendType<QDebugOverlay, true>(QSharedPointer<Render::FrameGraphNodeFunctor<Render::DebugOverlay, QDebugOverlay> >::create(m_renderer));
// Picking
q->registerBackendType<QObjectPicker, true>(QSharedPointer<Render::NodeFunctor<Render::ObjectPicker, Render::ObjectPickerManager> >::create(m_renderer));
@@ -392,6 +417,7 @@ void QRenderAspectPrivate::unregisterBackendTypes()
unregisterBackendType<QSetFence>();
unregisterBackendType<QWaitFence>();
unregisterBackendType<QSubtreeEnabler>();
+ unregisterBackendType<QDebugOverlay>();
// Picking
unregisterBackendType<QObjectPicker>();
@@ -540,12 +566,29 @@ QVector<Qt3DCore::QAspectJobPtr> QRenderAspect::jobsToExecute(qint64 time)
QVariant QRenderAspect::executeCommand(const QStringList &args)
{
Q_D(QRenderAspect);
+
+ if (args.size() == 1) {
+ Render::RenderSettings *settings = d->m_renderer->settings();
+ auto *droot = static_cast<Qt3DCore::QEntityPrivate *>(Qt3DCore::QNodePrivate::get(d->m_root));
+ auto *fg = qobject_cast<Qt3DRender::QFrameGraphNode *>(droot->m_scene->lookupNode(settings->activeFrameGraphID()));
+ if (fg) {
+ if (args.front() == QLatin1String("framegraph"))
+ return Qt3DRender::QFrameGraphNodePrivate::get(fg)->dumpFrameGraph();
+ if (args.front() == QLatin1String("framepaths"))
+ return Qt3DRender::QFrameGraphNodePrivate::get(fg)->dumpFrameGraphPaths().join(QLatin1String("\n"));
+ }
+ if (args.front() == QLatin1String("scenegraph"))
+ return droot->dumpSceneGraph();
+ }
+
return d->m_renderer->executeCommand(args);
}
void QRenderAspect::onEngineStartup()
{
Q_D(QRenderAspect);
+ if (d->m_renderAfterJobs) // synchronous rendering but using QWindow
+ d->m_renderer->initialize();
Render::NodeManagers *managers = d->m_renderer->nodeManagers();
Render::Entity *rootEntity = managers->lookupResource<Render::Entity, Render::EntityManager>(rootEntityId());
Q_ASSERT(rootEntity);
@@ -560,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);
@@ -606,6 +650,8 @@ void QRenderAspect::onUnregistered()
d->unregisterBackendTypes();
+ d->m_renderer->releaseGraphicsResources();
+
delete d->m_nodeManagers;
d->m_nodeManagers = nullptr;
@@ -648,6 +694,27 @@ 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 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;
+ }
+ const QByteArray targetKeyName = targetKey.toLatin1();
+ qFatal("Unable to find renderer plugin for %s", targetKeyName.constData());
+ 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 62e373b11..0eb04cee9 100644
--- a/src/render/frontend/qrenderaspect_p.h
+++ b/src/render/frontend/qrenderaspect_p.h
@@ -87,6 +87,8 @@ public:
static QRenderAspectPrivate* findPrivate(Qt3DCore::QAspectEngine *engine);
void syncDirtyFrontEndNode(Qt3DCore::QNode *node, Qt3DCore::QBackendNode *backend, bool firstTime) const override;
+ void jobsDone() override;
+ void frameDone() override;
void registerBackendTypes();
void unregisterBackendTypes();
@@ -97,11 +99,13 @@ public:
void renderShutdown();
void registerBackendType(const QMetaObject &, const Qt3DCore::QBackendNodeMapperPtr &functor);
QVector<Qt3DCore::QAspectJobPtr> createGeometryRendererJobs();
+ Render::AbstractRenderer *loadRendererPlugin();
Render::NodeManagers *m_nodeManagers;
Render::AbstractRenderer *m_renderer;
bool m_initialized;
+ bool m_renderAfterJobs;
QList<QSceneImporter *> m_sceneImporter;
QVector<QString> m_loadedPlugins;
QVector<Render::QRenderPlugin *> m_renderPlugins;
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 <QOffscreenSurface>
+#include <QOpenGLContext>
+#include <QOpenGLFunctions>
+#include <QOpenGLExtraFunctions>
+#include <QSet>
+#include <QDebug>
+
+#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<QRenderCapabilities::Profile>(format.profile());
+ m_majorVersion = format.majorVersion();
+ m_minorVersion = format.minorVersion();
+ const QSet<QByteArray> 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<const char *>(funcs->glGetString(GL_VENDOR)));
+ m_renderer = QString::fromUtf8(reinterpret_cast<const char *>(funcs->glGetString(GL_RENDERER)));
+ m_version = QString::fromUtf8(reinterpret_cast<const char *>(funcs->glGetString(GL_VERSION)));
+ m_glslVersion = QString::fromUtf8(reinterpret_cast<const char *>(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..14e233f59
--- /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 <QtCore/qobject.h>
+#include <QtGui/qsurfaceformat.h>
+#include <Qt3DRender/qt3drender_global.h>
+
+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 <QtCore/private/qobject_p.h>
+#include <Qt3DRender/qrendercapabilities.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
+
+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 d106e4205..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"
@@ -104,25 +105,25 @@ void QRenderSettingsPrivate::invalidateFrame()
/*! \internal */
void QRenderSettingsPrivate::_q_onPickingMethodChanged(QPickingSettings::PickMethod pickMethod)
{
- notifyPropertyChange("pickMethod", pickMethod);// TODOSYNC
+ notifyPropertyChange("pickMethod", pickMethod);
}
/*! \internal */
void QRenderSettingsPrivate::_q_onPickResultModeChanged(QPickingSettings::PickResultMode pickResultMode)
{
- notifyPropertyChange("pickResultMode", pickResultMode);// TODOSYNC
+ notifyPropertyChange("pickResultMode", pickResultMode);
}
/*! \internal */
void QRenderSettingsPrivate::_q_onFaceOrientationPickingModeChanged(QPickingSettings::FaceOrientationPickingMode faceOrientationPickingMode)
{
- notifyPropertyChange("faceOrientationPickingMode", faceOrientationPickingMode);// TODOSYNC
+ notifyPropertyChange("faceOrientationPickingMode", faceOrientationPickingMode);
}
/*! \internal */
void QRenderSettingsPrivate::_q_onWorldSpaceToleranceChanged(float worldSpaceTolerance)
{
- notifyPropertyChange("pickWorldSpaceTolerance", worldSpaceTolerance);// TODOSYNC
+ notifyPropertyChange("pickWorldSpaceTolerance", worldSpaceTolerance);
}
QRenderSettings::QRenderSettings(Qt3DCore::QNode *parent)
@@ -142,6 +143,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
Holds the current pick settings for the \l{Qt 3D Render Framegraph}{FrameGraph}.
@@ -161,12 +182,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..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,8 +71,8 @@ public:
};
Q_ENUM(RenderPolicy) // LCOV_EXCL_LINE
+ QRenderCapabilities* renderCapabilities();
QPickingSettings* pickingSettings();
- const QPickingSettings* pickingSettings() const;
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 <Qt3DCore/private/qcomponent_p.h>
#include <Qt3DRender/qrendersettings.h>
#include <Qt3DRender/qpickingsettings.h>
+#include <Qt3DRender/qrendercapabilities.h>
#include <Qt3DRender/private/qt3drender_global_p.h>
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/frontend/sphere.cpp b/src/render/frontend/sphere.cpp
index 470dbfe59..0caeed9f1 100644
--- a/src/render/frontend/sphere.cpp
+++ b/src/render/frontend/sphere.cpp
@@ -93,54 +93,6 @@ bool intersectRaySphere(const Qt3DRender::RayCasting::QRay3D &ray, const Qt3DRen
return true;
}
-inline QPair<int, int> findExtremePoints(const QVector<Vector3D> &points)
-{
- // Find indices of extreme points along x, y, and z axes
- int xMin = 0, xMax = 0, yMin = 0, yMax = 0, zMin = 0, zMax = 0;
- for (int i = 1; i < points.size(); ++i) {
- const Vector3D &p = points.at(i);
- if (p.x() < points[xMin].x())
- xMin = i;
- if (p.x() > points[xMax].x())
- xMax = i;
- if (p.y() < points[yMin].y())
- yMin = i;
- if (p.y() > points[yMax].y())
- yMax = i;
- if (p.z() < points[zMin].z())
- zMin = i;
- if (p.z() > points[zMax].z())
- zMax = i;
- }
-
- // Calculate squared distance for the pairs of points
- const float xDist2 = (points.at(xMax) - points.at(xMin)).lengthSquared();
- const float yDist2 = (points.at(yMax) - points.at(yMin)).lengthSquared();
- const float zDist2 = (points.at(zMax) - points.at(zMin)).lengthSquared();
-
- // Select most distant pair
- QPair<int, int> extremeIndices(xMin, xMax);
- if (yDist2 > xDist2 && yDist2 > zDist2)
- extremeIndices = qMakePair(yMin, yMax);
- if (zDist2 > xDist2 && zDist2 > yDist2)
- extremeIndices = qMakePair(zMin, zMax);
-
- return extremeIndices;
-}
-
-inline void sphereFromExtremePoints(Qt3DRender::Render::Sphere &s, const QVector<Vector3D> &points)
-{
- // Find two most separated points on any of the basis vectors
- QPair<int, int> extremeIndices = findExtremePoints(points);
-
- // Construct sphere to contain these two points
- const Vector3D &p = points.at(extremeIndices.first);
- const Vector3D &q = points.at(extremeIndices.second);
- const Vector3D c = 0.5f * (p + q);
- s.setCenter(c);
- s.setRadius((q - c).length());
-}
-
inline void constructRitterSphere(Qt3DRender::Render::Sphere &s, const QVector<Vector3D> &points)
{
//def bounding_sphere(points):
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 <Qt3DCore/private/matrix4x4_p.h>
#include <Qt3DRender/private/boundingsphere_p.h>
-#include <QMatrix4x4>
-
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.cpp b/src/render/geometry/buffer.cpp
index 0ce81efc1..6db3bab44 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
@@ -105,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()
@@ -152,20 +137,31 @@ void Buffer::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
m_manager->addDirtyBuffer(peerId());
}
{
- QVariant v = node->property("QT3D_updateData");
- if (v.isValid()) {
+ const QVariant v = node->property("QT3D_updateData");
+
+ // Make sure we record data if it's the first time we are called
+ // or if we have no partial updates
+ if (firstTime || !v.isValid()){
+ const QByteArray newData = node->data();
+ const bool dirty = m_data != newData;
+ m_bufferDirty |= dirty;
+ m_data = newData;
+
+ // Since frontend applies partial updates to its m_data
+ // if we enter this code block, there's no problem in actually
+ // ignoring the partial updates
+ if (v.isValid())
+ const_cast<QBuffer *>(node)->setProperty("QT3D_updateData", {});
+
+ if (dirty && !m_data.isEmpty())
+ forceDataUpload();
+ } else if (v.isValid()) {
+ // Apply partial updates and record them to allow partial upload to the GPU
Qt3DRender::QBufferUpdate updateData = v.value<Qt3DRender::QBufferUpdate>();
m_data.replace(updateData.offset, updateData.data.size(), updateData.data);
m_bufferUpdates.push_back(updateData);
m_bufferDirty = true;
const_cast<QBuffer *>(node)->setProperty("QT3D_updateData", {});
- } else {
- QByteArray newData = node->data();
- bool dirty = m_data != newData;
- m_bufferDirty |= dirty;
- m_data = newData;
- if (dirty && !m_data.isEmpty())
- forceDataUpload();
}
}
markDirty(AbstractRenderer::BuffersDirty);
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.cpp b/src/render/geometry/geometryrenderer.cpp
index 3b460f48c..881c0f66b 100644
--- a/src/render/geometry/geometryrenderer.cpp
+++ b/src/render/geometry/geometryrenderer.cpp
@@ -139,8 +139,16 @@ void GeometryRenderer::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
if (functorDirty) {
m_dirty = true;
m_geometryFactory = newFunctor;
- if (m_geometryFactory && m_manager != nullptr)
+ if (m_geometryFactory && m_manager != nullptr) {
m_manager->addDirtyGeometryRenderer(peerId());
+
+ const bool isQMeshFunctor = m_geometryFactory->id() == Qt3DRender::functorTypeId<MeshLoaderFunctor>();
+ if (isQMeshFunctor) {
+ const QMesh *meshNode = static_cast<const QMesh *>(node);
+ QMeshPrivate *dmeshNode = QMeshPrivate::get(const_cast<QMesh *>(meshNode));
+ dmeshNode->setStatus(QMesh::Loading);
+ }
+ }
}
markDirty(AbstractRenderer::GeometryDirty);
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/gltfskeletonloader.cpp b/src/render/geometry/gltfskeletonloader.cpp
index c152605dc..d5d344ce1 100644
--- a/src/render/geometry/gltfskeletonloader.cpp
+++ b/src/render/geometry/gltfskeletonloader.cpp
@@ -48,6 +48,7 @@
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DCore/private/qmath3d_p.h>
+#include <Qt3DCore/private/qloadgltf_p.h>
QT_BEGIN_NAMESPACE
@@ -316,10 +317,7 @@ GLTFSkeletonLoader::GLTFSkeletonLoader()
bool GLTFSkeletonLoader::load(QIODevice *ioDev)
{
- QByteArray jsonData = ioDev->readAll();
- QJsonDocument sceneDocument = QJsonDocument::fromJson(jsonData);
-
- if (Q_UNLIKELY(!setJSON(sceneDocument))) {
+ if (Q_UNLIKELY(!setJSON(qLoadGLTF(ioDev->readAll())))) {
qCWarning(Jobs, "not a JSON document");
return false;
}
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/qbuffer.cpp b/src/render/geometry/qbuffer.cpp
index d27da25c7..8399bdd7c 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
@@ -301,36 +310,14 @@ QBuffer::~QBuffer()
}
/*!
- * \internal
- */
-void QBuffer::sceneChangeEvent(const Qt3DCore::QSceneChangePtr &change)
-{
- if (change->type() == PropertyUpdated) {
- QPropertyUpdatedChangePtr e = qSharedPointerCast<QPropertyUpdatedChange>(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")) {
- const bool blocked = blockNotifications(true);
- setData(e->value().toByteArray());
- blockNotifications(blocked);
- Q_EMIT dataAvailable();
- }
- }
-}
-
-/*!
* Sets \a bytes as data.
*/
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);
}
}
@@ -446,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 1bd1aa8fd..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);
@@ -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);
@@ -129,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;
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/geometry/qgeometryrenderer.cpp b/src/render/geometry/qgeometryrenderer.cpp
index 6e0a24f61..8720a5c00 100644
--- a/src/render/geometry/qgeometryrenderer.cpp
+++ b/src/render/geometry/qgeometryrenderer.cpp
@@ -149,7 +149,7 @@ QGeometryRendererPrivate::~QGeometryRendererPrivate()
*/
/*!
- \qmlproperty int GeometryRenderer::restartIndex
+ \qmlproperty int GeometryRenderer::restartIndexValue
Holds the restart index.
*/
@@ -161,7 +161,7 @@ QGeometryRendererPrivate::~QGeometryRendererPrivate()
*/
/*!
- \qmlproperty bool GeometryRenderer::primitiveRestart
+ \qmlproperty bool GeometryRenderer::primitiveRestartEnabled
Holds the primitive restart flag.
*/
@@ -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..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);
@@ -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..1f05a71f6 100644
--- a/src/render/geometry/qmesh.cpp
+++ b/src/render/geometry/qmesh.cpp
@@ -148,17 +148,6 @@ void QMeshPrivate::setStatus(QMesh::Status status)
*/
/*!
- \enum QMesh::Status
-
- This enum identifies the status of shader used.
-
- \value None A source mesh hasn't been assigned a source yet
- \value Loading The mesh geometry is loading
- \value Ready The mesh geometry was successfully loaded
- \value Error An error occurred while loading the mesh
-*/
-
-/*!
\qmlproperty enumeration Mesh::status
Holds the status of the mesh loading.
@@ -197,6 +186,17 @@ void QMeshPrivate::setStatus(QMesh::Status status)
*/
/*!
+ \enum Qt3DRender::QMesh::Status
+
+ This enum identifies the status of shader used.
+
+ \value None A source mesh hasn't been assigned a source yet
+ \value Loading The mesh geometry is loading
+ \value Ready The mesh geometry was successfully loaded
+ \value Error An error occurred while loading the mesh
+*/
+
+/*!
* Constructs a new QMesh with \a parent.
*/
QMesh::QMesh(QNode *parent)
@@ -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/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/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/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/qsceneloader.cpp b/src/render/io/qsceneloader.cpp
index cf1e45355..2d53702f6 100644
--- a/src/render/io/qsceneloader.cpp
+++ b/src/render/io/qsceneloader.cpp
@@ -41,7 +41,6 @@
#include "qsceneloader_p.h"
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qentity.h>
#include <Qt3DCore/qtransform.h>
#include <Qt3DRender/qgeometryrenderer.h>
@@ -253,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)
@@ -313,7 +317,7 @@ QStringList QSceneLoader::entityNames() const
/*!
\qmlmethod Entity SceneLoader::component(string entityName, enumeration componentType)
- Returns a component matching \a componentType of a loaded entity with an \a objectName matching
+ Returns a component matching \a componentType of a loaded entity with an \e objectName matching
the \a entityName.
If the entity has multiple matching components, the first match in the component list of
the entity is returned.
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/io/scene.cpp b/src/render/io/scene.cpp
index 089091701..1a2000bbb 100644
--- a/src/render/io/scene.cpp
+++ b/src/render/io/scene.cpp
@@ -39,7 +39,6 @@
#include "scene_p.h"
#include <Qt3DCore/qentity.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qdownloadhelperservice_p.h>
@@ -80,6 +79,9 @@ void Scene::syncFromFrontEnd(const Qt3DCore::QNode *frontEnd, bool firstTime)
m_sceneManager->addSceneData(m_source, peerId());
else
m_sceneManager->startSceneDownload(m_source, peerId());
+
+ const auto d = static_cast<const QSceneLoaderPrivate *>(Qt3DCore::QNodePrivate::get(node));
+ const_cast<QSceneLoaderPrivate *>(d)->setStatus(QSceneLoader::Loading);
}
markDirty(AbstractRenderer::AllDirty);
}
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<SceneDownloader> 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 35e658535..ea2916006 100644
--- a/src/render/jobs/abstractpickingjob.cpp
+++ b/src/render/jobs/abstractpickingjob.cpp
@@ -39,7 +39,6 @@
#include "abstractpickingjob_p.h"
#include <Qt3DRender/qgeometryrenderer.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/objectpicker_p.h>
@@ -63,6 +62,7 @@ AbstractPickingJob::AbstractPickingJob()
, m_node(nullptr)
, m_frameGraphRoot(nullptr)
, m_renderSettings(nullptr)
+ , m_oneEnabledAtLeast(false)
{
}
@@ -72,6 +72,7 @@ AbstractPickingJob::AbstractPickingJob(Qt3DCore::QAspectJobPrivate &dd)
, m_node(nullptr)
, m_frameGraphRoot(nullptr)
, m_renderSettings(nullptr)
+ , m_oneEnabledAtLeast(false)
{
}
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 <Qt3DRender/private/qboundingvolumeprovider_p.h>
#include <Qt3DRender/private/qcollisionqueryresult_p.h>
#include <Qt3DRender/private/pickboundingvolumeutils_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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/calcboundingvolumejob.cpp b/src/render/jobs/calcboundingvolumejob.cpp
index 9af2f4f38..172c4ddca 100644
--- a/src/render/jobs/calcboundingvolumejob.cpp
+++ b/src/render/jobs/calcboundingvolumejob.cpp
@@ -354,7 +354,7 @@ CalculateBoundingVolumeJob::CalculateBoundingVolumeJob()
: m_manager(nullptr)
, m_node(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::CalcBoundingVolume, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::CalcBoundingVolume, 0)
}
void CalculateBoundingVolumeJob::run()
diff --git a/src/render/jobs/calcgeometrytrianglevolumes.cpp b/src/render/jobs/calcgeometrytrianglevolumes.cpp
index d2b12e09c..eb31a25a6 100644
--- a/src/render/jobs/calcgeometrytrianglevolumes.cpp
+++ b/src/render/jobs/calcgeometrytrianglevolumes.cpp
@@ -53,7 +53,7 @@ CalcGeometryTriangleVolumes::CalcGeometryTriangleVolumes(const Qt3DCore::QNodeId
, m_geometryRendererId(geometryRendererId)
, m_manager(manager)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::CalcTriangleVolume, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::CalcTriangleVolume, 0)
}
void CalcGeometryTriangleVolumes::run()
diff --git a/src/render/jobs/computefilteredboundingvolumejob.cpp b/src/render/jobs/computefilteredboundingvolumejob.cpp
index 02852685c..0be3cb489 100644
--- a/src/render/jobs/computefilteredboundingvolumejob.cpp
+++ b/src/render/jobs/computefilteredboundingvolumejob.cpp
@@ -39,7 +39,6 @@
#include "computefilteredboundingvolumejob_p.h"
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/sphere_p.h>
@@ -74,12 +73,25 @@ void expandWorldBoundingVolume(NodeManagers *manager,
} // namespace
+class ComputeFilteredBoundingVolumeJobPrivate : public Qt3DCore::QAspectJobPrivate
+{
+public:
+ ComputeFilteredBoundingVolumeJobPrivate(ComputeFilteredBoundingVolumeJob *job) : Qt3DCore::QAspectJobPrivate(), m_job(job) {}
+ ~ComputeFilteredBoundingVolumeJobPrivate() {}
+
+ void postFrame(Qt3DCore::QAspectManager *aspectManager) override;
+
+ ComputeFilteredBoundingVolumeJob *m_job;
+ Qt3DRender::Render::Sphere m_sphere;
+};
+
ComputeFilteredBoundingVolumeJob::ComputeFilteredBoundingVolumeJob()
- : m_root(nullptr)
+ : Qt3DCore::QAspectJob(*new ComputeFilteredBoundingVolumeJobPrivate(this))
+ , m_root(nullptr)
, m_ignoreSubTree(nullptr)
, m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::ExpandBoundingVolume, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::ExpandBoundingVolume, 0)
}
void ComputeFilteredBoundingVolumeJob::setRoot(Entity *root)
@@ -100,11 +112,13 @@ void ComputeFilteredBoundingVolumeJob::ignoreSubTree(Entity *node)
void ComputeFilteredBoundingVolumeJob::run()
{
qCDebug(Jobs) << "Entering" << Q_FUNC_INFO << QThread::currentThread();
+ Q_D(ComputeFilteredBoundingVolumeJob);
+ d->m_sphere = {};
if (!m_root)
return;
if (!m_ignoreSubTree) {
- finished(*m_root->worldBoundingVolumeWithChildren());
+ d->m_sphere = *m_root->worldBoundingVolumeWithChildren();
return;
}
@@ -118,20 +132,24 @@ void ComputeFilteredBoundingVolumeJob::run()
parent = parent->parent();
}
if (!isFilterChildOfRoot) {
- finished(*m_root->worldBoundingVolumeWithChildren());
+ d->m_sphere = *m_root->worldBoundingVolumeWithChildren();
return;
}
- Qt3DRender::Render::Sphere sphere;
- expandWorldBoundingVolume(m_manager, &sphere, m_root, m_ignoreSubTree);
- finished(sphere);
+ expandWorldBoundingVolume(m_manager, &d->m_sphere, m_root, m_ignoreSubTree);
qCDebug(Jobs) << "Exiting" << Q_FUNC_INFO << QThread::currentThread();
}
-void ComputeFilteredBoundingVolumeJob::finished(const Qt3DRender::Render::Sphere &sphere)
+void ComputeFilteredBoundingVolumeJob::finished(Qt3DCore::QAspectManager *aspectManager, const Qt3DRender::Render::Sphere &sphere)
+{
+ Q_UNUSED(aspectManager)
+ Q_UNUSED(sphere)
+}
+
+void ComputeFilteredBoundingVolumeJobPrivate::postFrame(Qt3DCore::QAspectManager *aspectManager)
{
- Q_UNUSED(sphere);
+ m_job->finished(aspectManager, m_sphere);
}
} // namespace Render
diff --git a/src/render/jobs/computefilteredboundingvolumejob_p.h b/src/render/jobs/computefilteredboundingvolumejob_p.h
index d2aca575c..0f804e647 100644
--- a/src/render/jobs/computefilteredboundingvolumejob_p.h
+++ b/src/render/jobs/computefilteredboundingvolumejob_p.h
@@ -64,6 +64,7 @@ namespace Render {
class Entity;
class NodeManagers;
class Sphere;
+class ComputeFilteredBoundingVolumeJobPrivate;
class Q_3DRENDERSHARED_PRIVATE_EXPORT ComputeFilteredBoundingVolumeJob : public Qt3DCore::QAspectJob
{
@@ -76,9 +77,10 @@ public:
void run() override;
protected:
- virtual void finished(const Qt3DRender::Render::Sphere &sphere);
+ virtual void finished(Qt3DCore::QAspectManager *aspectManager, const Qt3DRender::Render::Sphere &sphere); // called in main thread
private:
+ Q_DECLARE_PRIVATE(ComputeFilteredBoundingVolumeJob)
Entity *m_root;
Entity *m_ignoreSubTree;
NodeManagers *m_manager;
diff --git a/src/render/jobs/expandboundingvolumejob.cpp b/src/render/jobs/expandboundingvolumejob.cpp
index d63934b54..ec783e5e0 100644
--- a/src/render/jobs/expandboundingvolumejob.cpp
+++ b/src/render/jobs/expandboundingvolumejob.cpp
@@ -39,7 +39,6 @@
#include "expandboundingvolumejob_p.h"
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
#include <Qt3DRender/private/sphere_p.h>
@@ -62,7 +61,7 @@ void expandWorldBoundingVolume(NodeManagers *manager, Entity *node)
const auto childrenHandles = node->childrenHandles();
for (const HEntity &handle : childrenHandles) {
Entity *c = manager->renderNodesManager()->data(handle);
- if (c)
+ if (c && c->isEnabled())
expandWorldBoundingVolume(manager, c);
}
@@ -72,7 +71,7 @@ void expandWorldBoundingVolume(NodeManagers *manager, Entity *node)
Qt3DRender::Render::Sphere *parentBoundingVolume = node->worldBoundingVolumeWithChildren();
for (const HEntity &handle : childrenHandles) {
Entity *c = manager->renderNodesManager()->data(handle);
- if (c)
+ if (c && c->isEnabled())
parentBoundingVolume->expandToContain(*c->worldBoundingVolumeWithChildren());
}
}
@@ -84,7 +83,7 @@ ExpandBoundingVolumeJob::ExpandBoundingVolumeJob()
: m_node(nullptr)
, m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::ExpandBoundingVolume, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::ExpandBoundingVolume, 0)
}
void ExpandBoundingVolumeJob::setRoot(Entity *root)
diff --git a/src/render/jobs/filterentitybycomponentjob_p.h b/src/render/jobs/filterentitybycomponentjob_p.h
index dd64e50a7..cefcdd296 100644
--- a/src/render/jobs/filterentitybycomponentjob_p.h
+++ b/src/render/jobs/filterentitybycomponentjob_p.h
@@ -74,7 +74,7 @@ public:
: Qt3DCore::QAspectJob()
, m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::EntityComponentTypeFiltering, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::EntityComponentTypeFiltering, 0)
}
inline void setManager(EntityManager *manager) Q_DECL_NOTHROW { m_manager = manager; }
@@ -97,10 +97,6 @@ private:
QVector<Entity *> m_filteredEntities;
};
-template<typename T, typename ... Ts>
-using FilterEntityByComponentJobPtr = QSharedPointer<FilterEntityByComponentJob<T, Ts...>>;
-
-
} // Render
} // Qt3DRender
diff --git a/src/render/jobs/filterlayerentityjob.cpp b/src/render/jobs/filterlayerentityjob.cpp
index e206ef968..032004422 100644
--- a/src/render/jobs/filterlayerentityjob.cpp
+++ b/src/render/jobs/filterlayerentityjob.cpp
@@ -58,7 +58,7 @@ FilterLayerEntityJob::FilterLayerEntityJob()
: Qt3DCore::QAspectJob()
, m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::LayerFiltering, layerFilterJobCounter++);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::LayerFiltering, layerFilterJobCounter++)
}
diff --git a/src/render/jobs/filterproximitydistancejob.cpp b/src/render/jobs/filterproximitydistancejob.cpp
index a25e88508..02b712fc2 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()
@@ -55,9 +57,9 @@ void FilterProximityDistanceJob::run()
// Fill m_filteredEntities
// If no filtering needs to be done, this will be the output value
// otherwise it will be used as the base list of entities to filter
- selectAllEntities();
if (hasProximityFilter()) {
+ selectAllEntities();
QVector<Entity *> entitiesToFilter = std::move(m_filteredEntities);
FrameGraphManager *frameGraphManager = m_manager->frameGraphManager();
EntityManager *entityManager = m_manager->renderNodesManager();
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 <Qt3DCore/qaspectjob.h>
#include <Qt3DCore/qnodeid.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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 17ca60bff..eddea12e8 100644
--- a/src/render/jobs/framecleanupjob.cpp
+++ b/src/render/jobs/framecleanupjob.cpp
@@ -38,7 +38,6 @@
****************************************************************************/
#include "framecleanupjob_p.h"
-#include <private/renderer_p.h>
#include <private/nodemanagers_p.h>
#include <private/entity_p.h>
#include <private/shaderdata_p.h>
@@ -55,7 +54,7 @@ FrameCleanupJob::FrameCleanupJob()
: m_managers(nullptr)
, m_root(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::FrameCleanup, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::FrameCleanup, 0)
}
FrameCleanupJob::~FrameCleanupJob()
@@ -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 0922fb0cb..aa1a57a31 100644
--- a/src/render/jobs/frustumcullingjob.cpp
+++ b/src/render/jobs/frustumcullingjob.cpp
@@ -41,7 +41,6 @@
#include <Qt3DRender/private/job_common_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/entity_p.h>
-#include <Qt3DRender/private/renderview_p.h>
#include <Qt3DRender/private/sphere_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
@@ -58,7 +57,7 @@ FrustumCullingJob::FrustumCullingJob()
, m_manager(nullptr)
, m_active(false)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::FrustumCulling, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::FrustumCulling, 0)
}
void FrustumCullingJob::run()
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 <Qt3DCore/qaspectjob.h>
#include <Qt3DCore/private/matrix4x4_p.h>
+#include <Qt3DCore/private/vector3d_p.h>
+#include <Qt3DCore/private/vector4d_p.h>
#include <Qt3DRender/private/aligned_malloc_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
//
// 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/genericlambdajob_p.h b/src/render/jobs/genericlambdajob_p.h
index 4d93f0f8d..8cf4276f6 100644
--- a/src/render/jobs/genericlambdajob_p.h
+++ b/src/render/jobs/genericlambdajob_p.h
@@ -68,7 +68,7 @@ public:
: Qt3DCore::QAspectJob()
, m_callable(callable)
{
- SET_JOB_RUN_STAT_TYPE(this, type, 0);
+ SET_JOB_RUN_STAT_TYPE(this, type, 0)
}
// QAspectJob interface
@@ -111,7 +111,7 @@ public:
: Qt3DCore::QAspectJob(*new GenericLambdaJobAndPostFramePrivate<T, U>(postFrameCallable))
, m_runCallable(runCallable)
{
- SET_JOB_RUN_STAT_TYPE(this, type, 0);
+ SET_JOB_RUN_STAT_TYPE(this, type, 0)
}
// QAspectJob interface
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/jobs/jobs.pri b/src/render/jobs/jobs.pri
index 2181e4a95..eb89ab35e 100644
--- a/src/render/jobs/jobs.pri
+++ b/src/render/jobs/jobs.pri
@@ -18,7 +18,6 @@ HEADERS += \
$$PWD/lightgatherer_p.h \
$$PWD/expandboundingvolumejob_p.h \
$$PWD/updateworldboundingvolumejob_p.h \
- $$PWD/sendrendercapturejob_p.h \
$$PWD/updateshaderdatatransformjob_p.h \
$$PWD/updatelevelofdetailjob_p.h \
$$PWD/updatemeshtrianglelistjob_p.h \
@@ -47,7 +46,6 @@ SOURCES += \
$$PWD/lightgatherer.cpp \
$$PWD/expandboundingvolumejob.cpp \
$$PWD/updateworldboundingvolumejob.cpp \
- $$PWD/sendrendercapturejob.cpp \
$$PWD/updateshaderdatatransformjob.cpp \
$$PWD/updatemeshtrianglelistjob.cpp \
$$PWD/updatelevelofdetailjob.cpp \
diff --git a/src/render/jobs/lightgatherer.cpp b/src/render/jobs/lightgatherer.cpp
index b76cd4d73..b878b0a78 100644
--- a/src/render/jobs/lightgatherer.cpp
+++ b/src/render/jobs/lightgatherer.cpp
@@ -41,6 +41,7 @@
#include <Qt3DRender/private/job_common_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/entity_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
QT_BEGIN_NAMESPACE
@@ -53,11 +54,14 @@ LightGatherer::LightGatherer()
, m_manager(nullptr)
, m_environmentLight(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::LightGathering, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::LightGathering, 0)
}
void LightGatherer::run()
{
+ m_lights.clear();
+ m_environmentLight = nullptr;
+
const QVector<HEntity> handles = m_manager->activeHandles();
int envLightCount = 0;
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 <Qt3DCore/qaspectjob.h>
#include <Qt3DRender/private/lightsource_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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 49f271df5..fd57248e1 100644
--- a/src/render/jobs/loadbufferjob.cpp
+++ b/src/render/jobs/loadbufferjob.cpp
@@ -39,9 +39,11 @@
#include "loadbufferjob_p.h"
#include <Qt3DRender/private/buffer_p.h>
+#include <Qt3DRender/private/qbuffer_p.h>
#include <Qt3DRender/private/buffermanager_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/job_common_p.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DRender/private/renderlogging_p.h>
QT_BEGIN_NAMESPACE
@@ -49,13 +51,24 @@ 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)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadBuffer, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadBuffer, 0)
}
LoadBufferJob::~LoadBufferJob()
@@ -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<Buffer, BufferManager>(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<decltype(frontendBuffer)>(aspectManager->lookupNode(m_bufferToUpdate->peerId()));
+ QBufferPrivate *dFrontend = static_cast<decltype(dFrontend)>(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..5f20bfb00 100644
--- a/src/render/jobs/loadbufferjob_p.h
+++ b/src/render/jobs/loadbufferjob_p.h
@@ -63,8 +63,9 @@ namespace Qt3DRender {
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);
@@ -76,6 +77,9 @@ public:
protected:
HBuffer m_handle;
NodeManagers *m_nodeManagers;
+
+private:
+ Q_DECLARE_PRIVATE(LoadBufferJob)
};
typedef QSharedPointer<LoadBufferJob> LoadBufferJobPtr;
diff --git a/src/render/jobs/loadgeometryjob.cpp b/src/render/jobs/loadgeometryjob.cpp
index 88930038a..2069336cd 100644
--- a/src/render/jobs/loadgeometryjob.cpp
+++ b/src/render/jobs/loadgeometryjob.cpp
@@ -66,7 +66,7 @@ LoadGeometryJob::LoadGeometryJob(const HGeometryRenderer &handle)
, m_handle(handle)
, m_nodeManagers(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadGeometry, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadGeometry, 0)
}
LoadGeometryJob::~LoadGeometryJob()
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 <QSharedPointer>
#include <Qt3DCore/qaspectjob.h>
#include <Qt3DRender/private/handle_types_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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 f858f82e3..959cbe3eb 100644
--- a/src/render/jobs/loadscenejob.cpp
+++ b/src/render/jobs/loadscenejob.cpp
@@ -38,9 +38,9 @@
****************************************************************************/
#include "loadscenejob_p.h"
-#include <private/renderer_p.h>
#include <private/nodemanagers_p.h>
#include <private/scenemanager_p.h>
+#include <QCoreApplication>
#include <Qt3DCore/qentity.h>
#include <Qt3DCore/private/qaspectmanager_p.h>
#include <Qt3DRender/private/job_common_p.h>
@@ -63,7 +63,7 @@ LoadSceneJob::LoadSceneJob(const QUrl &source, Qt3DCore::QNodeId sceneComponent)
, m_sceneComponent(sceneComponent)
, m_managers(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadScene, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::LoadScene, 0)
}
void LoadSceneJob::setData(const QByteArray &data)
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 <QSharedPointer>
#include <QUrl>
#include <functional>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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 8d0d47fb9..de12b7e39 100644
--- a/src/render/jobs/loadskeletonjob.cpp
+++ b/src/render/jobs/loadskeletonjob.cpp
@@ -47,6 +47,9 @@
#include <Qt3DRender/private/job_common_p.h>
#include <Qt3DRender/private/qurlhelper_p.h>
#include <Qt3DRender/private/gltfskeletonloader_p.h>
+#include <Qt3DRender/private/renderlogging_p.h>
+#include <QtCore/QCoreApplication>
+#include <QtCore/QFileInfo>
QT_BEGIN_NAMESPACE
@@ -288,7 +291,7 @@ void LoadSkeletonJobPrivate::postFrame(Qt3DCore::QAspectManager *manager)
dloaderNode->setStatus(m_backendSkeleton->status());
if (m_loadedRootJoint) {
- dloaderNode->m_rootJoint = m_loadedRootJoint;
+ dloaderNode->setRootJoint(m_loadedRootJoint);
m_loadedRootJoint = nullptr;
}
}
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 <Qt3DRender/qviewport.h>
#include <Qt3DRender/qgeometryrenderer.h>
#include <Qt3DRender/private/qobjectpicker_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/objectpicker_p.h>
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 <Qt3DRender/private/qboundingvolumeprovider_p.h>
#include <Qt3DRender/private/qcollisionqueryresult_p.h>
#include <Qt3DRender/private/pickboundingvolumeutils_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <Qt3DRender/qpickevent.h>
#include <QMouseEvent>
#include <QKeyEvent>
@@ -76,7 +77,7 @@ namespace PickingUtils {
typedef QVector<RayCasting::QCollisionQueryResult::Hit> 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 <Qt3DRender/private/pickboundingvolumeutils_p.h>
#include <Qt3DRender/private/qray3d_p.h>
#include <Qt3DRender/private/sphere_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/rendersettings_p.h>
#include <Qt3DRender/private/trianglesvisitor_p.h>
#include <Qt3DRender/private/entityvisitor_p.h>
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 <Qt3DRender/qpickevent.h>
#include <Qt3DRender/private/handle_types_p.h>
#include <Qt3DRender/private/qcollisionqueryresult_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QSharedPointer>
@@ -70,7 +71,7 @@ typedef QVector<RayCasting::QCollisionQueryResult::Hit> 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/sendbuffercapturejob.cpp b/src/render/jobs/sendbuffercapturejob.cpp
index 8683ea9f2..2ccb72337 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 <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/job_common_p.h>
#include <Qt3DRender/private/buffer_p.h>
+#include <Qt3DRender/private/buffermanager_p.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DRender/private/qbuffer_p.h>
QT_BEGIN_NAMESPACE
@@ -51,36 +52,75 @@ namespace Qt3DRender {
namespace Render {
+class SendBufferCaptureJobPrivate : public Qt3DCore::QAspectJobPrivate
+{
+public:
+ SendBufferCaptureJobPrivate() {}
+ ~SendBufferCaptureJobPrivate() {}
+
+ void postFrame(Qt3DCore::QAspectManager *aspectManager) override;
+
+ mutable QMutex m_mutex;
+ QVector<QPair<Qt3DCore::QNodeId, QByteArray>> m_buffersToCapture;
+ QVector<QPair<Qt3DCore::QNodeId, QByteArray>> m_buffersToNotify;
+};
+
SendBufferCaptureJob::SendBufferCaptureJob()
- : Qt3DCore::QAspectJob()
+ : 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()
{
}
-void SendBufferCaptureJob::addRequest(QPair<Buffer *, QByteArray> request)
+// Called from SubmitRenderView while rendering
+void SendBufferCaptureJob::addRequest(QPair<Qt3DCore::QNodeId, QByteArray> 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<Buffer*, QByteArray> &pendingCapture : qAsConst(m_pendingSendBufferCaptures)) {
- pendingCapture.first->updateDataFromGPUToCPU(pendingCapture.second);
+ Q_ASSERT(m_nodeManagers);
+ Q_D(SendBufferCaptureJob);
+ QMutexLocker locker(&d->m_mutex);
+ for (const QPair<Qt3DCore::QNodeId, QByteArray> &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<QPair<Qt3DCore::QNodeId, QByteArray>> pendingSendBufferCaptures = std::move(m_buffersToNotify);
+ for (const auto &bufferDataPair : pendingSendBufferCaptures) {
+ QBuffer *frontendBuffer = static_cast<decltype(frontendBuffer)>(aspectManager->lookupNode(bufferDataPair.first));
+ if (!frontendBuffer)
+ continue;
+ QBufferPrivate *dFrontend = static_cast<decltype(dFrontend)>(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 <Qt3DCore/qaspectjob.h>
+#include <Qt3DCore/qnodeid.h>
#include <Qt3DRender/qt3drender_global.h>
#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QMutex>
@@ -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<Buffer*, QByteArray> request);
+ void setManagers(NodeManagers *nodeManagers) { m_nodeManagers = nodeManagers; }
+ void addRequest(QPair<Qt3DCore::QNodeId, QByteArray> request);
bool hasRequests() const;
void run() final;
private:
- QMutex m_mutex;
-
- QVector<QPair<Buffer*, QByteArray> > m_pendingSendBufferCaptures;
+ Q_DECLARE_PRIVATE(SendBufferCaptureJob)
+ NodeManagers *m_nodeManagers;
};
typedef QSharedPointer<SendBufferCaptureJob> SendBufferCaptureJobPtr;
diff --git a/src/render/jobs/updateentitylayersjob.cpp b/src/render/jobs/updateentitylayersjob.cpp
index 2c5e38364..b8c50c179 100644
--- a/src/render/jobs/updateentitylayersjob.cpp
+++ b/src/render/jobs/updateentitylayersjob.cpp
@@ -52,7 +52,7 @@ namespace Render {
UpdateEntityLayersJob::UpdateEntityLayersJob()
: m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateLayerEntity, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateLayerEntity, 0)
}
diff --git a/src/render/jobs/updatemeshtrianglelistjob.cpp b/src/render/jobs/updatemeshtrianglelistjob.cpp
index 1c61d1c90..4837dcad6 100644
--- a/src/render/jobs/updatemeshtrianglelistjob.cpp
+++ b/src/render/jobs/updatemeshtrianglelistjob.cpp
@@ -60,7 +60,7 @@ namespace Render {
UpdateMeshTriangleListJob::UpdateMeshTriangleListJob()
: m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateMeshTriangleList, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateMeshTriangleList, 0)
}
UpdateMeshTriangleListJob::~UpdateMeshTriangleListJob()
diff --git a/src/render/jobs/updateshaderdatatransformjob.cpp b/src/render/jobs/updateshaderdatatransformjob.cpp
index c29a827e3..11fe91932 100644
--- a/src/render/jobs/updateshaderdatatransformjob.cpp
+++ b/src/render/jobs/updateshaderdatatransformjob.cpp
@@ -61,7 +61,7 @@ namespace Render {
UpdateShaderDataTransformJob::UpdateShaderDataTransformJob()
: m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateShaderDataTransform, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateShaderDataTransform, 0)
}
UpdateShaderDataTransformJob::~UpdateShaderDataTransformJob()
diff --git a/src/render/jobs/updateskinningpalettejob.cpp b/src/render/jobs/updateskinningpalettejob.cpp
index 0f5d3d6d6..b77707f15 100644
--- a/src/render/jobs/updateskinningpalettejob.cpp
+++ b/src/render/jobs/updateskinningpalettejob.cpp
@@ -50,7 +50,7 @@ UpdateSkinningPaletteJob::UpdateSkinningPaletteJob()
, m_nodeManagers(nullptr)
, m_root()
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateSkinningPalette, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateSkinningPalette, 0)
}
UpdateSkinningPaletteJob::~UpdateSkinningPaletteJob()
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 <QtCore/qsharedpointer.h>
#include <Qt3DRender/private/handle_types_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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/updatetreeenabledjob.cpp b/src/render/jobs/updatetreeenabledjob.cpp
index e97fc6414..22d6f6083 100644
--- a/src/render/jobs/updatetreeenabledjob.cpp
+++ b/src/render/jobs/updatetreeenabledjob.cpp
@@ -71,8 +71,9 @@ 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);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateTreeEnabled, 0)
}
void UpdateTreeEnabledJob::setRoot(Entity *root)
diff --git a/src/render/jobs/updateworldboundingvolumejob.cpp b/src/render/jobs/updateworldboundingvolumejob.cpp
index 40dd919bc..65a3ec75d 100644
--- a/src/render/jobs/updateworldboundingvolumejob.cpp
+++ b/src/render/jobs/updateworldboundingvolumejob.cpp
@@ -52,7 +52,7 @@ UpdateWorldBoundingVolumeJob::UpdateWorldBoundingVolumeJob()
: Qt3DCore::QAspectJob()
, m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateWorldBoundingVolume, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateWorldBoundingVolume, 0)
}
void UpdateWorldBoundingVolumeJob::run()
@@ -61,6 +61,8 @@ void UpdateWorldBoundingVolumeJob::run()
for (const HEntity &handle : handles) {
Entity *node = m_manager->data(handle);
+ if (!node->isEnabled())
+ continue;
*(node->worldBoundingVolume()) = node->localBoundingVolume()->transformed(*(node->worldTransform()));
*(node->worldBoundingVolumeWithChildren()) = *(node->worldBoundingVolume()); // expanded in UpdateBoundingVolumeJob
}
diff --git a/src/render/jobs/updateworldtransformjob.cpp b/src/render/jobs/updateworldtransformjob.cpp
index 13e14442f..12582c297 100644
--- a/src/render/jobs/updateworldtransformjob.cpp
+++ b/src/render/jobs/updateworldtransformjob.cpp
@@ -42,7 +42,6 @@
#include <Qt3DCore/qtransform.h>
#include <Qt3DCore/private/qtransform_p.h>
#include <Qt3DCore/private/qaspectmanager_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/transform_p.h>
#include <Qt3DRender/private/renderlogging_p.h>
@@ -65,11 +64,13 @@ struct TransformUpdate
QMatrix4x4 worldTransformMatrix;
};
-QVector<TransformUpdate> updateWorldTransformAndBounds(NodeManagers *manager, Entity *node, const Matrix4x4 &parentTransform)
+void updateWorldTransformAndBounds(NodeManagers *manager, Entity *node, const Matrix4x4 &parentTransform, QVector<TransformUpdate> &updatedTransforms)
{
+ if (!node->isEnabled())
+ return;
+
Matrix4x4 worldTransform(parentTransform);
Transform *nodeTransform = node->renderComponent<Transform>();
- QVector<TransformUpdate> updatedTransforms;
const bool hasTransformComponent = nodeTransform != nullptr && nodeTransform->isEnabled();
if (hasTransformComponent)
@@ -85,9 +86,8 @@ QVector<TransformUpdate> 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;
}
}
@@ -108,7 +108,7 @@ UpdateWorldTransformJob::UpdateWorldTransformJob()
, m_node(nullptr)
, m_manager(nullptr)
{
- SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateTransform, 0);
+ SET_JOB_RUN_STAT_TYPE(this, JobTypes::UpdateTransform, 0)
}
void UpdateWorldTransformJob::setRoot(Entity *root)
@@ -137,7 +137,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();
}
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 <Qt3DRender/qt3drender_global.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
#include <QVector>
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<Light *> &lights);
diff --git a/src/render/lights/qdirectionallight.cpp b/src/render/lights/qdirectionallight.cpp
index 13fb78843..51827b644 100644
--- a/src/render/lights/qdirectionallight.cpp
+++ b/src/render/lights/qdirectionallight.cpp
@@ -115,12 +115,18 @@ QDirectionalLight::QDirectionalLight(QDirectionalLightPrivate &dd, QNode *parent
/*!
\qmlproperty vector3d Qt3D.Render::DirectionalLight::worldDirection
- Specifies the world direction of the directional light
+ Specifies the world direction of the directional light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QDirectionalLight::worldDirection
- Specifies the world direction of the directional light
+ Specifies the world direction of the directional light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
void QDirectionalLight::setWorldDirection(const QVector3D &direction)
{
diff --git a/src/render/lights/qenvironmentlight.cpp b/src/render/lights/qenvironmentlight.cpp
index 86ef04f95..977e117db 100644
--- a/src/render/lights/qenvironmentlight.cpp
+++ b/src/render/lights/qenvironmentlight.cpp
@@ -158,6 +158,9 @@ QEnvironmentLight::~QEnvironmentLight()
Holds the current environment irradiance map texture.
By default, the environment irradiance texture is null.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
@@ -166,6 +169,9 @@ QEnvironmentLight::~QEnvironmentLight()
Holds the current environment irradiance map texture.
By default, the environment irradiance texture is null.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
QAbstractTexture *QEnvironmentLight::irradiance() const
{
@@ -179,6 +185,9 @@ QAbstractTexture *QEnvironmentLight::irradiance() const
Holds the current environment specular map texture.
By default, the environment specular texture is null.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
@@ -187,6 +196,9 @@ QAbstractTexture *QEnvironmentLight::irradiance() const
Holds the current environment specular map texture.
By default, the environment specular texture is null.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
QAbstractTexture *QEnvironmentLight::specular() const
{
diff --git a/src/render/lights/qpointlight.cpp b/src/render/lights/qpointlight.cpp
index 2b042c91d..c16291709 100644
--- a/src/render/lights/qpointlight.cpp
+++ b/src/render/lights/qpointlight.cpp
@@ -135,12 +135,18 @@ QPointLight::QPointLight(QPointLightPrivate &dd, QNode *parent)
/*!
\qmlproperty float Qt3D.Render::PointLight::constantAttenuation
- Specifies the constant attenuation of the point light
+ Specifies the constant attenuation of the point light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QPointLight::constantAttenuation
- Specifies the constant attenuation of the point light
+ Specifies the constant attenuation of the point light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QPointLight::constantAttenuation() const
{
@@ -159,12 +165,18 @@ void QPointLight::setConstantAttenuation(float value)
/*!
\qmlproperty float Qt3D.Render::PointLight::linearAttenuation
- Specifies the linear attenuation of the point light
+ Specifies the linear attenuation of the point light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QPointLight::linearAttenuation
- Specifies the linear attenuation of the point light
+ Specifies the linear attenuation of the point light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QPointLight::linearAttenuation() const
{
@@ -183,12 +195,18 @@ void QPointLight::setLinearAttenuation(float value)
/*!
\qmlproperty float Qt3D.Render::PointLight::quadraticAttenuation
- Specifies the quadratic attenuation of the point light
+ Specifies the quadratic attenuation of the point light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QPointLight::quadraticAttenuation
- Specifies the quadratic attenuation of the point light
+ Specifies the quadratic attenuation of the point light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QPointLight::quadraticAttenuation() const
{
diff --git a/src/render/lights/qspotlight.cpp b/src/render/lights/qspotlight.cpp
index eddafbe61..c725a6baf 100644
--- a/src/render/lights/qspotlight.cpp
+++ b/src/render/lights/qspotlight.cpp
@@ -140,12 +140,18 @@ QSpotLight::QSpotLight(QSpotLightPrivate &dd, QNode *parent)
/*!
\qmlproperty float Qt3D.Render::SpotLight::constantAttenuation
- Specifies the constant attenuation of the spot light
+ Specifies the constant attenuation of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QSpotLight::constantAttenuation
- Specifies the constant attenuation of the spot light
+ Specifies the constant attenuation of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QSpotLight::constantAttenuation() const
{
@@ -164,12 +170,18 @@ void QSpotLight::setConstantAttenuation(float value)
/*!
\qmlproperty float Qt3D.Render::SpotLight::linearAttenuation
- Specifies the linear attenuation of the spot light
+ Specifies the linear attenuation of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QSpotLight::linearAttenuation
- Specifies the linear attenuation of the spot light
+ Specifies the linear attenuation of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QSpotLight::linearAttenuation() const
{
@@ -188,12 +200,18 @@ void QSpotLight::setLinearAttenuation(float value)
/*!
\qmlproperty float Qt3D.Render::SpotLight::quadraticAttenuation
- Specifies the quadratic attenuation of the spot light
+ Specifies the quadratic attenuation of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QSpotLight::quadraticAttenuation
- Specifies the quadratic attenuation of the spot light
+ Specifies the quadratic attenuation of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QSpotLight::quadraticAttenuation() const
{
@@ -212,12 +230,18 @@ void QSpotLight::setQuadraticAttenuation(float value)
/*!
\qmlproperty vector3d Qt3D.Render::SpotLight::localDirection
- Specifies the local direction of the spot light
+ Specifies the local direction of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QSpotLight::localDirection
- Specifies the local direction of the spot light
+ Specifies the local direction of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
QVector3D QSpotLight::localDirection() const
{
@@ -227,12 +251,18 @@ QVector3D QSpotLight::localDirection() const
/*!
\qmlproperty float Qt3D.Render::SpotLight::cutOffAngle
- Specifies the cut off angle of the spot light
+ Specifies the cut off angle of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
/*!
\property Qt3DRender::QSpotLight::cutOffAngle
- Specifies the cut off angle of the spot light
+ Specifies the cut off angle of the spot light.
+
+ \note The exact meaning and use of this property is up to the
+ material implementation.
*/
float QSpotLight::cutOffAngle() const
{
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 <Qt3DRender/private/effect_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/qeffect.h>
#include <Qt3DRender/qparameter.h>
+#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/private/qeffect_p.h>
#include <QVariant>
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 <QVariant>
#include <Qt3DRender/private/backendnode_p.h>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
#include <Qt3DRender/private/parameterpack_p.h>
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/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/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/qshaderimage.cpp b/src/render/materialsystem/qshaderimage.cpp
index f2ce04c3d..508cf44f2 100644
--- a/src/render/materialsystem/qshaderimage.cpp
+++ b/src/render/materialsystem/qshaderimage.cpp
@@ -342,7 +342,7 @@ QShaderImagePrivate::~QShaderImagePrivate()
*/
/*!
- \qmlproperty Qt3DRender::QShaderImage::mipLevel
+ \qmlproperty int Qt3D.Render::ShaderImage::mipLevel
Holds which mipLevel out of the referenced texture should be used for the
ShaderImage.
@@ -351,7 +351,7 @@ QShaderImagePrivate::~QShaderImagePrivate()
*/
/*!
- \qmlproperty Qt3DRender::QShaderImage::layer
+ \qmlproperty int Qt3D.Render::ShaderImage::layer
Holds which layer out of the referenced texture should be used for the
ShaderImage. This property does nothing if \a layered is set to true or if
@@ -365,11 +365,11 @@ QShaderImagePrivate::~QShaderImagePrivate()
cubeMapFace = layer - (cubeMapLayer * 6)
\endcode
- \default 0
+ Default value is 0.
*/
/*!
- * \qmlproperty Qt3DRender::QShaderImage::layered
+ * \qmlproperty bool Qt3D.Render::ShaderImage::layered
If set to true, if the referenced texture is a one-dimensional array,
two-dimensional array, three-dimensional, cube map, cube map array, or
@@ -377,21 +377,28 @@ QShaderImagePrivate::~QShaderImagePrivate()
for all layers. If set to false, only the single layer specified by the \a
layer property will be bound.
- \default false
+ Default value is \c false.
*/
/*!
- \qmlproperty Qt3DRender::QShaderImage::access
+ \qmlproperty enumeration Qt3D.Render::ShaderImage::access
Specifies the type of access we want to allow from our shader instances to
the image. If a shader tries to write or read from an image that has
incompatible access, the behavior is undefined.
- \default ShaderImage.ReadWrite
+ \value ShaderImage.ReadOnly
+ Read-only access.
+ \value ShaderImage.WriteOnly
+ Write-only access.
+ \value ShaderImage.ReadWrite
+ Read-write access.
+
+ Default value is ShaderImage.ReadWrite.
*/
/*!
- \qmlproperty Qt3DRender::QShaderImage::format
+ \qmlproperty enumeration Qt3D.Render::ShaderImage::format
Specifies the image format, which is essentially important when storing values
in the ShaderImage from a shader.
@@ -407,7 +414,7 @@ QShaderImagePrivate::~QShaderImagePrivate()
By default Qt3D will try to set the image format to match that of the
referenced texture.
- \default ShaderImage.Automatic
+ Default value is ShaderImage.Automatic.
*/
/*!
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..8a14255a8 100644
--- a/src/render/materialsystem/qshaderprogram_p.h
+++ b/src/render/materialsystem/qshaderprogram_p.h
@@ -51,14 +51,15 @@
// We mean it.
//
-#include <private/qnode_p.h>
+#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DRender/qshaderprogram.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
-class QShaderProgramPrivate : public Qt3DCore::QNodePrivate
+class Q_3DRENDERSHARED_PRIVATE_EXPORT QShaderProgramPrivate : public Qt3DCore::QNodePrivate
{
public:
QShaderProgramPrivate();
@@ -72,6 +73,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 +90,7 @@ struct QShaderProgramData
QByteArray geometryShaderCode;
QByteArray fragmentShaderCode;
QByteArray computeShaderCode;
+ QShaderProgram::Format format;
};
} // namespace Qt3DRender
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/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 <Qt3DRender/private/qrenderpass_p.h>
#include <Qt3DRender/private/renderstates_p.h>
-#include <Qt3DRender/private/renderstateset_p.h>
#include <algorithm>
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 58709b37e..94e30a2c0 100644
--- a/src/render/materialsystem/shader.cpp
+++ b/src/render/materialsystem/shader.cpp
@@ -46,10 +46,10 @@
#include <QMutexLocker>
#include <qshaderprogram.h>
#include <Qt3DRender/private/attachmentpack_p.h>
-#include <Qt3DRender/private/graphicscontext_p.h>
#include <Qt3DRender/private/qshaderprogram_p.h>
#include <Qt3DRender/private/stringtoint_p.h>
#include <Qt3DCore/qpropertyupdatedchange.h>
+#include <Qt3DRender/private/managers_p.h>
QT_BEGIN_NAMESPACE
@@ -57,49 +57,51 @@ using namespace Qt3DCore;
namespace Qt3DRender {
namespace Render {
+const int Shader::modelMatrixNameId = StringToInt::lookupId(QLatin1String("modelMatrix"));
+const int Shader::viewMatrixNameId = StringToInt::lookupId(QLatin1String("viewMatrix"));
+const int Shader::projectionMatrixNameId = StringToInt::lookupId(QLatin1String("projectionMatrix"));
+const int Shader::modelViewMatrixNameId = StringToInt::lookupId(QLatin1String("modelView"));
+const int Shader::viewProjectionMatrixNameId = StringToInt::lookupId(QLatin1String("viewProjectionMatrix"));
+const int Shader::modelViewProjectionNameId = StringToInt::lookupId(QLatin1String("modelViewProjection"));
+const int Shader::mvpNameId = StringToInt::lookupId(QLatin1String("mvp"));
+const int Shader::inverseModelMatrixNameId = StringToInt::lookupId(QLatin1String("inverseModelMatrix"));
+const int Shader::inverseViewMatrixNameId = StringToInt::lookupId(QLatin1String("inverseViewMatrix"));
+const int Shader::inverseProjectionMatrixNameId = StringToInt::lookupId(QLatin1String("inverseProjectionMatrix"));
+const int Shader::inverseModelViewNameId = StringToInt::lookupId(QLatin1String("inverseModelView"));
+const int Shader::inverseViewProjectionMatrixNameId = StringToInt::lookupId(QLatin1String("inverseViewProjectionMatrix"));
+const int Shader::inverseModelViewProjectionNameId = StringToInt::lookupId(QLatin1String("inverseModelViewProjection"));
+const int Shader::modelNormalMatrixNameId = StringToInt::lookupId(QLatin1String("modelNormalMatrix"));
+const int Shader::modelViewNormalNameId = StringToInt::lookupId(QLatin1String("modelViewNormal"));
+const int Shader::viewportMatrixNameId = StringToInt::lookupId(QLatin1String("viewportMatrix"));
+const int Shader::inverseViewportMatrixNameId = StringToInt::lookupId(QLatin1String("inverseViewportMatrix"));
+const int Shader::aspectRatioNameId = StringToInt::lookupId(QLatin1String("aspectRatio"));
+const int Shader::exposureNameId = StringToInt::lookupId(QLatin1String("exposure"));
+const int Shader::gammaNameId = StringToInt::lookupId(QLatin1String("gamma"));
+const int Shader::timeNameId = StringToInt::lookupId(QLatin1String("time"));
+const int Shader::eyePositionNameId = StringToInt::lookupId(QLatin1String("eyePosition"));
+const int Shader::skinningPaletteNameId = StringToInt::lookupId(QLatin1String("skinningPalette[0]"));
Shader::Shader()
: BackendNode(ReadWrite)
- , m_isLoaded(false)
- , m_dna(0)
- , m_graphicsContext(nullptr)
- , m_status(QShaderProgram::NotReady)
, m_requiresFrontendSync(false)
+ , m_status(QShaderProgram::NotReady)
+ , m_format(QShaderProgram::GLSL)
+ , m_dirty(false)
{
m_shaderCode.resize(static_cast<int>(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_format = QShaderProgram::GLSL;
+ m_log.clear();
+ m_dirty = false;
}
void Shader::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
@@ -120,48 +122,7 @@ void Shader::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
if (code != m_shaderCode.value(shaderType))
setShaderCode(shaderType, code);
}
-}
-
-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<QString> Shader::uniformsNames() const
-{
- return m_uniformsNames;
-}
-
-QVector<QString> Shader::attributesNames() const
-{
- return m_attributesNames;
-}
-
-QVector<QString> Shader::uniformBlockNames() const
-{
- return m_uniformBlockNames;
-}
-
-QVector<QString> Shader::storageBlockNames() const
-{
- return m_shaderStorageBlockNames;
-}
-
-QVector<QByteArray> Shader::shaderCode() const
-{
- return m_shaderCode;
+ setFormat(node->format());
}
void Shader::setShaderCode(QShaderProgram::ShaderType type, const QByteArray &code)
@@ -170,218 +131,25 @@ void Shader::setShaderCode(QShaderProgram::ShaderType type, const QByteArray &co
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<QString, ShaderUniform> 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)
+void Shader::setFormat(QShaderProgram::Format format)
{
- const PackUniformHash &values = pack.uniforms();
-
- auto it = values.cbegin();
- const auto end = values.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.key()) {
- pack.setSubmissionUniform(uniform);
- break;
- }
- }
- ++it;
- }
-}
-
-void Shader::setFragOutputs(const QHash<QString, int> &fragOutputs)
-{
- {
- QMutexLocker lock(&m_mutex);
- m_fragOutputs = fragOutputs;
- }
- updateDNA();
-}
-
-const QHash<QString, int> 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<QString, int>::const_iterator it = m_fragOutputs.cbegin();
- QHash<QString, int>::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<ShaderUniform> &uniformsDescription)
-{
- m_uniforms = uniformsDescription;
- m_uniformsNames.resize(uniformsDescription.size());
- m_uniformsNamesIds.resize(uniformsDescription.size());
- QHash<QString, ShaderUniform> activeUniformsInDefaultBlock;
-
- for (int i = 0, m = uniformsDescription.size(); i < m; i++) {
- m_uniformsNames[i] = m_uniforms[i].m_name;
- m_uniforms[i].m_nameId = StringToInt::lookupId(m_uniformsNames[i]);
- m_uniformsNamesIds[i] = m_uniforms[i].m_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<ShaderAttribute> &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<ShaderUniformBlock> &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<ShaderUniform>::const_iterator uniformsIt = m_uniforms.cbegin();
- const QVector<ShaderUniform>::const_iterator uniformsEnd = m_uniforms.cend();
-
- QVector<QString>::const_iterator uniformNamesIt = m_uniformsNames.cbegin();
- const QVector<QString>::const_iterator uniformNamesEnd = m_attributesNames.cend();
-
- QHash<QString, ShaderUniform> 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);
- }
+ if (format == m_format)
+ return;
+ m_format = format;
+ m_dirty = true;
+ setStatus(QShaderProgram::NotReady);
+ markDirty(AbstractRenderer::ShadersDirty);
}
-void Shader::initializeShaderStorageBlocks(const QVector<ShaderStorageBlock> &shaderStorageBlockDescription)
+QVector<QByteArray> 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;
}
/*!
@@ -391,25 +159,17 @@ void Shader::initializeShaderStorageBlocks(const QVector<ShaderStorageBlock> &sh
*/
void Shader::initializeFromReference(const Shader &other)
{
- Q_ASSERT(m_dna == other.m_dna);
- m_uniformsNamesIds = other.m_uniformsNamesIds;
- 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());
+}
+
+// Called by renderer plugin when loading a GL Shader plugins
+void Shader::requestCacheRebuild()
+{
+ markDirty(AbstractRenderer::MaterialDirty);
}
void Shader::setLog(const QString &log)
@@ -424,6 +184,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 1c9731e50..5eccc7510 100644
--- a/src/render/materialsystem/shader_p.h
+++ b/src/render/materialsystem/shader_p.h
@@ -52,11 +52,7 @@
//
#include <Qt3DRender/private/backendnode_p.h>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
-#include <Qt3DRender/private/shadervariables_p.h>
#include <Qt3DRender/qshaderprogram.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
-#include <QMutex>
#include <QVector>
QT_BEGIN_NAMESPACE
@@ -70,117 +66,95 @@ namespace Render {
class ShaderManager;
class AttachmentPack;
-typedef uint ProgramDNA;
-
-class Q_AUTOTEST_EXPORT Shader : public BackendNode
+class Q_3DRENDERSHARED_PRIVATE_EXPORT Shader : public BackendNode
{
public:
+ static const int modelMatrixNameId;
+ static const int viewMatrixNameId;
+ static const int projectionMatrixNameId;
+ static const int modelViewMatrixNameId;
+ static const int viewProjectionMatrixNameId;
+ static const int modelViewProjectionNameId;
+ static const int mvpNameId;
+ static const int inverseModelMatrixNameId;
+ static const int inverseViewMatrixNameId;
+ static const int inverseProjectionMatrixNameId;
+ static const int inverseModelViewNameId;
+ static const int inverseViewProjectionMatrixNameId;
+ static const int inverseModelViewProjectionNameId;
+ static const int modelNormalMatrixNameId;
+ static const int modelViewNormalNameId;
+ static const int viewportMatrixNameId;
+ static const int inverseViewportMatrixNameId;
+ static const int aspectRatioNameId;
+ static const int exposureNameId;
+ static const int gammaNameId;
+ static const int timeNameId;
+ static const int eyePositionNameId;
+ static const int skinningPaletteNameId;
+
Shader();
~Shader();
void cleanup();
- void setGraphicsContext(GraphicsContext *context);
- GraphicsContext *graphicsContext();
-
- void prepareUniforms(ShaderParameterPack &pack);
- void setFragOutputs(const QHash<QString, int> &fragOutputs);
- const QHash<QString, int> fragOutputs() const;
-
- inline QVector<int> uniformsNamesIds() const { return m_uniformsNamesIds; }
- inline QVector<int> uniformBlockNamesIds() const { return m_uniformBlockNamesIds; }
- inline QVector<int> storageBlockNamesIds() const { return m_shaderStorageBlockNamesIds; }
- inline QVector<int> attributeNamesIds() const { return m_attributeNamesIds; }
-
- QVector<QString> uniformsNames() const;
- QVector<QString> attributesNames() const;
- QVector<QString> uniformBlockNames() const;
- QVector<QString> storageBlockNames() const;
QVector<QByteArray> 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<ShaderUniform> uniforms() const { return m_uniforms; }
- inline QVector<ShaderAttribute> attributes() const { return m_attributes; }
- inline QVector<ShaderUniformBlock> uniformBlocks() const { return m_uniformBlocks; }
- inline QVector<ShaderStorageBlock> storageBlocks() const { return m_shaderStorageBlocks; }
-
- QHash<QString, ShaderUniform> 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; }
+ void setFormat(QShaderProgram::Format format);
+ QShaderProgram::Format format() const { return m_format; }
+ 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<QString> m_uniformsNames;
- QVector<int> m_uniformsNamesIds;
- QVector<ShaderUniform> m_uniforms;
-
- QVector<QString> m_attributesNames;
- QVector<int> m_attributeNamesIds;
- QVector<ShaderAttribute> m_attributes;
-
- QVector<QString> m_uniformBlockNames;
- QVector<int> m_uniformBlockNamesIds;
- QVector<ShaderUniformBlock> m_uniformBlocks;
- QHash<int, QHash<QString, ShaderUniform> > m_uniformBlockIndexToShaderUniforms;
-
- QVector<QString> m_shaderStorageBlockNames;
- QVector<int> m_shaderStorageBlockNamesIds;
- QVector<ShaderStorageBlock> m_shaderStorageBlocks;
+ // Set by Renderer plugin
+ void setLog(const QString &log);
+ void setStatus(QShaderProgram::Status status);
+ void initializeFromReference(const Shader &other);
- QHash<QString, int> m_fragOutputs;
+ void requestCacheRebuild();
+private:
QVector<QByteArray> 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;
+ QShaderProgram::Status m_status;
+ QShaderProgram::Format m_format;
+ bool m_dirty;
- void updateDNA();
-
- // Private so that only GraphicContext can call it
- void initializeUniforms(const QVector<ShaderUniform> &uniformsDescription);
- void initializeAttributes(const QVector<ShaderAttribute> &attributesDescription);
- void initializeUniformBlocks(const QVector<ShaderUniformBlock> &uniformBlockDescription);
- void initializeShaderStorageBlocks(const QVector<ShaderStorageBlock> &shaderStorageBlockDescription);
-
- void initializeFromReference(const Shader &other);
- void setLog(const QString &log);
- void setStatus(QShaderProgram::Status status);
-
- friend class GraphicsContext;
};
#ifndef QT_NO_DEBUG_STREAM
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/shaderbuilder.cpp b/src/render/materialsystem/shaderbuilder.cpp
index 23f1400c9..7434cd901 100644
--- a/src/render/materialsystem/shaderbuilder.cpp
+++ b/src/render/materialsystem/shaderbuilder.cpp
@@ -278,7 +278,7 @@ void ShaderBuilder::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
markDirty(AbstractRenderer::ShadersDirty);
}
- static const std::pair<QShaderProgram::ShaderType, QUrl (QShaderProgramBuilder::*)() const> shaderTypesToGetters[] = {
+ static const QVector<std::pair<QShaderProgram::ShaderType, QUrl (QShaderProgramBuilder::*)() const>> shaderTypesToGetters = {
{QShaderProgram::Vertex, &QShaderProgramBuilder::vertexShaderGraph},
{QShaderProgram::TessellationControl, &QShaderProgramBuilder::tessellationControlShaderGraph},
{QShaderProgram::TessellationEvaluation, &QShaderProgramBuilder::tessellationEvaluationShaderGraph},
@@ -287,7 +287,7 @@ void ShaderBuilder::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
{QShaderProgram::Compute, &QShaderProgramBuilder::computeShaderGraph},
};
- for (auto it = std::cbegin(shaderTypesToGetters), end = std::cend(shaderTypesToGetters); it != end; ++it) {
+ for (auto it = shaderTypesToGetters.cbegin(), end = shaderTypesToGetters.cend(); it != end; ++it) {
const QUrl url = (node->*(it->second))();
if (url != m_graphs.value(it->first)) {
setShaderGraph(it->first, url);
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 <QtCore/QMutexLocker>
-
-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<Qt3DCore::QNodeId> &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<Qt3DCore::QNodeId> 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<Qt3DCore::QNodeId> &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<Qt3DCore::QNodeId> &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<Qt3DCore::QNodeId> ShaderCache::shaderIdsForProgram(ProgramDNA dna) const
-{
- return m_programRefs.value(dna);
-}
-
-} // namespace Render
-} // namespace Qt3DRender
-
-QT_END_NAMESPACE
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 <QMetaObject>
#include <Qt3DCore/qdynamicpropertyupdatedchange.h>
#include <Qt3DCore/qpropertyupdatedchange.h>
-#include <private/graphicscontext_p.h>
#include <private/qbackendnode_p.h>
-#include <private/glbuffer_p.h>
#include <private/managers_p.h>
#include <private/nodemanagers_p.h>
-#include <private/renderviewjobutils_p.h>
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 <Qt3DRender/private/backendnode_p.h>
-#include <Qt3DRender/private/shadervariables_p.h>
#include <Qt3DRender/qshaderdata.h>
#include <QMutex>
#include <Qt3DCore/private/matrix4x4_p.h>
@@ -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/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/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 <Qt3DRender/qparameter.h>
#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qgraphicsapifilter.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/filterkey_p.h>
#include <Qt3DRender/private/qtechnique_p.h>
#include <Qt3DRender/private/shader_p.h>
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<QPickEvent> 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 <QMouseEvent>
#include <QKeyEvent>
#include <QtCore/qmutex.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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/qabstractraycaster.cpp b/src/render/picking/qabstractraycaster.cpp
index ab0916401..f26c67e99 100644
--- a/src/render/picking/qabstractraycaster.cpp
+++ b/src/render/picking/qabstractraycaster.cpp
@@ -58,10 +58,6 @@ QAbstractRayCasterPrivate::QAbstractRayCasterPrivate()
m_shareable = false;
}
-/*!
- \property Qt3DRender::QAbstractRayCaster::Hits
-*/
-
QAbstractRayCasterPrivate *QAbstractRayCasterPrivate::get(QAbstractRayCaster *obj)
{
return obj->d_func();
@@ -341,11 +337,7 @@ void QAbstractRayCaster::addLayer(QLayer *layer)
if (!layer->parent())
layer->setParent(this);
- if (d->m_changeArbiter != nullptr) {
- const auto change = Qt3DCore::QPropertyNodeAddedChangePtr::create(id(), layer);
- change->setPropertyName("layer");
- d->notifyObservers(change);
- }
+ d->updateNode(layer, "layer", Qt3DCore::PropertyValueAdded);
}
}
@@ -356,11 +348,7 @@ void QAbstractRayCaster::removeLayer(QLayer *layer)
{
Q_ASSERT(layer);
Q_D(QAbstractRayCaster);
- if (d->m_changeArbiter != nullptr) {
- const auto change = Qt3DCore::QPropertyNodeRemovedChangePtr::create(id(), layer);
- change->setPropertyName("layer");
- d->notifyObservers(change);
- }
+ d->updateNode(layer, "layer", Qt3DCore::PropertyValueRemoved);
d->m_layers.removeOne(layer);
// Remove bookkeeping connection
d->unregisterDestructionHelper(layer);
diff --git a/src/render/picking/qobjectpicker.cpp b/src/render/picking/qobjectpicker.cpp
index 7d9741f21..4f039b361 100644
--- a/src/render/picking/qobjectpicker.cpp
+++ b/src/render/picking/qobjectpicker.cpp
@@ -152,7 +152,7 @@ namespace Qt3DRender {
This signal is emitted when the bounding volume defined by the
pickAttribute property intersects with a ray on a mouse click. Intersection
- information are accessible through the pick \a parameter.
+ information are accessible through the \a pick parameter.
*/
/*!
@@ -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);
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 <Qt3DCore/private/qcomponent_p.h>
#include <Qt3DCore/qnodeid.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DRender/private/qt3drender_global_p.h>
#include <Qt3DRender/private/objectpicker_p.h>
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 <Qt3DRender/qlayer.h>
#include <Qt3DRender/private/qabstractraycaster_p.h>
#include <Qt3DRender/private/raycastingjob_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
QT_BEGIN_NAMESPACE
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 <QtCore/QObject>
+#include <QtCore/QtPlugin>
+#include <QtCore/QFactoryInterface>
+#include <Qt3DRender/private/qt3drender_global_p.h>
+#include <Qt3DRender/qrenderaspect.h>
+
+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 <QtCore/private/qfactoryloader_p.h>
+#include <QtCore/QCoreApplication>
+#include <QtCore/QDir>
+
+#include <Qt3DRender/private/qrendererplugin_p.h>
+
+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<AbstractRenderer, QRendererPlugin>(directLoader(), name, renderMode))
+ return ret;
+#else
+ qWarning() << QObject::tr("Cannot load QRendererPlugin plugin from %1. "
+ "Library loading is disabled.").arg(pluginPath);
+#endif
+ }
+ return qLoadPlugin<AbstractRenderer, QRendererPlugin>(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 <Qt3DRender/private/qt3drender_global_p.h>
+#include <Qt3DRender/qrenderaspect.h>
+#include <QtCore/QStringList>
+
+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/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/render.pro b/src/render/render.pro
index 55303fa83..2b81e8a06 100644
--- a/src/render/render.pro
+++ b/src/render/render.pro
@@ -1,9 +1,9 @@
TARGET = Qt3DRender
MODULE = 3drender
-QT = core-private gui-private 3dcore-private
-QT_PRIVATE = openglextensions
+QT = core-private 3dcore-private opengl
QT_FOR_PRIVATE = concurrent
+DEFINES += BUILD_QT3D_MODULE
include (backend/render-backend.pri)
include (geometry/geometry.pri)
@@ -18,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
@@ -39,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/opengl.pri b/src/render/renderers/opengl/opengl.pri
deleted file mode 100644
index 150c37f23..000000000
--- a/src/render/renderers/opengl/opengl.pri
+++ /dev/null
@@ -1,13 +0,0 @@
-qtHaveModule(opengl): QT += opengl opengl-private
-
-include (renderer/renderer.pri)
-include (jobs/jobs.pri)
-include (io/io.pri)
-include (textures/textures.pri)
-include (graphicshelpers/graphicshelpers.pri)
-include (renderstates/renderstates.pri)
-
-gcov {
- QMAKE_CXXFLAGS += -fprofile-arcs -ftest-coverage
- QMAKE_LFLAGS += -fprofile-arcs -ftest-coverage
-}
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/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 <Qt3DRender/private/qrenderstatecreatedchange_p.h>
#include <Qt3DCore/private/qresourcemanager_p.h>
#include <Qt3DRender/private/statemask_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
//#include <Qt3DRender/private/statevariant_p.h>
#include <QList>
#include <QVector3D>
@@ -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/qrastermode.cpp b/src/render/renderstates/qrastermode.cpp
index c432f1063..648872a84 100644
--- a/src/render/renderstates/qrastermode.cpp
+++ b/src/render/renderstates/qrastermode.cpp
@@ -48,7 +48,7 @@ namespace Qt3DRender {
/*!
\class Qt3DRender::QRasterMode
\brief The QRasterMode render state allows to control the type of
- rasterization to be performed
+ rasterization to be performed.
\since 5.14
\inmodule Qt3DRender
\ingroup renderstates
@@ -65,7 +65,7 @@ namespace Qt3DRender {
/*!
\qmltype RasterMode
\brief The RasterMode render state allows to control the type of
- rasterization to be performed
+ rasterization to be performed.
\since 5.14
\inqmlmodule Qt3D.Render
\inherits RenderState
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 <Qt3DRender/qcullface.h>
#include <Qt3DRender/qpointsize.h>
-#include <Qt3DRender/private/graphicscontext_p.h>
#include <Qt3DRender/private/qstenciloperation_p.h>
#include <Qt3DRender/private/qstenciltest_p.h>
#include <Qt3DRender/qblendequationarguments.h>
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<BlendEquationArguments, BlendEquationArgumentsMask, GLenum, GLenum, GLenum, GLenum, bool, int>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT BlendEquationArguments : public GenericState<BlendEquationArguments, BlendEquationArgumentsMask, GLenum, GLenum, GLenum, GLenum, bool, int>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT BlendEquation : public GenericState<BlendEquation, BlendStateMask, GLenum>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT BlendEquation : public GenericState<BlendEquation, BlendStateMask, GLenum>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT AlphaFunc : public GenericState<AlphaFunc, AlphaTestMask, GLenum, GLclampf>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT AlphaFunc : public GenericState<AlphaFunc, AlphaTestMask, GLenum, GLclampf>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT MSAAEnabled : public GenericState<MSAAEnabled, MSAAEnabledStateMask, GLboolean>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT MSAAEnabled : public GenericState<MSAAEnabled, MSAAEnabledStateMask, GLboolean>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT DepthRange : public GenericState<DepthRange, DepthRangeMask, double, double>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT DepthRange : public GenericState<DepthRange, DepthRangeMask, double, double>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT DepthTest : public GenericState<DepthTest, DepthTestStateMask, GLenum>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT DepthTest : public GenericState<DepthTest, DepthTestStateMask, GLenum>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT RasterMode : public GenericState<RasterMode, RasterModeMask, GLenum, GLenum>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT RasterMode : public GenericState<RasterMode, RasterModeMask, GLenum, GLenum>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT NoDepthMask : public GenericState<NoDepthMask, DepthWriteStateMask, GLboolean>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT NoDepthMask : public GenericState<NoDepthMask, DepthWriteStateMask, GLboolean>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT CullFace : public GenericState<CullFace, CullFaceStateMask, GLenum>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT CullFace : public GenericState<CullFace, CullFaceStateMask, GLenum>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT FrontFace : public GenericState<FrontFace, FrontFaceStateMask, GLenum>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT FrontFace : public GenericState<FrontFace, FrontFaceStateMask, GLenum>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT Dithering : public GenericState<Dithering, DitheringStateMask>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT Dithering : public GenericState<Dithering, DitheringStateMask>
{
};
-class Q_AUTOTEST_EXPORT ScissorTest : public GenericState<ScissorTest, ScissorStateMask, int, int, int, int>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ScissorTest : public GenericState<ScissorTest, ScissorStateMask, int, int, int, int>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT StencilTest : public GenericState<StencilTest, StencilTestStateMask, GLenum, int, uint, GLenum, int, uint>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT StencilTest : public GenericState<StencilTest, StencilTestStateMask, GLenum, int, uint, GLenum, int, uint>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT AlphaCoverage : public GenericState<AlphaCoverage, AlphaCoverageStateMask>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT AlphaCoverage : public GenericState<AlphaCoverage, AlphaCoverageStateMask>
{
};
-class Q_AUTOTEST_EXPORT PointSize : public GenericState<PointSize, PointSizeMask, bool, GLfloat>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT PointSize : public GenericState<PointSize, PointSizeMask, bool, GLfloat>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT PolygonOffset : public GenericState<PolygonOffset, PolygonOffsetStateMask, GLfloat, GLfloat>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT PolygonOffset : public GenericState<PolygonOffset, PolygonOffsetStateMask, GLfloat, GLfloat>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT ColorMask : public GenericState<ColorMask, ColorStateMask, GLboolean, GLboolean, GLboolean, GLboolean>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ColorMask : public GenericState<ColorMask, ColorStateMask, GLboolean, GLboolean, GLboolean, GLboolean>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT ClipPlane : public GenericState<ClipPlane, ClipPlaneMask, int, QVector3D, float>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT ClipPlane : public GenericState<ClipPlane, ClipPlaneMask, int, QVector3D, float>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT SeamlessCubemap : public GenericState<SeamlessCubemap, SeamlessCubemapMask>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT SeamlessCubemap : public GenericState<SeamlessCubemap, SeamlessCubemapMask>
{
};
-class Q_AUTOTEST_EXPORT StencilOp : public GenericState<StencilOp, StencilOpMask, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT StencilOp : public GenericState<StencilOp, StencilOpMask, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT StencilMask : public GenericState<StencilMask, StencilWriteStateMask, uint, uint>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT StencilMask : public GenericState<StencilMask, StencilWriteStateMask, uint, uint>
{
public:
void updateProperties(const QRenderState *node) override;
};
-class Q_AUTOTEST_EXPORT LineWidth : public GenericState<LineWidth, LineWidthMask, GLfloat, bool>
+class Q_3DRENDERSHARED_PRIVATE_EXPORT LineWidth : public GenericState<LineWidth, LineWidthMask, GLfloat, bool>
{
public:
void updateProperties(const QRenderState *node) override;
diff --git a/src/render/renderers/opengl/renderstates/renderstateset.cpp b/src/render/renderstates/renderstateset.cpp
index d667d9c76..6b66d2dd7 100644
--- a/src/render/renderers/opengl/renderstates/renderstateset.cpp
+++ b/src/render/renderstates/renderstateset.cpp
@@ -42,9 +42,6 @@
#include <bitset>
-#include <QDebug>
-#include <QOpenGLContext>
-
#include <Qt3DRender/private/renderstates_p.h>
#include <Qt3DRender/private/qrenderstate_p.h>
diff --git a/src/render/renderers/opengl/renderstates/renderstateset_p.h b/src/render/renderstates/renderstateset_p.h
index c2f3a0219..119f1edca 100644
--- a/src/render/renderers/opengl/renderstates/renderstateset_p.h
+++ b/src/render/renderstates/renderstateset_p.h
@@ -67,7 +67,7 @@ namespace Render {
class RenderState;
-class RenderStateSet
+class Q_3DRENDERSHARED_PRIVATE_EXPORT RenderStateSet
{
public:
RenderStateSet();
@@ -112,7 +112,7 @@ private:
};
template<>
-void RenderStateSet::addState<StateVariant>(const StateVariant &state);
+Q_3DRENDERSHARED_PRIVATE_EXPORT void RenderStateSet::addState<StateVariant>(const StateVariant &state);
} // namespace Render
} // namespace Qt3DRender
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.cpp b/src/render/services/vsyncframeadvanceservice.cpp
index b49870e68..662c12e4e 100644
--- a/src/render/services/vsyncframeadvanceservice.cpp
+++ b/src/render/services/vsyncframeadvanceservice.cpp
@@ -62,7 +62,7 @@ public:
QSemaphore m_semaphore;
QElapsedTimer m_elapsed;
- quint64 m_elapsedTimeSincePreviousFrame;
+ qint64 m_elapsedTimeSincePreviousFrame;
bool m_drivenByRenderThread;
};
@@ -75,14 +75,14 @@ VSyncFrameAdvanceService::~VSyncFrameAdvanceService()
{
}
-// Aspect Thread
+// Main Thread
qint64 VSyncFrameAdvanceService::waitForNextFrame()
{
Q_D(VSyncFrameAdvanceService);
d->m_semaphore.acquire(std::max(d->m_semaphore.available(), 1));
- const quint64 currentTime = d->m_elapsed.nsecsElapsed();
+ const qint64 currentTime = d->m_elapsed.nsecsElapsed();
qCDebug(VSyncAdvanceService) << "Elapsed nsecs since last call " << currentTime - d->m_elapsedTimeSincePreviousFrame;
d->m_elapsedTimeSincePreviousFrame = currentTime;
return currentTime;
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 <Qt3DCore/private/qabstractframeadvanceservice_p.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
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/qabstracttexture.cpp b/src/render/texture/qabstracttexture.cpp
index 7fca2ba3f..2e7fd0f63 100644
--- a/src/render/texture/qabstracttexture.cpp
+++ b/src/render/texture/qabstracttexture.cpp
@@ -977,7 +977,7 @@ float QAbstractTexture::maximumAnisotropy() const
}
/*!
- \property Qt3DRender::QAbstractTexture::ComparisonFunction
+ \property Qt3DRender::QAbstractTexture::comparisonFunction
Holds the comparison function of the texture provider.
*/
@@ -1008,7 +1008,7 @@ QAbstractTexture::ComparisonFunction QAbstractTexture::comparisonFunction() cons
}
/*!
- \property Qt3DRender::QAbstractTexture::ComparisonMode
+ \property Qt3DRender::QAbstractTexture::comparisonMode
Holds the comparison mode of the texture provider.
*/
@@ -1055,9 +1055,12 @@ QTextureGeneratorPtr QAbstractTexture::dataGenerator() const
*/
/*!
- * \qmlproperty handleType
+ * \qmlproperty enumeration AbstractTexture::handleType
*
* Holds the current texture handle type.
+ *
+ * \value AbstractTexture.NoHandle
+ * \value AbstractTexture.OpenGLTextureId
*/
/*!
@@ -1070,7 +1073,6 @@ QAbstractTexture::HandleType QAbstractTexture::handleType() const
return d->m_handleType;
}
-
/*!
* \property Qt3DRender::QAbstractTexture::handle
*
@@ -1079,7 +1081,7 @@ QAbstractTexture::HandleType QAbstractTexture::handleType() const
*/
/*!
- * \qmlproperty handle
+ * \qmlproperty var AbstractTexture::handle
*
* Holds the current texture handle, if Qt 3D is using the OpenGL renderer,
* handle is a texture id integer.
@@ -1098,8 +1100,8 @@ QVariant QAbstractTexture::handle() const
}
/*!
- * Allow to update a sub region of the texture without having to change the data
- * generator or rely on adding or removing texture images.
+ * Updates a sub region of the texture, defined by \a update, without having
+ * to change the data generator or rely on adding or removing texture images.
* \since 5.14
*/
void QAbstractTexture::updateData(const QTextureDataUpdate &update)
@@ -1135,7 +1137,7 @@ Qt3DCore::QNodeCreatedChangeBasePtr QAbstractTexture::createNodeCreationChange()
data.dataFunctor = d->m_dataFunctor;
data.sharedTextureId = d->m_sharedTextureId;
data.initialDataUpdates = d->m_pendingDataUpdates;
- return std::move(creationChange);
+ return creationChange;
}
/*!
@@ -1180,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/src/render/texture/qabstracttextureimage.cpp b/src/render/texture/qabstracttextureimage.cpp
index 9ca4599c5..6f68221fd 100644
--- a/src/render/texture/qabstracttextureimage.cpp
+++ b/src/render/texture/qabstracttextureimage.cpp
@@ -131,8 +131,8 @@ QTextureImageDataGeneratorPtr QAbstractTextureImagePrivate::dataGenerator() cons
/*!
\fn Qt3DRender::QTextureImageDataGeneratorPtr Qt3DRender::QAbstractTextureImage::dataGenerator() const
- Implement this method to return the \l QTextureImageDataGeneratorPtr, which will
- provide the data for the texture image.
+ Implement this method to return the QTextureImageDataGeneratorPtr instance,
+ which will provide the data for the texture image.
*/
/*!
diff --git a/src/render/texture/qtexture.cpp b/src/render/texture/qtexture.cpp
index bca66e630..6b7b92166 100644
--- a/src/render/texture/qtexture.cpp
+++ b/src/render/texture/qtexture.cpp
@@ -57,7 +57,7 @@
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/texture_p.h>
#include <Qt3DRender/private/qurlhelper_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
+#include <qmath.h>
QT_BEGIN_NAMESPACE
@@ -1125,7 +1125,7 @@ TextureDownloadRequest::TextureDownloadRequest(const QTextureFromSourceGenerator
}
-// Executed in aspect thread
+// Executed in main thread
void TextureDownloadRequest::onCompleted()
{
if (cancelled() || !succeeded())
@@ -1142,16 +1142,11 @@ void TextureDownloadRequest::onCompleted()
QTextureFromSourceGeneratorPtr oldGenerator = qSharedPointerCast<QTextureFromSourceGenerator>(texture->dataGenerator());
- // We create a new functor
- // Which is a copy of the old one + the downloaded sourceData
- auto newGenerator = QTextureFromSourceGeneratorPtr::create(*oldGenerator);
-
// Set raw data on functor so that it can really load something
- newGenerator->m_sourceData = m_data;
+ oldGenerator->m_sourceData = m_data;
- // Set new generator on texture
- // it implictely marks the texture as dirty so that the functor runs again with the downloaded data
- texture->setDataGenerator(newGenerator);
+ // Mark the texture as dirty so that the functor runs again with the downloaded data
+ texture->addDirtyFlag(Render::Texture::DirtyDataGenerator);
}
/*!
@@ -1520,7 +1515,10 @@ QTextureLoader::QTextureLoader(QNode *parent)
// Regenerate the texture functor when properties we support overriding
// from QAbstractTexture get changed.
Q_D(QTextureLoader);
- auto regenerate = [=] () { d->updateGenerator(); };
+ auto regenerate = [=] () {
+ if (!notificationsBlocked()) // check the change doesn't come from the backend
+ d->updateGenerator();
+ };
connect(this, &QAbstractTexture::formatChanged, regenerate);
}
diff --git a/src/render/texture/qtexturegenerator.cpp b/src/render/texture/qtexturegenerator.cpp
index 5e350af2d..36b5f6498 100644
--- a/src/render/texture/qtexturegenerator.cpp
+++ b/src/render/texture/qtexturegenerator.cpp
@@ -52,8 +52,7 @@ QTextureGenerator::~QTextureGenerator()
}
/*!
- \class QTextureGenerator
- \inherits QAbstractFunctor
+ \class Qt3DRender::QTextureGenerator
\inmodule Qt3DRender
\brief Provides the image data for a texture.
*/
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 <Qt3DRender/private/qt3drender_global_p.h>
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 d120c2b39..dab037568 100644
--- a/src/render/texture/texture.cpp
+++ b/src/render/texture/texture.cpp
@@ -47,7 +47,7 @@
#include <Qt3DCore/qpropertynoderemovedchange.h>
#include <Qt3DRender/private/texture_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
+#include <Qt3DRender/private/qabstracttexture_p.h>
#include <Qt3DRender/private/managers_p.h>
QT_BEGIN_NAMESPACE
@@ -149,6 +149,8 @@ void Texture::syncFromFrontEnd(const QNode *frontEnd, bool firstTime)
auto newGenerator = node->dataGenerator();
if (newGenerator != m_dataFunctor) {
setDataGenerator(newGenerator);
+ QAbstractTexturePrivate *dTexture = static_cast<QAbstractTexturePrivate *>(QNodePrivate::get(const_cast<QNode *>(frontEnd)));
+ dTexture->setStatus(QAbstractTexture::Loading);
}
QAbstractTexturePrivate *dnode = dynamic_cast<QAbstractTexturePrivate *>(QAbstractTexturePrivate::get(const_cast<QAbstractTexture *>(node)));
@@ -163,11 +165,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);
+ }
}
}
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 <QMutex>
+#include <QMutexLocker>
+#include <Qt3DRender/qtexture.h>
+#include <Qt3DRender/qtextureimagedata.h>
+#include <Qt3DRender/qtexturegenerator.h>
+#include <Qt3DRender/qtextureimagedatagenerator.h>
+#include <Qt3DRender/private/qt3drender_global_p.h>
+
+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 GeneratorPtr, class DataPtr, class ReferencedType>
+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<GeneratorPtr> pendingGenerators()
+ {
+ QMutexLocker lock(&m_mutex);
+
+ QVector<GeneratorPtr> 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<ReferencedType> 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<Entry> m_data;
+};
+
+class QT3DRENDERSHARED_PRIVATE_EXPORT TextureDataManager
+ : public GeneratorDataManager<QTextureGeneratorPtr, QTextureDataPtr, void*>
+{
+};
+
+class QT3DRENDERSHARED_PRIVATE_EXPORT TextureImageDataManager
+ : public GeneratorDataManager<QTextureImageDataGeneratorPtr, QTextureImageDataPtr, Qt3DCore::QNodeId>
+{
+};
+
+} // 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/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.*::.+";
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 <Qt3DAnimation/qanimationcliploader.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
-#include <Qt3DCore/private/qpropertyupdatedchangebase_p.h>
#include <qbackendnodetester.h>
#include <testpostmanarbiter.h>
diff --git a/tests/auto/animation/animationutils/tst_animationutils.cpp b/tests/auto/animation/animationutils/tst_animationutils.cpp
index 463656557..05558192d 100644
--- a/tests/auto/animation/animationutils/tst_animationutils.cpp
+++ b/tests/auto/animation/animationutils/tst_animationutils.cpp
@@ -38,7 +38,6 @@
#include <Qt3DAnimation/private/additiveclipblend_p.h>
#include <Qt3DAnimation/private/lerpclipblend_p.h>
#include <Qt3DAnimation/private/managers_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <QtGui/qvector2d.h>
#include <QtGui/qvector3d.h>
#include <QtGui/qvector4d.h>
@@ -57,7 +56,6 @@ Q_DECLARE_METATYPE(Clock *)
Q_DECLARE_METATYPE(ChannelMapper *)
Q_DECLARE_METATYPE(AnimationClip *)
Q_DECLARE_METATYPE(QVector<MappingData>)
-Q_DECLARE_METATYPE(QVector<Qt3DCore::QPropertyUpdatedChangePtr>)
Q_DECLARE_METATYPE(Channel)
Q_DECLARE_METATYPE(AnimatorEvaluationData)
Q_DECLARE_METATYPE(ClipEvaluationData)
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 <Qt3DAnimation/qblendedclipanimator.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
#include <qbackendnodetester.h>
#include <testpostmanarbiter.h>
@@ -44,7 +43,6 @@
#include <Qt3DAnimation/qchannelmapper.h>
#include <Qt3DAnimation/private/qblendedclipanimator_p.h>
#include <Qt3DAnimation/private/blendedclipanimator_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include "qbackendnodetester.h"
class tst_BlendedClipAnimator : public Qt3DCore::QBackendNodeTester
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 <Qt3DCore/qskeleton.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
#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<Qt3DCore::QPropertyUpdatedChange>::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/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 <QtTest/QTest>
#include <Qt3DAnimation/qanimationcliploader.h>
#include <Qt3DAnimation/private/qanimationcliploader_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qnodecreatedchange.h>
#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
#include <QObject>
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 <Qt3DAnimation/private/skeleton_p.h>
#include <Qt3DAnimation/private/handler_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
#include <qbackendnodetester.h>
#include <testpostmanarbiter.h>
diff --git a/tests/auto/core/common/qbackendnodetester.cpp b/tests/auto/core/common/qbackendnodetester.cpp
index a2685f556..13f4683d9 100644
--- a/tests/auto/core/common/qbackendnodetester.cpp
+++ b/tests/auto/core/common/qbackendnodetester.cpp
@@ -56,20 +56,29 @@ void QBackendNodeTester::simulateInitialization(QNode *frontend, QBackendNode *b
{
Q_ASSERT(frontend);
Q_ASSERT(backend);
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
const auto change = frontend->createNodeCreationChange();
backend->setPeerId(change->subjectId());
backend->setEnabled(change->isNodeEnabled());
backend->initializeFromPeer(change);
+ QT_WARNING_POP
}
void QBackendNodeTester::sceneChangeEvent(QBackendNode *backend, const Qt3DCore::QSceneChangePtr &e)
{
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
backend->sceneChangeEvent(e);
+ QT_WARNING_POP
}
QNodeCreatedChangeBasePtr QBackendNodeTester::creationChange(QNode *frontend) const
{
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
return frontend->createNodeCreationChange();
+ QT_WARNING_POP
}
} // namespace Qt3DCore
diff --git a/tests/auto/core/common/testpostmanarbiter.cpp b/tests/auto/core/common/testpostmanarbiter.cpp
index 5869cbad3..f0c362744 100644
--- a/tests/auto/core/common/testpostmanarbiter.cpp
+++ b/tests/auto/core/common/testpostmanarbiter.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include "testpostmanarbiter.h"
#include <Qt3DCore/private/qnode_p.h>
diff --git a/tests/auto/core/common/testpostmanarbiter.h b/tests/auto/core/common/testpostmanarbiter.h
index cecc24f93..e927c2489 100644
--- a/tests/auto/core/common/testpostmanarbiter.h
+++ b/tests/auto/core/common/testpostmanarbiter.h
@@ -70,7 +70,10 @@ public:
void setArbiterOnNode(Qt3DCore::QNode *node);
void addDirtyFrontEndNode(Qt3DCore::QNode *node) final;
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
void addDirtyFrontEndNode(Qt3DCore::QNode *node, Qt3DCore::QNode *subNode, const char *property, Qt3DCore::ChangeFlag change) final;
+ QT_WARNING_POP
void removeDirtyFrontEndNode(Qt3DCore::QNode *node) final;
private:
diff --git a/tests/auto/core/core.pro b/tests/auto/core/core.pro
index 37c707aa7..3e4a8479d 100644
--- a/tests/auto/core/core.pro
+++ b/tests/auto/core/core.pro
@@ -22,10 +22,11 @@ qtConfig(private_tests) {
threadpooler \
qpostman \
vector4d_base \
- vector3d_base
+ vector3d_base \
+ aspectcommanddebugger \
+ qscheduler
QT_FOR_CONFIG += 3dcore-private
- qtConfig(qt3d-profile-jobs): SUBDIRS += aspectcommanddebugger
qtConfig(qt3d-simd-sse2) {
SUBDIRS += \
vector4d_sse \
diff --git a/tests/auto/core/nodes/tst_nodes.cpp b/tests/auto/core/nodes/tst_nodes.cpp
index d65e20708..c39638754 100644
--- a/tests/auto/core/nodes/tst_nodes.cpp
+++ b/tests/auto/core/nodes/tst_nodes.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DCore/qnode.h>
#include <Qt3DCore/qentity.h>
@@ -40,6 +44,7 @@
#include <Qt3DCore/qpropertynoderemovedchange.h>
#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
#include <Qt3DCore/private/qaspectengine_p.h>
+#include <Qt3DCore/private/qaspectengine_p.h>
#include <private/qabstractaspect_p.h>
#include <private/qpostman_p.h>
@@ -92,6 +97,7 @@ private slots:
void checkConstructionWithNonRootParent(); // QTBUG-73986
void checkConstructionAsListElement();
void checkSceneIsSetOnConstructionWithParent(); // QTBUG-69352
+ void checkSubNodePostConstructIsCalledWhenReferincingNodeProperty(); // QTBUG-79350
void appendingComponentToEntity();
void appendingParentlessComponentToEntityWithoutScene();
@@ -290,22 +296,15 @@ public slots:
if (!attribute->parent())
attribute->setParent(this);
- if (d->m_changeArbiter != nullptr) {
- const auto change = Qt3DCore::QPropertyNodeAddedChangePtr::create(id(), attribute);
- change->setPropertyName("attribute");
- d->notifyObservers(change);
- }
+ d->updateNode(attribute, "attribute", Qt3DCore::PropertyValueAdded);
}
}
void removeAttribute(MyQNode *attribute)
{
Qt3DCore::QNodePrivate *d = Qt3DCore::QNodePrivate::get(this);
- if (d->m_changeArbiter != nullptr) {
- const auto change = Qt3DCore::QPropertyNodeRemovedChangePtr::create(id(), attribute);
- change->setPropertyName("attribute");
- d->notifyObservers(change);
- }
+ d->updateNode(attribute, "attribute", Qt3DCore::PropertyValueRemoved);
+
m_attributes.removeOne(attribute);
// Remove bookkeeping connection
d->unregisterDestructionHelper(attribute);
@@ -384,11 +383,7 @@ public:
if (!attribute->parent())
attribute->setParent(this);
- if (d->m_changeArbiter != nullptr) {
- const auto change = Qt3DCore::QPropertyNodeAddedChangePtr::create(id(), attribute);
- change->setPropertyName("attribute");
- d->notifyObservers(change);
- }
+ d->updateNode(attribute, "attribute", Qt3DCore::PropertyValueRemoved);
}
}
@@ -435,6 +430,29 @@ public:
}
};
+class MyFakeMaterial : public Qt3DCore::QComponent
+{
+ Q_OBJECT
+public:
+ explicit MyFakeMaterial(Qt3DCore::QNode *parent = nullptr)
+ : QComponent(parent)
+ , m_effect(new MyQNode(this))
+ , m_technique(new MyQNode(m_effect))
+ , m_renderPass(new MyQNode(m_technique))
+ {
+ }
+
+ void setArbiter(Qt3DCore::QAbstractArbiter *arbiter)
+ {
+ Q_ASSERT(arbiter);
+ Qt3DCore::QComponentPrivate::get(this)->setArbiter(arbiter);
+ }
+
+ MyQNode *m_effect;
+ MyQNode *m_technique;
+ MyQNode *m_renderPass;
+};
+
class TestAspectPrivate;
class TestAspect : public Qt3DCore::QAbstractAspect
{
@@ -928,6 +946,7 @@ void tst_Nodes::checkParentChangeFromExistingBackendParentToNewlyCreatedParent()
// GIVEN
ObserverSpy spy;
Qt3DCore::QAspectEngine engine;
+ engine.setRunMode(Qt3DCore::QAspectEngine::Manual);
QScopedPointer<MyQEntity> root(new MyQEntity());
root->setArbiterAndEngine(&spy, &engine);
auto aspect = new TestAspect;
@@ -937,6 +956,7 @@ void tst_Nodes::checkParentChangeFromExistingBackendParentToNewlyCreatedParent()
MyQNode *child2(new MyQNode(root.data()));
QCoreApplication::processEvents();
+ engine.processFrame();
// Due to the way we create root, it has a backend
QVERIFY(Qt3DCore::QNodePrivate::get(root.data())->m_hasBackendNode == true);
@@ -967,6 +987,7 @@ void tst_Nodes::checkParentChangeFromExistingBackendParentToNewlyCreatedParent()
// WHEN
QCoreApplication::processEvents();
+ engine.processFrame();
// THEN
QCOMPARE(spy.events.size(), 2);
@@ -1043,6 +1064,7 @@ void tst_Nodes::checkParentChangeFromExistingBackendParentToNewlyCreatedParent()
// WHEN
QCoreApplication::processEvents();
+ engine.processFrame();
// THEN
QCOMPARE(spy.events.size(), 2);
@@ -1221,6 +1243,7 @@ void tst_Nodes::checkAllBackendCreationDoneInSingleFrame()
// GIVEN
ObserverSpy spy;
Qt3DCore::QAspectEngine engine;
+ engine.setRunMode(Qt3DCore::QAspectEngine::Manual);
auto aspect = new TestAspect;
engine.registerAspect(aspect);
@@ -1253,6 +1276,7 @@ void tst_Nodes::checkAllBackendCreationDoneInSingleFrame()
// WHEN
QCoreApplication::processEvents();
+ engine.processFrame();
// THEN - both children have their backend nodes actually created.
QCOMPARE(aspect->events.count(), 2);
@@ -1544,20 +1568,8 @@ void tst_Nodes::checkConstructionAsListElement()
QCoreApplication::processEvents();
QCOMPARE(root->children().count(), 1);
- QCOMPARE(spy.events.size(), 2); // 1 child added change, 1 property change
-
- const auto newChildEvent = spy.events.takeFirst().change().dynamicCast<Qt3DCore::QPropertyNodeAddedChange>();
- QVERIFY(!newChildEvent.isNull());
- QCOMPARE(newChildEvent->subjectId(), root->id());
- QCOMPARE(newChildEvent->propertyName(), "children");
- QCOMPARE(newChildEvent->addedNodeId(), node->id());
-
- // Ensure second and last event is property set change
- const auto propertyEvent = spy.events.takeFirst().change().dynamicCast<Qt3DCore::QPropertyNodeAddedChange>();
- QVERIFY(!propertyEvent.isNull());
- QCOMPARE(propertyEvent->subjectId(), root->id());
- QCOMPARE(propertyEvent->propertyName(), "attribute");
- QCOMPARE(newChildEvent->addedNodeId(), node->id());
+ QCOMPARE(spy.dirtyNodes.size(), 1); // 1 property change
+ QCOMPARE(spy.dirtySubNodes.size(), 1); // 1 child added change
}
void tst_Nodes::checkSceneIsSetOnConstructionWithParent()
@@ -1606,6 +1618,52 @@ void tst_Nodes::checkSceneIsSetOnConstructionWithParent()
QCOMPARE(spy.dirtySubNodes.size(), 5); // 5 entities changed
}
+void tst_Nodes::checkSubNodePostConstructIsCalledWhenReferincingNodeProperty()
+{
+ // GIVEN
+ ObserverSpy spy;
+ Qt3DCore::QAspectEngine engine;
+ Qt3DCore::QScene scene(&engine);
+ QScopedPointer<MyQNode> root(new MyQNode());
+
+ // WHEN
+ root->setArbiterAndScene(&spy, &scene);
+ root->setSimulateBackendCreated(true);
+
+ // THEN
+ QVERIFY(Qt3DCore::QNodePrivate::get(root.data())->scene() != nullptr);
+
+ // WHEN
+ Qt3DCore::QEntity *subTreeRoot = new Qt3DCore::QEntity(root.data());
+ QCoreApplication::processEvents();
+
+ // THEN
+ QVERIFY(Qt3DCore::QNodePrivate::get(subTreeRoot)->m_hasBackendNode);
+
+ // WHEN
+ MyFakeMaterial *material = new MyFakeMaterial(subTreeRoot);
+ subTreeRoot->addComponent(material);
+
+ // THEN
+ QVERIFY(Qt3DCore::QNodePrivate::get(material)->m_hasBackendNode);
+ QVERIFY(Qt3DCore::QNodePrivate::get(material->m_effect)->m_hasBackendNode);
+ QVERIFY(Qt3DCore::QNodePrivate::get(material->m_technique)->m_hasBackendNode);
+ QVERIFY(Qt3DCore::QNodePrivate::get(material->m_renderPass)->m_hasBackendNode);
+
+ // WHEN
+ MyQNode *fakeRenderState = new MyQNode(material);
+ Qt3DCore::QNodePrivate *dPtr = Qt3DCore::QNodePrivate::get(fakeRenderState);
+
+ // THEN
+ QVERIFY(!dPtr->m_hasBackendNode);
+
+ // WHEN
+ material->m_renderPass->addAttribute(fakeRenderState);
+
+ // THEN
+ QVERIFY(dPtr->m_hasBackendNode);
+}
+
void tst_Nodes::appendingParentlessComponentToEntityWithoutScene()
{
// GIVEN
diff --git a/tests/auto/core/qaspectengine/tst_qaspectengine.cpp b/tests/auto/core/qaspectengine/tst_qaspectengine.cpp
index eb20536e6..48443a66f 100644
--- a/tests/auto/core/qaspectengine/tst_qaspectengine.cpp
+++ b/tests/auto/core/qaspectengine/tst_qaspectengine.cpp
@@ -146,6 +146,10 @@ private Q_SLOTS:
void shouldNotCrashInNormalStartupShutdownSequence()
{
+#ifdef Q_OS_MACOS
+ QSKIP("Test frequently times out. See QTBUG-80660.");
+#endif
+
// GIVEN
// An initialized aspect engine...
QAspectEngine engine;
@@ -168,7 +172,7 @@ private Q_SLOTS:
engine.setRootEntity(entity);
QEventLoop eventLoop;
- QTimer::singleShot(100, &eventLoop, SLOT(quit()));
+ QTimer::singleShot(1000, &eventLoop, SLOT(quit()));
eventLoop.exec();
// THEN
@@ -179,7 +183,7 @@ private Q_SLOTS:
// WHEN
// we set an empty/null scene root...
engine.setRootEntity(QEntityPtr());
- QTimer::singleShot(1000, &eventLoop, SLOT(quit()));
+ QTimer::singleShot(600, &eventLoop, SLOT(quit()));
// ...and allow events to process...
eventLoop.exec();
@@ -243,21 +247,21 @@ private Q_SLOTS:
// THEN
QCOMPARE(engine.executeCommand("list aspects").toString(),
- QString("Loaded aspects:\n * fake"));
+ QString("fake"));
// WHEN
engine.registerAspect("otherfake");
// THEN
QCOMPARE(engine.executeCommand("list aspects").toString(),
- QString("Loaded aspects:\n * fake\n * otherfake"));
+ QString("fake\notherfake"));
// WHEN
engine.registerAspect(new FakeAspect3);
// THEN
QCOMPARE(engine.executeCommand("list aspects").toString(),
- QString("Loaded aspects:\n * fake\n * otherfake\n * <unnamed>"));
+ QString("fake\notherfake\n<unnamed>"));
}
void shouldDelegateCommandsToAspects()
diff --git a/tests/auto/core/qchangearbiter/tst_qchangearbiter.cpp b/tests/auto/core/qchangearbiter/tst_qchangearbiter.cpp
index e54193398..3e9b24408 100644
--- a/tests/auto/core/qchangearbiter/tst_qchangearbiter.cpp
+++ b/tests/auto/core/qchangearbiter/tst_qchangearbiter.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DCore/private/qobserverinterface_p.h>
#include <Qt3DCore/private/qobservableinterface_p.h>
diff --git a/tests/auto/core/qentity/tst_qentity.cpp b/tests/auto/core/qentity/tst_qentity.cpp
index 7770a2632..7b41c9783 100644
--- a/tests/auto/core/qentity/tst_qentity.cpp
+++ b/tests/auto/core/qentity/tst_qentity.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QtTest>
#include <Qt3DCore/qentity.h>
#include <Qt3DCore/private/qentity_p.h>
diff --git a/tests/auto/core/qpostman/tst_qpostman.cpp b/tests/auto/core/qpostman/tst_qpostman.cpp
index f548d38fa..d0dfa0f49 100644
--- a/tests/auto/core/qpostman/tst_qpostman.cpp
+++ b/tests/auto/core/qpostman/tst_qpostman.cpp
@@ -86,227 +86,6 @@ private Q_SLOTS:
QCOMPARE(QPostmanPrivate::get(&postman)->m_scene, &scene);
}
- void checkSceneChangeEvent()
- {
- // GIVEN
- QScopedPointer<QScene> scene(new QScene);
- QPostman postman;
- TestArbiter arbiter;
- QNode rootNode;
- NodeChangeReceiver *receiverNode = new NodeChangeReceiver();
-
- QNodePrivate::get(&rootNode)->m_scene = scene.data();
- scene->setArbiter(&arbiter);
- postman.setScene(scene.data());
- // Setting the parent (which has a scene) adds the node into the observable lookup
- // table of the scene which is needed by the postman to distribute changes
- static_cast<QNode *>(receiverNode)->setParent(&rootNode);
- QCoreApplication::processEvents();
-
- // THEN
- QCOMPARE(receiverNode->hasReceivedChange(), false);
- QCOMPARE(QNodePrivate::get(receiverNode)->m_scene, scene.data());
-
- // WHEN
- QPropertyUpdatedChangePtr updateChange(new QPropertyUpdatedChange(receiverNode->id()));
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
- postman.sceneChangeEvent(updateChange);
- QCoreApplication::processEvents();
-
- // THEN
- QCOMPARE(receiverNode->hasReceivedChange(), true);
- }
-
- void checkNotifyBackend()
- {
- // GIVEN
- QScopedPointer<QScene> scene(new QScene);
- QPostman postman;
- TestArbiter arbiter;
-
- scene->setArbiter(&arbiter);
- postman.setScene(scene.data());
-
- // THEN
- QCOMPARE(arbiter.events.size(), 0);
-
- // WHEN
- QPropertyUpdatedChangePtr updateChange(new QPropertyUpdatedChange(QNodeId()));
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
- postman.notifyBackend(updateChange);
-
- QCoreApplication::processEvents();
-
- // THEN
- QCOMPARE(arbiter.events.size(), 1);
- }
-
- void checkShouldNotifyFrontend()
- {
- // GIVEN
- QScopedPointer<QScene> scene(new QScene);
- QPostman postman;
- TestArbiter arbiter;
- QNode rootNode;
- NodeChangeReceiver *receiverNode = new NodeChangeReceiver();
-
- QNodePrivate::get(&rootNode)->m_scene = scene.data();
- scene->setArbiter(&arbiter);
- postman.setScene(scene.data());
- // Setting the parent (which has a scene) adds the node into the observable lookup
- // table of the scene which is needed by the postman to distribute changes
- static_cast<QNode *>(receiverNode)->setParent(&rootNode);
- QCoreApplication::processEvents();
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
-
-
- // THEN -> we do track properties by default QNode::DefaultTrackMode
- // (unless marked as an intermediate change)
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
-
- {
- // WHEN
- receiverNode->setDefaultPropertyTrackingMode(QNode::TrackAllValues);
-
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
- QPropertyUpdatedChangeBasePrivate::get(updateChange.data())->m_isIntermediate
- = true;
-
- // THEN -> we do track properties marked as intermediate when
- // using TrackAllPropertiesMode
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
-
- {
- // GIVEN
- receiverNode->setDefaultPropertyTrackingMode(QNode::DontTrackValues);
- receiverNode->setPropertyTracking(QStringLiteral("vette"), Qt3DCore::QNode::TrackAllValues);
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
- QPropertyUpdatedChangeBasePrivate::get(updateChange.data())->m_isIntermediate
- = true;
-
- // THEN -> we don't track properties by default, unless named when
- // using TrackNamedPropertiesMode
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), false);
- }
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("vette");
- QPropertyUpdatedChangeBasePrivate::get(updateChange.data())->m_isIntermediate
- = true;
-
- // THEN
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
- }
-
- {
- // GIVEN
- receiverNode->setPropertyTracking(QStringLiteral("vette"), Qt3DCore::QNode::TrackAllValues);
- receiverNode->setDefaultPropertyTrackingMode(QNode::TrackAllValues);
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
-
- // THEN -> we don't track properties by default
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("vette");
-
- // THEN -> we don't track properties by default
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
- }
-
- {
- // GIVEN
- receiverNode->clearPropertyTrackings();
- receiverNode->setDefaultPropertyTrackingMode(QNode::TrackFinalValues);
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
-
- // THEN -> we do track properties by default, unless marked as intermediate
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
-
- {
- // WHEN
- auto addedChange
- = QPropertyNodeAddedChangePtr::create(receiverNode->id(), receiverNode);
-
- // THEN -> only QPropertyUpdatedChangePtr are filtered
- QCOMPARE(postman.shouldNotifyFrontend(addedChange), true);
- }
- {
- // WHEN
- auto removedChange
- = QPropertyNodeRemovedChangePtr::create(receiverNode->id(), receiverNode);
-
- // THEN -> only QPropertyUpdatedChangePtr are filtered
- QCOMPARE(postman.shouldNotifyFrontend(removedChange), true);
- }
- }
-
- {
- // GIVEN
- receiverNode->clearPropertyTrackings();
- receiverNode->setDefaultPropertyTrackingMode(QNode::TrackFinalValues);
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
- QPropertyUpdatedChangeBasePrivate::get(updateChange.data())->m_isIntermediate
- = true;
-
- // THEN -> we don't track intermediate properties by default
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), false);
- }
-
- {
- // WHEN
- auto updateChange = QPropertyUpdatedChangePtr::create(receiverNode->id());
- updateChange->setValue(1584);
- updateChange->setPropertyName("someName");
-
- // THEN
- QCOMPARE(postman.shouldNotifyFrontend(updateChange), true);
- }
-
- }
- }
-
};
QTEST_MAIN(tst_QPostman)
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<tst_ArrayResource, uint> 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);
+}
+
diff --git a/tests/auto/core/qscene/tst_qscene.cpp b/tests/auto/core/qscene/tst_qscene.cpp
index ecc72e992..eb6a8c5ec 100644
--- a/tests/auto/core/qscene/tst_qscene.cpp
+++ b/tests/auto/core/qscene/tst_qscene.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QtTest>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/qnode.h>
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 <QtTest/QtTest>
+#include <Qt3DCore/qaspectjob.h>
+#include <Qt3DCore/qabstractaspect.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DCore/private/qscheduler_p.h>
+#include <private/qabstractaspect_p.h>
+#include <private/qaspectjob_p.h>
+
+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<Job>;
+
+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<QAspectJobPtr> 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<AspectPrivate *>(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"
diff --git a/tests/auto/core/qservicelocator/tst_qservicelocator.cpp b/tests/auto/core/qservicelocator/tst_qservicelocator.cpp
index cde9834b4..40f0610df 100644
--- a/tests/auto/core/qservicelocator/tst_qservicelocator.cpp
+++ b/tests/auto/core/qservicelocator/tst_qservicelocator.cpp
@@ -52,11 +52,8 @@ class DummySystemInfoService : public QSystemInformationService
{
public:
DummySystemInfoService()
- : QSystemInformationService(QStringLiteral("Dummy System Information Service"))
+ : QSystemInformationService(nullptr, QStringLiteral("Dummy System Information Service"))
{}
-
- QStringList aspectNames() const final { return QStringList(); }
- int threadPoolThreadCount() const final { return 4; }
};
@@ -90,8 +87,8 @@ void tst_QServiceLocator::defaultServices()
QSystemInformationService *sysInfo = locator.systemInformation();
QVERIFY(sysInfo != nullptr);
- QVERIFY(sysInfo->description() == QStringLiteral("Null System Information Service"));
- QVERIFY(sysInfo->threadPoolThreadCount() == 0);
+ QVERIFY(sysInfo->description() == QStringLiteral("Default System Information Service"));
+ QVERIFY(sysInfo->threadPoolThreadCount() != 0);
}
void tst_QServiceLocator::addRemoveDefaultService()
@@ -105,7 +102,6 @@ void tst_QServiceLocator::addRemoveDefaultService()
// Get the service from the locator and check it works as expected
QSystemInformationService *service = locator.systemInformation();
QVERIFY(service == dummy.data());
- QVERIFY(service->threadPoolThreadCount() == 4);
// Ensure the other default services work
QOpenGLInformationService *glInfo = locator.openGLInformation();
@@ -118,7 +114,7 @@ void tst_QServiceLocator::addRemoveDefaultService()
QVERIFY(locator.serviceCount() == QServiceLocator::DefaultServiceCount);
// Check the dummy service still exists
- QVERIFY(dummy->threadPoolThreadCount() == 4);
+ QVERIFY(!dummy.isNull());
}
void tst_QServiceLocator::addRemoveUserService()
@@ -138,8 +134,8 @@ void tst_QServiceLocator::addRemoveUserService()
// Ensure the default services work
QSystemInformationService *sysInfo = locator.systemInformation();
QVERIFY(sysInfo != nullptr);
- QVERIFY(sysInfo->description() == QStringLiteral("Null System Information Service"));
- QVERIFY(sysInfo->threadPoolThreadCount() == 0);
+ QVERIFY(sysInfo->description() == QStringLiteral("Default System Information Service"));
+ QVERIFY(sysInfo->threadPoolThreadCount() != 0);
// Remove custom service
locator.unregisterServiceProvider(dummy->type());
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 <Qt3DCore/qskeleton.h>
#include <Qt3DCore/private/qskeleton_p.h>
#include <Qt3DCore/qjoint.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
@@ -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/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<Qt3DCore::QSkeletonLoader::Status>("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<Qt3DCore::QJoint*>();
- TestArbiter arbiter;
- arbiter.setArbiterOnNode(this);
- QSignalSpy spy(this, SIGNAL(rootJointChanged(Qt3DCore::QJoint*)));
- std::unique_ptr<QJoint> 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/core/qtransform/tst_qtransform.cpp b/tests/auto/core/qtransform/tst_qtransform.cpp
index 37848ffd6..18a906e4c 100644
--- a/tests/auto/core/qtransform/tst_qtransform.cpp
+++ b/tests/auto/core/qtransform/tst_qtransform.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QtTest>
#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qtransform.h>
diff --git a/tests/auto/core/threadpooler/tst_threadpooler.cpp b/tests/auto/core/threadpooler/tst_threadpooler.cpp
index cfe3480ee..289f0b103 100644
--- a/tests/auto/core/threadpooler/tst_threadpooler.cpp
+++ b/tests/auto/core/threadpooler/tst_threadpooler.cpp
@@ -182,7 +182,7 @@ void massTestFunction(QVector3D *data)
void tst_ThreadPooler::initTestCase()
{
- m_jobManager = new JobManager(this);
+ m_jobManager = new JobManager(nullptr);
}
void tst_ThreadPooler::cleanupTestCase()
diff --git a/tests/auto/coretest/qbackendnodetester.cpp b/tests/auto/coretest/qbackendnodetester.cpp
index be9767828..bd5fb85d1 100644
--- a/tests/auto/coretest/qbackendnodetester.cpp
+++ b/tests/auto/coretest/qbackendnodetester.cpp
@@ -57,15 +57,21 @@ void QBackendNodeTester::simulateInitialization(QNode *frontend, QBackendNode *b
{
Q_ASSERT(frontend);
Q_ASSERT(backend);
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
const auto change = frontend->createNodeCreationChange();
backend->setPeerId(change->subjectId());
backend->setEnabled(change->isNodeEnabled());
backend->initializeFromPeer(change);
+ QT_WARNING_POP
}
void QBackendNodeTester::sceneChangeEvent(QBackendNode *backend, const Qt3DCore::QSceneChangePtr &e)
{
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
backend->sceneChangeEvent(e);
+ QT_WARNING_POP
}
} // namespace Qt3DCore
diff --git a/tests/auto/coretest/testpostmanarbiter.cpp b/tests/auto/coretest/testpostmanarbiter.cpp
index d1263b8f7..d2e404809 100644
--- a/tests/auto/coretest/testpostmanarbiter.cpp
+++ b/tests/auto/coretest/testpostmanarbiter.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include "testpostmanarbiter_p.h"
#include <Qt3DCore/private/qnode_p.h>
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<Qt3DRender::QBufferDataGeneratorPtr, Qt3DRender::QBuffer *> 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/global/aspects_startup_shutdown/tst_aspects_startup_shutdown.cpp b/tests/auto/global/aspects_startup_shutdown/tst_aspects_startup_shutdown.cpp
index 9eec010be..00e4890c8 100644
--- a/tests/auto/global/aspects_startup_shutdown/tst_aspects_startup_shutdown.cpp
+++ b/tests/auto/global/aspects_startup_shutdown/tst_aspects_startup_shutdown.cpp
@@ -143,6 +143,8 @@ private slots:
void checkStartupAndShutdownImmediately()
{
+ QSKIP("Fails on CI for some unexplained reason");
+
// GIVEN
QWindow *win = new QWindow();
win->setSurfaceType(QSurface::OpenGLSurface);
@@ -170,6 +172,8 @@ private slots:
void checkStartupAndShutdownAfterAFewFrames()
{
+ QSKIP("Fails on CI for some unexplained reason");
+
// GIVEN
QWindow *win = new QWindow();
win->setSurfaceType(QSurface::OpenGLSurface);
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 <qbackendnodetester.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DInput/private/abstractaxisinput_p.h>
#include <Qt3DInput/QAbstractAxisInput>
#include <Qt3DInput/private/qabstractaxisinput_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#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 <qbackendnodetester.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qpropertynodeaddedchange.h>
#include <Qt3DCore/qpropertynoderemovedchange.h>
#include <Qt3DInput/private/action_p.h>
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 <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DInput/private/analogaxisinput_p.h>
#include <Qt3DInput/private/inputhandler_p.h>
#include <Qt3DInput/QAnalogAxisInput>
-#include <Qt3DCore/qpropertyupdatedchange.h>
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 <qbackendnodetester.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/qpropertynodeaddedchange.h>
#include <Qt3DCore/qpropertynoderemovedchange.h>
#include <Qt3DInput/private/axis_p.h>
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 <QtTest/QTest>
#include <qbackendnodetester.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DInput/private/axis_p.h>
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 <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DInput/private/buttonaxisinput_p.h>
#include <Qt3DInput/private/inputhandler_p.h>
#include <Qt3DInput/QButtonAxisInput>
-#include <Qt3DCore/qpropertyupdatedchange.h>
class tst_ButtonAxisInput: public Qt3DCore::QBackendNodeTester
{
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/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 <Qt3DInput/private/inputhandler_p.h>
#include <Qt3DInput/private/physicaldeviceproxy_p.h>
#include <Qt3DInput/private/qinputdeviceintegration_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
#include "qbackendnodetester.h"
#include "testdeviceproxy.h"
diff --git a/tests/auto/input/mousedevice/tst_mousedevice.cpp b/tests/auto/input/mousedevice/tst_mousedevice.cpp
index 41ecd68c7..cad1ab951 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)>() << 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)>() << 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)>() << 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)>() << 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()
@@ -249,6 +305,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/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 <Qt3DInput/private/qabstractphysicaldeviceproxy_p_p.h>
#include <Qt3DInput/private/physicaldeviceproxy_p.h>
#include <Qt3DInput/private/inputmanagers_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
-#include <Qt3DCore/private/qpropertyupdatedchangebase_p.h>
#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 <QtTest/QTest>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
#include <Qt3DCore/qnodecreatedchange.h>
#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 <QtTest/QTest>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
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 <QtTest/QTest>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
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 <QtTest/QTest>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qnodecreatedchangegenerator_p.h>
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)
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 <QtTest/QTest>
+#include <Qt3DInput/qmouseevent.h>
+#include <QtGui/QMouseEvent>
+#include <QObject>
+#include <QSignalSpy>
+
+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"
diff --git a/tests/auto/render/buffer/tst_buffer.cpp b/tests/auto/render/buffer/tst_buffer.cpp
index 48215bea5..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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <qbackendnodetester.h>
#include <Qt3DRender/private/buffer_p.h>
@@ -157,6 +161,61 @@ private Q_SLOTS:
QVERIFY(backendBuffer.pendingBufferUpdates().empty());
}
+
+ void checkForceFullUploadOnFirstTime()
+ {
+ // GIVEN
+ Qt3DRender::Render::Buffer backendBuffer;
+ Qt3DRender::Render::BufferManager bufferManager;
+ TestRenderer renderer;
+ Qt3DRender::QBuffer frontendBuffer;
+
+ QByteArray data("111456789\0");
+
+ frontendBuffer.setData(data);
+ frontendBuffer.updateData(1, QByteArray("23\0"));
+
+ // THEN
+ QCOMPARE(frontendBuffer.data(), QByteArray("123456789\0"));
+
+ // WHEN
+ backendBuffer.setManager(&bufferManager);
+ backendBuffer.setRenderer(&renderer);
+ simulateInitializationSync(&frontendBuffer, &backendBuffer);
+
+ // THEN
+ QCOMPARE(backendBuffer.pendingBufferUpdates().size(), 1);
+ Qt3DRender::QBufferUpdate fullUpdate = backendBuffer.pendingBufferUpdates().first();
+ QCOMPARE(fullUpdate.offset, -1);
+ QVERIFY(fullUpdate.data.isEmpty());
+ QCOMPARE(frontendBuffer.data(), backendBuffer.data());
+
+ backendBuffer.pendingBufferUpdates().clear();
+
+ // WHEN
+ frontendBuffer.updateData(1, QByteArray("00\0"));
+ backendBuffer.syncFromFrontEnd(&frontendBuffer, false);
+
+ // THEN
+ QCOMPARE(frontendBuffer.data(), QByteArray("100456789\0"));
+ QCOMPARE(backendBuffer.pendingBufferUpdates().size(), 1);
+ fullUpdate = backendBuffer.pendingBufferUpdates().first();
+ QCOMPARE(fullUpdate.offset, 1);
+ QCOMPARE(fullUpdate.data, QByteArray("00\0"));
+ QCOMPARE(frontendBuffer.data(), backendBuffer.data());
+
+ // WHEN
+ frontendBuffer.updateData(1, QByteArray("22\0"));
+ backendBuffer.syncFromFrontEnd(&frontendBuffer, true);
+
+ // THEN
+ QCOMPARE(frontendBuffer.data(), QByteArray("122456789\0"));
+ fullUpdate = backendBuffer.pendingBufferUpdates().first();
+ QCOMPARE(fullUpdate.offset, -1);
+ QVERIFY(fullUpdate.data.isEmpty());
+ QCOMPARE(frontendBuffer.data(), backendBuffer.data());
+ }
+
void checkPropertyChanges()
{
// GIVEN
@@ -237,10 +296,7 @@ private Q_SLOTS:
backendBuffer.executeFunctor();
// THEN
- QCOMPARE(arbiter.events.count(), 1);
- Qt3DCore::QPropertyUpdatedChangePtr change = arbiter.events.first().staticCast<Qt3DCore::QPropertyUpdatedChange>();
- 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);
diff --git a/tests/auto/render/commons/testrenderer.cpp b/tests/auto/render/commons/testrenderer.cpp
index 0f5cdc7c9..6b6e2326e 100644
--- a/tests/auto/render/commons/testrenderer.cpp
+++ b/tests/auto/render/commons/testrenderer.cpp
@@ -30,10 +30,7 @@
QT_BEGIN_NAMESPACE
-TestRenderer::TestRenderer()
- : m_managers(nullptr)
-{
-}
+TestRenderer::TestRenderer() = default;
TestRenderer::~TestRenderer()
{
diff --git a/tests/auto/render/commons/testrenderer.h b/tests/auto/render/commons/testrenderer.h
index 8d27998a0..7b3e0a387 100644
--- a/tests/auto/render/commons/testrenderer.h
+++ b/tests/auto/render/commons/testrenderer.h
@@ -30,6 +30,7 @@
#define TESTRENDERER_H
#include <Qt3DRender/private/abstractrenderer_p.h>
+#include <Qt3DRender/private/resourceaccessor_p.h>
QT_BEGIN_NAMESPACE
@@ -43,32 +44,38 @@ public:
API api() const override { return AbstractRenderer::OpenGL; }
qint64 time() const override { return 0; }
void setTime(qint64 time) override { Q_UNUSED(time); }
- void setNodeManagers(Qt3DRender::Render::NodeManagers *m) override { m_managers = m; }
+ 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) }
Qt3DRender::Render::NodeManagers *nodeManagers() const override { return m_managers; }
Qt3DCore::QServiceLocator *services() const override { return nullptr; }
void initialize() override {}
void shutdown() override {}
void releaseGraphicsResources() override {}
void render() override {}
- void doRender(bool swapBuffers) override { Q_UNUSED(swapBuffers); }
+ void doRender(bool swapBuffers) override { Q_UNUSED(swapBuffers) }
void cleanGraphicsResources() override {}
bool isRunning() const override { return true; }
- bool shouldRender() override { return true; }
+ bool shouldRender() const override { return true; }
void skipNextFrame() override {}
+ void jobsDone(Qt3DCore::QAspectManager *manager) override { Q_UNUSED(manager) }
QVector<Qt3DCore::QAspectJobPtr> preRenderingJobs() override { return QVector<Qt3DCore::QAspectJobPtr>(); }
QVector<Qt3DCore::QAspectJobPtr> renderBinJobs() override { return QVector<Qt3DCore::QAspectJobPtr>(); }
Qt3DCore::QAspectJobPtr pickBoundingVolumeJob() override { return Qt3DCore::QAspectJobPtr(); }
Qt3DCore::QAspectJobPtr rayCastingJob() override { return Qt3DCore::QAspectJobPtr(); }
Qt3DCore::QAspectJobPtr syncLoadingJobs() override { return Qt3DCore::QAspectJobPtr(); }
Qt3DCore::QAspectJobPtr expandBoundingVolumeJob() override { return Qt3DCore::QAspectJobPtr(); }
- void setSceneRoot(Qt3DRender::Render::Entity *root) override { Q_UNUSED(root); }
+ void setSceneRoot(Qt3DRender::Render::Entity *root) override { Q_UNUSED(root) }
Qt3DRender::Render::Entity *sceneRoot() const override { return nullptr; }
Qt3DRender::Render::FrameGraphNode *frameGraphRoot() const override { return nullptr; }
Qt3DCore::QAbstractFrameAdvanceService *frameAdvanceService() const override { return nullptr; }
- void registerEventFilter(Qt3DCore::QEventFilterService *service) override { Q_UNUSED(service); }
- void setSettings(Qt3DRender::Render::RenderSettings *settings) override { Q_UNUSED(settings); }
+ void registerEventFilter(Qt3DCore::QEventFilterService *service) override { Q_UNUSED(service) }
+ void setSettings(Qt3DRender::Render::RenderSettings *settings) override { Q_UNUSED(settings) }
Qt3DRender::Render::RenderSettings *settings() const override { return nullptr; }
void markDirty(Qt3DRender::Render::AbstractRenderer::BackendNodeDirtySet changes, Qt3DRender::Render::BackendNode *node) override;
@@ -85,12 +92,15 @@ public:
QSurfaceFormat format() override;
void setOpenGLContext(QOpenGLContext *) override {}
+ bool accessOpenGLTexture(Qt3DCore::QNodeId, QOpenGLTexture **, QMutex **, bool) override { return false; }
+ QSharedPointer<Qt3DRender::Render::RenderBackendResourceAccessor> 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;
+ Qt3DRender::Render::NodeManagers *m_managers = nullptr;
+ QSharedPointer<Qt3DRender::Render::ResourceAccessor> m_resourceAccessor;
};
QT_END_NAMESPACE
diff --git a/tests/auto/render/computecommand/tst_computecommand.cpp b/tests/auto/render/computecommand/tst_computecommand.cpp
index 990c0cd98..d6fa1d579 100644
--- a/tests/auto/render/computecommand/tst_computecommand.cpp
+++ b/tests/auto/render/computecommand/tst_computecommand.cpp
@@ -31,12 +31,17 @@
#include <Qt3DRender/qcomputecommand.h>
#include <Qt3DRender/private/qcomputecommand_p.h>
#include <Qt3DRender/private/computecommand_p.h>
+#include <Qt3DRender/private/nodemanagers_p.h>
+#include <Qt3DRender/private/managers_p.h>
#include <Qt3DCore/private/qbackendnode_p.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/qpropertyupdatedchange.h>
#include "qbackendnodetester.h"
#include "testrenderer.h"
#include "testpostmanarbiter.h"
+
class tst_ComputeCommand : public Qt3DCore::QBackendNodeTester
{
Q_OBJECT
@@ -54,6 +59,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 +67,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 +225,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 +233,28 @@ private Q_SLOTS:
backendComputeCommand.updateFrameCount();
// THEN
- QCOMPARE(backendComputeCommand.frameCount(), false);
+ 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
+
+ // WHEN
+ computeCommand.setEnabled(false);
+ backendComputeCommand.syncFromFrontEnd(&computeCommand, false);
+
+ // THEN
QCOMPARE(backendComputeCommand.isEnabled(), false);
- QCOMPARE(arbiter.events.size(), 1);
- {
- auto change = arbiter.events.first().staticCast<Qt3DCore::QPropertyUpdatedChange>();
- QCOMPARE(change->propertyName(), "enabled");
- QCOMPARE(change->value().value<int>(), false);
- QCOMPARE(change->type(), Qt3DCore::PropertyUpdated);
- }
+ 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);
}
};
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DRender/qtextureimagedata.h>
#include <Qt3DRender/private/qtexture_p.h>
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 <Qt3DRender/qparameter.h>
#include <Qt3DRender/private/qeffect_p.h>
#include <Qt3DRender/private/effect_p.h>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
#include "qbackendnodetester.h"
#include "testrenderer.h"
diff --git a/tests/auto/render/entity/tst_entity.cpp b/tests/auto/render/entity/tst_entity.cpp
index e3b8e756e..a762330dd 100644
--- a/tests/auto/render/entity/tst_entity.cpp
+++ b/tests/auto/render/entity/tst_entity.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QtTest>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/entity_p_p.h>
@@ -35,7 +39,6 @@
#include <Qt3DRender/private/entityaccumulator_p.h>
#include <Qt3DRender/QCameraLens>
-#include <Qt3DCore/QPropertyNodeAddedChange>
#include <Qt3DCore/QTransform>
#include <Qt3DRender/QEnvironmentLight>
@@ -123,11 +126,13 @@ 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<Transform>().isNull());
QVERIFY(entity.componentUuid<CameraLens>().isNull());
QVERIFY(entity.componentUuid<Material>().isNull());
@@ -141,20 +146,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<Transform>().isNull());
@@ -170,7 +171,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<Transform,
CameraLens, Material, GeometryRenderer, ObjectPicker, ComputeCommand, Armature>();
QVERIFY(containsAll);
@@ -195,6 +196,9 @@ private slots:
containsAll = entity.containsComponentsOfType<Transform,
CameraLens, Material, GeometryRenderer, ObjectPicker, ComputeCommand, Armature>();
QVERIFY(!containsAll);
+
+ QVERIFY(renderer.dirtyBits() & Qt3DRender::Render::AbstractRenderer::AllDirty);
+ renderer.resetDirty();
}
void checkEntityReparenting()
@@ -217,6 +221,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 +245,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 +261,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<Qt3DCore::QNode *>(nullptr));
sendParentChange(frontendEntityB);
@@ -264,6 +277,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 +314,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 +331,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 +346,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 +360,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/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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <qbackendnodetester.h>
#include <Qt3DRender/private/geometry_p.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <qbackendnodetester.h>
#include <Qt3DRender/private/geometryrenderer_p.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DRender/private/gltexture_p.h>
#include <Qt3DRender/qabstracttexture.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DRender/qtextureimagedata.h>
#include <Qt3DRender/private/qtexture_p.h>
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 <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/filterlayerentityjob_p.h>
+#include <Qt3DRender/private/updateentitylayersjob_p.h>
#include <Qt3DRender/private/updatetreeenabledjob_p.h>
#include <Qt3DRender/qlayer.h>
#include <Qt3DRender/qlayerfilter.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QtTest>
#include <Qt3DCore/qcomponent.h>
#include <Qt3DRender/qgeometryfactory.h>
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 <Qt3DRender/qpickevent.h>
#include <Qt3DRender/qobjectpicker.h>
#include <Qt3DCore/private/qbackendnode_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include "testpostmanarbiter.h"
#include "testrenderer.h"
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..3caf11c8f
--- /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 <QtTest/QTest>
+#include <Qt3DRender/qcomputecommand.h>
+#include <Qt3DRender/private/qcomputecommand_p.h>
+#include <Qt3DRender/private/computecommand_p.h>
+#include <Qt3DRender/private/nodemanagers_p.h>
+#include <Qt3DRender/private/managers_p.h>
+#include <Qt3DCore/private/qbackendnode_p.h>
+#include <Qt3DCore/private/qaspectmanager_p.h>
+#include <Qt3DCore/private/qscene_p.h>
+#include <Qt3DCore/qpropertyupdatedchange.h>
+#include <renderer_p.h>
+#include "qbackendnodetester.h"
+#include "testrenderer.h"
+#include "testpostmanarbiter.h"
+
+
+// tst_Renderer is a friend class of Renderer
+class tst_Renderer : public Qt3DRender::Render::OpenGL::Renderer
+{
+public:
+ tst_Renderer()
+ : Qt3DRender::Render::OpenGL::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/filtercompatibletechniquejob/BLACKLIST b/tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST
index 7cbc7c4c0..7cbc7c4c0 100644
--- a/tests/auto/render/filtercompatibletechniquejob/BLACKLIST
+++ b/tests/auto/render/opengl/filtercompatibletechniquejob/BLACKLIST
diff --git a/tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro b/tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro
index 4f63e514b..5d533839c 100644
--- a/tests/auto/render/filtercompatibletechniquejob/filtercompatibletechniquejob.pro
+++ b/tests/auto/render/opengl/filtercompatibletechniquejob/filtercompatibletechniquejob.pro
@@ -8,5 +8,8 @@ CONFIG += testcase
SOURCES += tst_filtercompatibletechniquejob.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp b/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp
index 25262a772..e5c34f804 100644
--- a/tests/auto/render/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp
+++ b/tests/auto/render/opengl/filtercompatibletechniquejob/tst_filtercompatibletechniquejob.cpp
@@ -35,12 +35,12 @@
#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qviewport.h>
#include <Qt3DRender/private/technique_p.h>
-#include <Qt3DRender/private/filtercompatibletechniquejob_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
-#include <Qt3DRender/private/renderer_p.h>
-#include <Qt3DRender/private/submissioncontext_p.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
#include <Qt3DRender/private/techniquemanager_p.h>
+#include <renderer_p.h>
+#include <submissioncontext_p.h>
+#include <filtercompatibletechniquejob_p.h>
QT_BEGIN_NAMESPACE
@@ -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();
@@ -91,7 +94,8 @@ public:
~TestAspect()
{
- QRenderAspect::onUnregistered();
+ if (m_contextCreationSuccessful)
+ QRenderAspect::onUnregistered();
}
Qt3DRender::Render::NodeManagers *nodeManagers() const
@@ -100,6 +104,11 @@ public:
? d_func()->m_renderer->nodeManagers() : nullptr;
}
+ bool contextCreationSuccessful() const
+ {
+ return m_contextCreationSuccessful;
+ }
+
void initializeRenderer()
{
renderer()->setOpenGLContext(&m_glContext);
@@ -107,9 +116,9 @@ public:
renderer()->submissionContext()->beginDrawing(m_window.data());
}
- Render::Renderer *renderer() const
+ Render::OpenGL::Renderer *renderer() const
{
- return static_cast<Render::Renderer *>(d_func()->m_renderer);
+ return static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer);
}
void onRegistered() { QRenderAspect::onRegistered(); }
@@ -119,6 +128,7 @@ private:
QScopedPointer<Qt3DCore::QAspectJobManager> m_jobManager;
QScopedPointer<QWindow> m_window;
QOpenGLContext m_glContext;
+ bool m_contextCreationSuccessful;
};
} // namespace Qt3DRender
@@ -186,7 +196,7 @@ private Q_SLOTS:
void checkInitialState()
{
// GIVEN
- Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob;
+ Qt3DRender::Render::OpenGL::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob;
// THEN
QVERIFY(backendFilterCompatibleTechniqueJob.manager() == nullptr);
@@ -194,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);
@@ -208,9 +218,14 @@ private Q_SLOTS:
void checkRunRendererRunning()
{
// GIVEN
- Qt3DRender::Render::FilterCompatibleTechniqueJob backendFilterCompatibleTechniqueJob;
+ Qt3DRender::Render::OpenGL::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);
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..6a5bc87ea
--- /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 <QtTest/QTest>
+#include <glresourcemanagers_p.h>
+#include <Qt3DCore/qnodeid.h>
+#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::OpenGL::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::OpenGL::GLShader *glShader1 = cache.createOrAdoptExisting(&backendShaderNode1);
+
+ // THEN
+ QVERIFY(glShader1 != nullptr);
+ QVector<Qt3DCore::QNodeId> shaderNodeIds = cache.shaderIdsForProgram(glShader1);
+ QCOMPARE(shaderNodeIds.size(), 1);
+ QCOMPARE(shaderNodeIds.first(), backendShaderNode1.peerId());
+
+ // WHEN
+ Qt3DRender::Render::OpenGL::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::OpenGL::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::OpenGL::GLShader *glShader1 = cache.lookupResource(backendShaderNode1.peerId());
+ Qt3DRender::Render::OpenGL::GLShader *glShader2 = cache.lookupResource(backendShaderNode2.peerId());
+ QVERIFY(glShader1 != nullptr);
+ QCOMPARE(glShader1, glShader2);
+ const QVector<Qt3DCore::QNodeId> 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::OpenGL::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::OpenGL::GLShader *glShader = cache.lookupResource(backendShaderNode1.peerId());
+ cache.abandon(glShader, &backendShaderNode1);
+
+ // THEN
+ QVector<Qt3DCore::QNodeId> 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<Qt3DRender::Render::OpenGL::GLShader *> releasedShaders = cache.takeAbandonned();
+ QCOMPARE(releasedShaders.size(), 1);
+ QCOMPARE(releasedShaders.first(), glShader);
+}
+
+void tst_GLShaderManager::insertAfterRemoval()
+{
+ // GIVEN
+ Qt3DRender::Render::OpenGL::GLShaderManager cache;
+ Qt3DRender::QShaderProgram frontendShader;
+ TestRenderer renderer;
+ Qt3DRender::Render::Shader backendShaderNode;
+
+
+ backendShaderNode.setRenderer(&renderer);
+ simulateInitialization(&frontendShader, &backendShaderNode);
+
+ // WHEN
+ Qt3DRender::Render::OpenGL::GLShader *apiShader1 = cache.createOrAdoptExisting(&backendShaderNode);
+ const Qt3DRender::Render::OpenGL::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::OpenGL::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/opengl/graphicshelpergl2/graphicshelpergl2.pro
index b27060635..eb8ba7f04 100644
--- a/tests/auto/render/graphicshelpergl2/graphicshelpergl2.pro
+++ b/tests/auto/render/opengl/graphicshelpergl2/graphicshelpergl2.pro
@@ -9,5 +9,8 @@ CONFIG += testcase
SOURCES += \
tst_graphicshelpergl2.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/graphicshelpergl2/tst_graphicshelpergl2.cpp b/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp
index ffafc2312..5a1d22283 100644
--- a/tests/auto/render/graphicshelpergl2/tst_graphicshelpergl2.cpp
+++ b/tests/auto/render/opengl/graphicshelpergl2/tst_graphicshelpergl2.cpp
@@ -29,7 +29,7 @@
#include <QtTest/QTest>
#include <Qt3DRender/qrendertargetoutput.h>
#include <Qt3DRender/private/uniform_p.h>
-#include <Qt3DRender/private/graphicshelpergl2_p.h>
+#include <graphicshelpergl2_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
#include <QtOpenGLExtensions/QOpenGLExtensions>
#include <QOpenGLContext>
@@ -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/graphicshelpergl3_2/graphicshelpergl3_2.pro b/tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro
index 5d8bf60fd..a613f1279 100644
--- a/tests/auto/render/graphicshelpergl3_2/graphicshelpergl3_2.pro
+++ b/tests/auto/render/opengl/graphicshelpergl3_2/graphicshelpergl3_2.pro
@@ -9,5 +9,8 @@ CONFIG += testcase
SOURCES += \
tst_graphicshelpergl3_2.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp b/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp
index 840a7f6da..08c30dc15 100644
--- a/tests/auto/render/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp
+++ b/tests/auto/render/opengl/graphicshelpergl3_2/tst_graphicshelpergl3_2.cpp
@@ -29,7 +29,7 @@
#include <QtTest/QTest>
#include <Qt3DRender/qrendertargetoutput.h>
#include <Qt3DRender/private/uniform_p.h>
-#include <Qt3DRender/private/graphicshelpergl3_2_p.h>
+#include <graphicshelpergl3_2_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
#include <QOpenGLBuffer>
#include <QOpenGLFunctions_3_2_Core>
@@ -43,6 +43,7 @@
using namespace Qt3DRender;
using namespace Qt3DRender::Render;
+using namespace Qt3DRender::Render::OpenGL;
namespace {
diff --git a/tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro b/tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro
index 36bda15b2..5ef0b6806 100644
--- a/tests/auto/render/graphicshelpergl3_3/graphicshelpergl3_3.pro
+++ b/tests/auto/render/opengl/graphicshelpergl3_3/graphicshelpergl3_3.pro
@@ -9,5 +9,8 @@ CONFIG += testcase
SOURCES += \
tst_graphicshelpergl3_3.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp b/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp
index 874c83f0b..b463e6236 100644
--- a/tests/auto/render/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp
+++ b/tests/auto/render/opengl/graphicshelpergl3_3/tst_graphicshelpergl3_3.cpp
@@ -29,8 +29,8 @@
#include <QtTest/QTest>
#include <Qt3DRender/qrendertargetoutput.h>
#include <Qt3DRender/private/uniform_p.h>
-#include <Qt3DRender/private/graphicshelpergl3_3_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
+#include <graphicshelpergl3_3_p.h>
#include <QOpenGLBuffer>
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLShaderProgram>
@@ -42,6 +42,7 @@
using namespace Qt3DRender;
using namespace Qt3DRender::Render;
+using namespace Qt3DRender::Render::OpenGL;
namespace {
diff --git a/tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro b/tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro
index b20d1afec..5ea881208 100644
--- a/tests/auto/render/graphicshelpergl4/graphicshelpergl4.pro
+++ b/tests/auto/render/opengl/graphicshelpergl4/graphicshelpergl4.pro
@@ -9,5 +9,8 @@ CONFIG += testcase
SOURCES += \
tst_graphicshelpergl4.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/graphicshelpergl4/tst_graphicshelpergl4.cpp b/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp
index 6e5c54303..8f86f38ce 100644
--- a/tests/auto/render/graphicshelpergl4/tst_graphicshelpergl4.cpp
+++ b/tests/auto/render/opengl/graphicshelpergl4/tst_graphicshelpergl4.cpp
@@ -29,8 +29,8 @@
#include <QtTest/QTest>
#include <Qt3DRender/qrendertargetoutput.h>
#include <Qt3DRender/private/uniform_p.h>
-#include <Qt3DRender/private/graphicshelpergl4_p.h>
#include <Qt3DRender/private/attachmentpack_p.h>
+#include <graphicshelpergl4_p.h>
#include <QOpenGLBuffer>
#include <QOpenGLFunctions_4_3_Core>
#include <QOpenGLShaderProgram>
@@ -43,6 +43,7 @@
using namespace Qt3DRender;
using namespace Qt3DRender::Render;
+using namespace Qt3DRender::Render::OpenGL;
namespace {
diff --git a/tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro b/tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro
index ac68b8248..106e7a263 100644
--- a/tests/auto/render/materialparametergathererjob/materialparametergathererjob.pro
+++ b/tests/auto/render/opengl/materialparametergathererjob/materialparametergathererjob.pro
@@ -8,4 +8,7 @@ CONFIG += testcase
SOURCES += tst_materialparametergathererjob.cpp
-include(../commons/commons.pri)
+include(../../commons/commons.pri)
+
+# Link Against OpenGL Renderer Plugin
+include(../opengl_render_plugin.pri)
diff --git a/tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp b/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp
index 236faa8f0..efd2c6603 100644
--- a/tests/auto/render/materialparametergathererjob/tst_materialparametergathererjob.cpp
+++ b/tests/auto/render/opengl/materialparametergathererjob/tst_materialparametergathererjob.cpp
@@ -36,16 +36,18 @@
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/entity_p.h>
-#include <Qt3DRender/private/materialparametergathererjob_p.h>
+#include <materialparametergathererjob_p.h>
#include <Qt3DRender/private/techniquefilternode_p.h>
#include <Qt3DRender/private/technique_p.h>
#include <Qt3DRender/private/techniquemanager_p.h>
#include <Qt3DRender/private/renderpassfilternode_p.h>
+#include <Qt3DRender/qrendersettings.h>
#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DRender/qeffect.h>
#include <Qt3DRender/qmaterial.h>
#include <Qt3DRender/qparameter.h>
#include <Qt3DRender/qtechniquefilter.h>
+#include <Qt3DRender/qtechnique.h>
#include <Qt3DRender/qrenderpassfilter.h>
#include <Qt3DRender/qrenderpass.h>
#include <Qt3DRender/qshaderprogram.h>
@@ -105,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;
}
@@ -230,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();
@@ -250,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();
@@ -272,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();
@@ -304,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();
@@ -344,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();
@@ -380,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();
@@ -414,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();
@@ -454,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();
@@ -507,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);
@@ -524,10 +526,10 @@ private Q_SLOTS:
// THEN -> RenderPassFilter wins
QCOMPARE(gatherer->materialToPassAndParameter().size(), 1);
- const QVector<Qt3DRender::Render::RenderPassParameterData> passParameterData = gatherer->materialToPassAndParameter().begin().value();
+ const QVector<Qt3DRender::Render::OpenGL::RenderPassParameterData> 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()));
@@ -563,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);
@@ -580,10 +582,10 @@ private Q_SLOTS:
// THEN -> TechniqueFilter wins
QCOMPARE(gatherer->materialToPassAndParameter().size(), 1);
- const QVector<Qt3DRender::Render::RenderPassParameterData> passParameterData = gatherer->materialToPassAndParameter().begin().value();
+ const QVector<Qt3DRender::Render::OpenGL::RenderPassParameterData> 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()));
@@ -618,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);
@@ -635,10 +637,10 @@ private Q_SLOTS:
// THEN -> TechniqueFilter wins
QCOMPARE(gatherer->materialToPassAndParameter().size(), 1);
- const QVector<Qt3DRender::Render::RenderPassParameterData> passParameterData = gatherer->materialToPassAndParameter().begin().value();
+ const QVector<Qt3DRender::Render::OpenGL::RenderPassParameterData> 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()));
@@ -672,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);
@@ -689,10 +691,10 @@ private Q_SLOTS:
// THEN -> TechniqueFilter wins
QCOMPARE(gatherer->materialToPassAndParameter().size(), 1);
- const QVector<Qt3DRender::Render::RenderPassParameterData> passParameterData = gatherer->materialToPassAndParameter().begin().value();
+ const QVector<Qt3DRender::Render::OpenGL::RenderPassParameterData> 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()));
@@ -722,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);
@@ -739,10 +741,10 @@ private Q_SLOTS:
// THEN -> TechniqueFilter wins
QCOMPARE(gatherer->materialToPassAndParameter().size(), 1);
- const QVector<Qt3DRender::Render::RenderPassParameterData> passParameterData = gatherer->materialToPassAndParameter().begin().value();
+ const QVector<Qt3DRender::Render::OpenGL::RenderPassParameterData> 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()));
@@ -766,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);
@@ -783,10 +785,10 @@ private Q_SLOTS:
// THEN -> TechniqueFilter wins
QCOMPARE(gatherer->materialToPassAndParameter().size(), 1);
- const QVector<Qt3DRender::Render::RenderPassParameterData> passParameterData = gatherer->materialToPassAndParameter().begin().value();
+ const QVector<Qt3DRender::Render::OpenGL::RenderPassParameterData> 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/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/qgraphicsutils/qgraphicsutils.pro b/tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro
index 031a26246..8c936c527 100644
--- a/tests/auto/render/qgraphicsutils/qgraphicsutils.pro
+++ b/tests/auto/render/opengl/qgraphicsutils/qgraphicsutils.pro
@@ -7,3 +7,6 @@ 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/qgraphicsutils/tst_qgraphicsutils.cpp b/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp
index e3676ad3b..bd4772045 100644
--- a/tests/auto/render/qgraphicsutils/tst_qgraphicsutils.cpp
+++ b/tests/auto/render/opengl/qgraphicsutils/tst_qgraphicsutils.cpp
@@ -27,7 +27,7 @@
****************************************************************************/
#include <QtTest/QtTest>
-#include <private/qgraphicsutils_p.h>
+#include <qgraphicsutils_p.h>
class tst_QGraphicsUtils : public QObject
{
@@ -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<GLfloat>(testVector, 1, 4);
+ const GLfloat *vectorData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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<GLfloat>(QVariant(variantList), 3, 4);
+ const GLfloat *vectorData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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<GLfloat> data(16);
void *innerData = data.data();
- Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData,
- Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant<GLfloat>(position, 1, 3),
- posUniform, 3);
- Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData,
- Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant<GLfloat>(direction, 1, 3),
- dirUniform, 3);
- Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData,
- Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant<GLfloat>(color, 1, 4),
- colUniform, 4);
- Qt3DRender::Render::QGraphicsUtils::fillDataArray(innerData,
- Qt3DRender::Render::QGraphicsUtils::valueArrayFromVariant<GLfloat>(intensity, 1, 1),
- intUniform, 1);
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData,
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(position, 1, 3),
+ posUniform, 3);
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData,
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(direction, 1, 3),
+ dirUniform, 3);
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData,
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(color, 1, 4),
+ colUniform, 4);
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::fillDataArray(innerData,
+ Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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<GLfloat>(mat, 1, 16);
+ const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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<GLfloat>(QVariant::fromValue(mat), 1, 12);
+ const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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<GLfloat>(QVariant::fromValue(mat), 1, 12);
+ const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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<GLfloat>(QVariant::fromValue(matrices), 3, 12);
+ const GLfloat *matData = Qt3DRender::Render::OpenGL::QGraphicsUtils::valueArrayFromVariant<GLfloat>(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/renderer/renderer.pro b/tests/auto/render/opengl/renderer/renderer.pro
index cbafc156b..d481c7b9e 100644
--- a/tests/auto/render/renderer/renderer.pro
+++ b/tests/auto/render/opengl/renderer/renderer.pro
@@ -7,3 +7,6 @@ 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/renderer/tst_renderer.cpp b/tests/auto/render/opengl/renderer/tst_renderer.cpp
index e1bf8dfd9..db7a37af1 100644
--- a/tests/auto/render/renderer/tst_renderer.cpp
+++ b/tests/auto/render/opengl/renderer/tst_renderer.cpp
@@ -30,13 +30,12 @@
#include <QMutex>
#include <QWaitCondition>
#include <QThread>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/viewportnode_p.h>
-#include <Qt3DRender/private/renderview_p.h>
-#include <Qt3DRender/private/renderviewbuilder_p.h>
+#include <renderer_p.h>
+#include <renderview_p.h>
+#include <renderviewbuilder_p.h>
#include <Qt3DRender/private/offscreensurfacehelper_p.h>
-#include <Qt3DRender/private/renderqueue_p.h>
-#include <Qt3DRender/private/job_common_p.h>
+#include <renderqueue_p.h>
class tst_Renderer : public QObject
{
@@ -51,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
@@ -78,17 +77,7 @@ private Q_SLOTS:
1); // RayCastingJob
// WHEN
- renderer.addRenderCaptureSendRequest(Qt3DCore::QNodeId::createId());
- jobs = renderer.preRenderingJobs();
-
- // THEN
- QCOMPARE(jobs.size(),
- 1 + // PickBoundingVolumeJob
- 1 + // RayCastingJob
- 1); // SendRenderCaptureJob
-
- // WHEN
- renderer.m_sendBufferCaptureJob->addRequest({nullptr, {}});
+ renderer.m_sendBufferCaptureJob->addRequest({Qt3DCore::QNodeId(), {}});
jobs = renderer.preRenderingJobs();
// THEN
@@ -110,20 +99,6 @@ private Q_SLOTS:
1); // SendSetFenceHandlesJob
// Note: pending set fence handles are only cleared when the job is run
- // WHEN
- renderer.m_updatedTextureProperties.push_back({{}, {}});
- jobs = renderer.preRenderingJobs();
-
- // THEN
- QCOMPARE(jobs.size(),
- 1 + // PickBoundingVolumeJob
- 1 + // RayCastingJob
- 1 + // SendBufferCaptureJob
- 1 + // SendSetFenceHandlesJob
- 1); // SendTextureChangesToFrontend
-
- // Note: pending texture changes are only cleared when the job is run
-
// Properly shutdown command thread
renderer.shutdown();
}
@@ -132,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
@@ -154,39 +129,84 @@ 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 singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount();
+
+ const int singleRenderViewCommandRebuildJobCount = 1 + Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount();
+
+ const int singleRenderViewJobCount = 8 + 1 * Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount();
// RenderViewBuilder renderViewJob,
// syncRenderViewInitializationJob,
// syncFrustumCullingJob,
// filterProximityJob,
// setClearDrawBufferIndexJob,
// frustumCullingJob,
- // syncRenderCommandBuldingJob,
- // syncRenderViewCommandBuilderJob
+ // syncRenderCommandUpdateJob,
+ // syncRenderViewCommandPostUpdateJob
// n * (RenderViewCommandBuildJobs)
// WHEN
QVector<Qt3DCore::QAspectJobPtr> 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 + // 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
+ 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)
+ // 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
@@ -197,6 +217,7 @@ private Q_SLOTS:
1 + // updateSkinningPaletteJob
1 + // SyncLoadingJobs
singleRenderViewJobCount +
+ singleRenderViewCommandRebuildJobCount +
renderViewBuilderMaterialCacheJobCount +
layerCacheJobCount);
@@ -253,6 +274,7 @@ private Q_SLOTS:
1 + // updateSkinningPaletteJob
1 + // SyncLoadingJobs
singleRenderViewJobCount +
+ singleRenderViewCommandRebuildJobCount +
renderViewBuilderMaterialCacheJobCount);
renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty);
@@ -274,6 +296,7 @@ private Q_SLOTS:
1 + // ExpandBoundingVolumeJob
1 + // RenderableEntityFilterPtr
1 + // SyncRenderableEntities
+ singleRenderViewCommandRebuildJobCount +
singleRenderViewJobCount);
renderer.clearDirtyBits(Qt3DRender::Render::AbstractRenderer::AllDirty);
@@ -315,41 +338,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/renderqueue/renderqueue.pro b/tests/auto/render/opengl/renderqueue/renderqueue.pro
index 945fe4cf4..19106ba92 100644
--- a/tests/auto/render/renderqueue/renderqueue.pro
+++ b/tests/auto/render/opengl/renderqueue/renderqueue.pro
@@ -8,4 +8,7 @@ CONFIG += testcase
SOURCES += tst_renderqueue.cpp
-include(../../core/common/common.pri)
+include(../../../core/common/common.pri)
+
+# Link Against OpenGL Renderer Plugin
+include(../opengl_render_plugin.pri)
diff --git a/tests/auto/render/renderqueue/tst_renderqueue.cpp b/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp
index 071f9b3a5..728648a3c 100644
--- a/tests/auto/render/renderqueue/tst_renderqueue.cpp
+++ b/tests/auto/render/opengl/renderqueue/tst_renderqueue.cpp
@@ -30,8 +30,8 @@
#include <QMutex>
#include <QWaitCondition>
#include <QThread>
-#include <Qt3DRender/private/renderqueue_p.h>
-#include <Qt3DRender/private/renderview_p.h>
+#include <renderqueue_p.h>
+#include <renderview_p.h>
class tst_RenderQueue : public QObject
{
@@ -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<Qt3DRender::Render::RenderView *> renderViews;
+ QList<Qt3DRender::Render::OpenGL::RenderView *> 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<Qt3DRender::Render::RenderView *> renderViews(7);
+ QVector<Qt3DRender::Render::OpenGL::RenderView *> 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<Qt3DRender::Render::RenderView *> frame = renderQueue.nextFrameQueue();
+ QVector<Qt3DRender::Render::OpenGL::RenderView *> 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<Qt3DRender::Render::RenderView *> renderViews(7);
+ QVector<Qt3DRender::Render::OpenGL::RenderView *> 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<Qt3DRender::Render::RenderView *> renderViews(5);
+ QVector<Qt3DRender::Render::OpenGL::RenderView *> renderViews(5);
for (int i = 0; i < 5; ++i) {
renderQueue.queueRenderView(renderViews.at(i), i);
}
diff --git a/tests/auto/render/renderviewbuilder/renderviewbuilder.pro b/tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro
index 00fdd49cf..b7b8f5b81 100644
--- a/tests/auto/render/renderviewbuilder/renderviewbuilder.pro
+++ b/tests/auto/render/opengl/renderviewbuilder/renderviewbuilder.pro
@@ -8,5 +8,8 @@ CONFIG += testcase
SOURCES += tst_renderviewbuilder.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/renderviewbuilder/tst_renderviewbuilder.cpp b/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp
index 96d51a3a9..fe534e243 100644
--- a/tests/auto/render/renderviewbuilder/tst_renderviewbuilder.cpp
+++ b/tests/auto/render/opengl/renderviewbuilder/tst_renderviewbuilder.cpp
@@ -31,7 +31,7 @@
#include <Qt3DCore/private/qnodevisitor_p.h>
#include <Qt3DCore/private/qnode_p.h>
-#include <Qt3DRender/private/renderviewbuilder_p.h>
+#include <renderviewbuilder_p.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
#include <Qt3DRender/qviewport.h>
#include <Qt3DRender/qclearbuffers.h>
@@ -52,6 +52,7 @@
#include <Qt3DRender/private/qrenderaspect_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
+#include <Qt3DRender/private/filterentitybycomponentjob_p.h>
QT_BEGIN_NAMESPACE
@@ -95,14 +96,14 @@ public:
return d_func()->m_renderer->nodeManagers();
}
- Render::Renderer *renderer() const
+ Render::OpenGL::Renderer *renderer() const
{
- return static_cast<Render::Renderer *>(d_func()->m_renderer);
+ return static_cast<Render::OpenGL::Renderer *>(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;
}
@@ -215,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);
@@ -224,36 +225,36 @@ 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::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();
@@ -263,55 +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());
- }
-
- {
- // WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
- renderViewBuilder.setLightGathererCacheNeedsToBeRebuilt(true);
- renderViewBuilder.prepareJobs();
-
- // THEN
- QCOMPARE(renderViewBuilder.lightGathererCacheNeedsToBeRebuilt(), true);
- QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount());
- }
-
- {
- // WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
- renderViewBuilder.setRenderableCacheNeedsToBeRebuilt(true);
- renderViewBuilder.prepareJobs();
-
- // THEN
- QCOMPARE(renderViewBuilder.renderableCacheNeedsToBeRebuilt(), true);
- QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount());
- }
-
- {
- // WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
- renderViewBuilder.setComputableCacheNeedsToBeRebuilt(true);
- renderViewBuilder.prepareJobs();
-
- // THEN
- QCOMPARE(renderViewBuilder.computableCacheNeedsToBeRebuilt(), true);
- QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 10 + 1 * Qt3DRender::Render::RenderViewBuilder::optimalJobCount());
+ QCOMPARE(renderViewBuilder.buildJobHierachy().size(), 9 + 2 * Qt3DRender::Render::OpenGL::RenderViewBuilder::optimalJobCount());
}
}
@@ -328,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();
@@ -338,8 +306,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,48 +315,49 @@ 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() + 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.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));
}
}
{
// 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();
@@ -399,63 +368,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));
}
}
}
@@ -472,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();
@@ -487,21 +456,18 @@ private Q_SLOTS:
Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport();
Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport);
Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport));
+ Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer();
// THEN
Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id());
QVERIFY(leafNode != nullptr);
// WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
- renderViewBuilder.setLightGathererCacheNeedsToBeRebuilt(true);
- renderViewBuilder.prepareJobs();
- renderViewBuilder.buildJobHierachy();
- renderViewBuilder.lightGathererJob()->run();
+ renderer->lightGathererJob()->run();
// THEN
- QCOMPARE(renderViewBuilder.lightGathererJob()->lights().size(), 2);
- QVERIFY(renderViewBuilder.lightGathererJob()->takeEnvironmentLight() != nullptr);
+ QCOMPARE(renderer->lightGathererJob()->lights().size(), 2);
+ QVERIFY(renderer->lightGathererJob()->takeEnvironmentLight() != nullptr);
}
void checkRenderableEntitiesFilteringExecution()
@@ -510,20 +476,17 @@ private Q_SLOTS:
Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport();
Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport);
Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport));
+ Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer();
// THEN
Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id());
QVERIFY(leafNode != nullptr);
// WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
- renderViewBuilder.setRenderableCacheNeedsToBeRebuilt(true);
- renderViewBuilder.prepareJobs();
- renderViewBuilder.buildJobHierachy();
- renderViewBuilder.renderableEntityFilterJob()->run();
+ renderer->renderableEntityFilterJob()->run();
// THEN
- QCOMPARE(renderViewBuilder.renderableEntityFilterJob()->filteredEntities().size(), 1);
+ QCOMPARE(renderer->renderableEntityFilterJob()->filteredEntities().size(), 1);
}
void checkComputableEntitiesFilteringExecution()
@@ -532,20 +495,17 @@ private Q_SLOTS:
Qt3DRender::QViewport *viewport = new Qt3DRender::QViewport();
Qt3DRender::QClearBuffers *clearBuffer = new Qt3DRender::QClearBuffers(viewport);
Qt3DRender::TestAspect testAspect(buildSimpleScene(viewport));
+ Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer();
// THEN
Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(clearBuffer->id());
QVERIFY(leafNode != nullptr);
// WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
- renderViewBuilder.setComputableCacheNeedsToBeRebuilt(true);
- renderViewBuilder.prepareJobs();
- renderViewBuilder.buildJobHierachy();
- renderViewBuilder.computableEntityFilterJob()->run();
+ renderer->computableEntityFilterJob()->run();
// THEN
- QCOMPARE(renderViewBuilder.computableEntityFilterJob()->filteredEntities().size(), 1);
+ QCOMPARE(renderer->computableEntityFilterJob()->filteredEntities().size(), 1);
}
void checkSyncRenderViewInitializationExecution()
@@ -568,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();
@@ -581,7 +541,7 @@ private Q_SLOTS:
// WHEN
renderViewBuilder.renderViewJob()->run();
- renderViewBuilder.syncRenderViewInitializationJob()->run();
+ renderViewBuilder.syncRenderViewPostInitializationJob()->run();
// THEN
QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true);
@@ -592,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();
@@ -608,7 +568,7 @@ private Q_SLOTS:
// WHEN
renderViewBuilder.renderViewJob()->run();
- renderViewBuilder.syncRenderViewInitializationJob()->run();
+ renderViewBuilder.syncRenderViewPostInitializationJob()->run();
// THEN
QCOMPARE(renderViewBuilder.frustumCullingJob()->isActive(), true);
@@ -638,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();
@@ -647,7 +607,7 @@ private Q_SLOTS:
// WHEN
renderViewBuilder.renderViewJob()->run();
- renderViewBuilder.syncFrustumCullingJob()->run();
+ renderViewBuilder.syncPreFrustumCullingJob()->run();
// THEN
QCOMPARE(convertToQMatrix4x4(renderViewBuilder.frustumCullingJob()->viewProjection()), camera->projectionMatrix() * camera->viewMatrix());
@@ -662,24 +622,29 @@ private Q_SLOTS:
Qt3DRender::QLayer *layer = new Qt3DRender::QLayer();
layerFilter->addLayer(layer);
Qt3DRender::TestAspect testAspect(buildEntityFilterTestScene(viewport, layer));
+ Qt3DRender::Render::OpenGL::Renderer *renderer = testAspect.renderer();
// THEN
Qt3DRender::Render::FrameGraphNode *leafNode = testAspect.nodeManagers()->frameGraphManager()->lookupNode(layerFilter->id());
QVERIFY(leafNode != nullptr);
// WHEN
- Qt3DRender::Render::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
+ renderer->markDirty(Qt3DRender::Render::AbstractRenderer::AllDirty, nullptr);
+
+ Qt3DRender::Render::OpenGL::RenderViewBuilder renderViewBuilder(leafNode, 0, testAspect.renderer());
+
renderViewBuilder.setLayerCacheNeedsToBeRebuilt(true);
- renderViewBuilder.setRenderableCacheNeedsToBeRebuilt(true);
renderViewBuilder.prepareJobs();
renderViewBuilder.buildJobHierachy();
+ renderer->renderableEntityFilterJob()->run();
+ renderer->cacheRenderableEntitiesJob()->run();
+
renderViewBuilder.renderViewJob()->run();
- renderViewBuilder.renderableEntityFilterJob()->run();
- renderViewBuilder.syncRenderViewInitializationJob()->run();
+ renderViewBuilder.syncRenderViewPostInitializationJob()->run();
renderViewBuilder.filterEntityByLayerJob()->run();
- QVector<Qt3DRender::Render::Entity *> renderableEntity = renderViewBuilder.renderableEntityFilterJob()->filteredEntities();
+ QVector<Qt3DRender::Render::Entity *> renderableEntity = renderer->renderableEntityFilterJob()->filteredEntities();
QVector<Qt3DRender::Render::Entity *> filteredEntity = renderViewBuilder.filterEntityByLayerJob()->filteredEntities();
// THEN
@@ -689,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/renderviews/renderviews.pro b/tests/auto/render/opengl/renderviews/renderviews.pro
index 046c00696..7efbaec14 100644
--- a/tests/auto/render/renderviews/renderviews.pro
+++ b/tests/auto/render/opengl/renderviews/renderviews.pro
@@ -8,5 +8,8 @@ CONFIG += testcase
SOURCES += tst_renderviews.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/renderviews/tst_renderviews.cpp b/tests/auto/render/opengl/renderviews/tst_renderviews.cpp
index 5c377788b..6d01122d1 100644
--- a/tests/auto/render/renderviews/tst_renderviews.cpp
+++ b/tests/auto/render/opengl/renderviews/tst_renderviews.cpp
@@ -28,12 +28,17 @@
#include <QtTest/QTest>
#include <qbackendnodetester.h>
-#include <private/renderview_p.h>
#include <private/memorybarrier_p.h>
-#include <private/renderviewjobutils_p.h>
-#include <private/rendercommand_p.h>
#include <testpostmanarbiter.h>
#include <testrenderer.h>
+#include <private/shader_p.h>
+#include <Qt3DRender/qshaderprogram.h>
+#include <renderview_p.h>
+#include <renderviewjobutils_p.h>
+#include <rendercommand_p.h>
+#include <renderer_p.h>
+#include <glresourcemanagers_p.h>
+#include <private/shader_p.h>
QT_BEGIN_NAMESPACE
@@ -41,6 +46,8 @@ namespace Qt3DRender {
namespace Render {
+namespace OpenGL {
+
namespace {
void compareShaderParameterPacks(const ShaderParameterPack &t1,
@@ -49,16 +56,11 @@ void compareShaderParameterPacks(const ShaderParameterPack &t1,
const PackUniformHash hash1 = t1.uniforms();
const PackUniformHash hash2 = t2.uniforms();
- QCOMPARE(hash1.size(), hash2.size());
-
- auto it = hash1.constBegin();
- const auto end = hash1.constEnd();
+ QCOMPARE(hash1.keys.size(), hash2.keys.size());
- while (it != end) {
- const auto h2It = hash2.find(it.key());
- QVERIFY(h2It != hash2.cend());
- QCOMPARE(it.value(), h2It.value());
- ++it;
+ 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));
}
}
@@ -67,6 +69,7 @@ void compareShaderParameterPacks(const ShaderParameterPack &t1,
class tst_RenderViews : public Qt3DCore::QBackendNodeTester
{
Q_OBJECT
+
private Q_SLOTS:
void checkRenderViewSizeFitsWithAllocator()
@@ -124,7 +127,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());
@@ -135,15 +138,20 @@ private Q_SLOTS:
void checkRenderCommandBackToFrontSorting()
{
// GIVEN
+ Qt3DRender::Render::NodeManagers nodeManagers;
+ Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
RenderView renderView;
- QVector<RenderCommand *> rawCommands;
+ QVector<RenderCommand> rawCommands;
QVector<QSortPolicy::SortType> sortTypes;
+ renderer.setNodeManagers(&nodeManagers);
+ renderView.setRenderer(&renderer);
+
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);
}
@@ -153,34 +161,40 @@ private Q_SLOTS:
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
+ const QVector<RenderCommand> 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
+ renderer.shutdown();
}
void checkRenderCommandMaterialSorting()
{
// GIVEN
+ Qt3DRender::Render::NodeManagers nodeManagers;
+ Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
RenderView renderView;
- QVector<RenderCommand *> rawCommands;
+ QVector<RenderCommand> rawCommands;
QVector<QSortPolicy::SortType> 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<GLShader *>(0x250),
+ reinterpret_cast<GLShader *>(0x500),
+ reinterpret_cast<GLShader *>(0x1000),
+ reinterpret_cast<GLShader *>(0x1500),
+ reinterpret_cast<GLShader *>(0x2000)
};
for (int i = 0; i < 20; ++i) {
- RenderCommand *c = new RenderCommand();
- c->m_shaderDna = dnas[i % 5];
+ RenderCommand c;
+ c.m_glShader = dnas[i % 5];
rawCommands.push_back(c);
}
@@ -190,26 +204,27 @@ private Q_SLOTS:
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
+ const QVector<RenderCommand> 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<QVector<ProgramDNA>>("programDNAs");
+ QTest::addColumn<QVector<QShaderProgram*>>("shaders");
QTest::addColumn<QVector<ShaderParameterPack>>("rawParameters");
QTest::addColumn<QVector<ShaderParameterPack>>("expectedMinimizedParameters");
@@ -220,68 +235,96 @@ 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>() << ProgramDNA(883) << ProgramDNA(1584))
+ << (QVector<QShaderProgram*>() << shader1 << shader2)
<< (QVector<ShaderParameterPack>() << pack1 << pack1)
<< (QVector<ShaderParameterPack>() << pack1 << pack1);
QTest::newRow("SingleShaderMinified")
- << (QVector<ProgramDNA>() << ProgramDNA(883) << ProgramDNA(883) << ProgramDNA(883))
+ << (QVector<QShaderProgram*>() << shader1 << shader1 << shader1)
<< (QVector<ShaderParameterPack>() << pack1 << pack1 << pack1)
<< (QVector<ShaderParameterPack>() << pack1 << minifiedPack1 << minifiedPack1);
QTest::newRow("MultipleShadersMinified")
- << (QVector<ProgramDNA>() << ProgramDNA(883) << ProgramDNA(883) << ProgramDNA(883) << ProgramDNA(1584) << ProgramDNA(1584) << ProgramDNA(1584))
+ << (QVector<QShaderProgram*>() << shader1 << shader1 << shader1 << shader2 << shader2 << shader2)
<< (QVector<ShaderParameterPack>() << pack1 << pack1 << pack1 << pack1 << pack1 << pack1)
<< (QVector<ShaderParameterPack>() << pack1 << minifiedPack1 << minifiedPack1 << pack1 << minifiedPack1 << minifiedPack1);
}
void checkRenderViewUniformMinification()
{
- QFETCH(QVector<ProgramDNA>, programDNAs);
+ QFETCH(QVector<QShaderProgram*>, shaders);
QFETCH(QVector<ShaderParameterPack>, rawParameters);
QFETCH(QVector<ShaderParameterPack>, expectedMinimizedParameters);
- RenderView renderView;
- QVector<RenderCommand *> rawCommands;
+ Qt3DRender::Render::NodeManagers nodeManagers;
+ Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
+ renderer.setNodeManagers(&nodeManagers);
- 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);
+ 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<RenderCommand> 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::SortType>() << QSortPolicy::Uniform));
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
+ const QVector<RenderCommand> 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));
+ 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;
+ Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
RenderView renderView;
- QVector<RenderCommand *> rawCommands;
+ QVector<RenderCommand> rawCommands;
QVector<QSortPolicy::SortType> sortTypes;
+ renderer.setNodeManagers(&nodeManagers);
+ renderView.setRenderer(&renderer);
+
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);
}
@@ -291,26 +334,32 @@ private Q_SLOTS:
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
+ const QVector<RenderCommand> 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
+ renderer.shutdown();
}
void checkRenderCommandStateCostSorting()
{
// GIVEN
+ Qt3DRender::Render::NodeManagers nodeManagers;
+ Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
RenderView renderView;
- QVector<RenderCommand *> rawCommands;
+ QVector<RenderCommand> rawCommands;
QVector<QSortPolicy::SortType> sortTypes;
+ renderer.setNodeManagers(&nodeManagers);
+ renderView.setRenderer(&renderer);
+
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);
}
@@ -320,30 +369,37 @@ private Q_SLOTS:
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
+ const QVector<RenderCommand> 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
+ renderer.shutdown();
}
void checkRenderCommandCombinedStateMaterialDepthSorting()
{
// GIVEN
+ Qt3DRender::Render::NodeManagers nodeManagers;
+ Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
RenderView renderView;
- QVector<RenderCommand *> rawCommands;
+ QVector<RenderCommand> rawCommands;
QVector<QSortPolicy::SortType> 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<GLShader *>(0x250),
+ reinterpret_cast<GLShader *>(0x500),
+ reinterpret_cast<GLShader *>(0x1000),
+ reinterpret_cast<GLShader *>(0x1500),
+ reinterpret_cast<GLShader *>(0x2000)
};
float depth[3] = {
@@ -357,25 +413,25 @@ private Q_SLOTS:
200
};
- auto buildRC = [] (ProgramDNA dna, float depth, int changeCost) {
- RenderCommand *c = new RenderCommand();
- c->m_shaderDna = dna;
- c->m_depth = depth;
- c->m_changeCost = changeCost;
+ 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 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;
@@ -385,12 +441,9 @@ private Q_SLOTS:
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
+ const QVector<RenderCommand> 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));
@@ -405,6 +458,7 @@ private Q_SLOTS:
QCOMPARE(c9, sortedCommands.at(6));
// RenderCommands are deleted by RenderView dtor
+ renderer.shutdown();
}
void checkRenderCommandTextureSorting()
@@ -421,61 +475,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<RenderCommand *> rawCommands = {a, b, c, d, e, f, g};
+ QVector<RenderCommand> rawCommands = {a, b, c, d, e, f, g};
renderView.addSortType(sortTypes);
renderView.setCommands(rawCommands);
renderView.sort();
// THEN
- const QVector<RenderCommand *> sortedCommands = renderView.commands();
- qDebug() << rawCommands << sortedCommands;
+ const QVector<RenderCommand> sortedCommands = renderView.commands();
QCOMPARE(rawCommands.size(), sortedCommands.size());
QCOMPARE(sortedCommands.at(0), a);
QCOMPARE(sortedCommands.at(1), g);
@@ -489,6 +542,8 @@ private Q_SLOTS:
private:
};
+} // OpenGL
+
} // Render
} // Qt3DRender
@@ -496,6 +551,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/renderviewutils/renderviewutils.pro b/tests/auto/render/opengl/renderviewutils/renderviewutils.pro
index 90d8a2562..e9c9f8d51 100644
--- a/tests/auto/render/renderviewutils/renderviewutils.pro
+++ b/tests/auto/render/opengl/renderviewutils/renderviewutils.pro
@@ -8,5 +8,8 @@ CONFIG += testcase
SOURCES += tst_renderviewutils.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/renderviewutils/tst_renderviewutils.cpp b/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp
index 6d349f994..6b714b9e1 100644
--- a/tests/auto/render/renderviewutils/tst_renderviewutils.cpp
+++ b/tests/auto/render/opengl/renderviewutils/tst_renderviewutils.cpp
@@ -29,7 +29,8 @@
#include <QtTest/QTest>
#include <qbackendnodetester.h>
#include <Qt3DCore/qdynamicpropertyupdatedchange.h>
-#include <Qt3DRender/private/renderviewjobutils_p.h>
+#include <renderviewjobutils_p.h>
+#include <shadervariables_p.h>
#include <Qt3DRender/private/shaderdata_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/stringtoint_p.h>
@@ -107,11 +108,11 @@ public:
return m_scalar;
}
- QHash<QString, Qt3DRender::Render::ShaderUniform> buildUniformMap(const QString &blockName)
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> buildUniformMap(const QString &blockName)
{
- QHash<QString, Qt3DRender::Render::ShaderUniform> uniforms;
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> uniforms;
- uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::ShaderUniform());
+ uniforms.insert(blockName + QStringLiteral(".scalar"), Qt3DRender::Render::OpenGL::ShaderUniform());
return uniforms;
}
@@ -148,11 +149,11 @@ public:
return m_texture;
}
- QHash<QString, Qt3DRender::Render::ShaderUniform> buildUniformMap(const QString &blockName)
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> buildUniformMap(const QString &blockName)
{
- QHash<QString, Qt3DRender::Render::ShaderUniform> uniforms;
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> uniforms;
- uniforms.insert(blockName + QStringLiteral(".texture"), Qt3DRender::Render::ShaderUniform());
+ uniforms.insert(blockName + QStringLiteral(".texture"), Qt3DRender::Render::OpenGL::ShaderUniform());
return uniforms;
}
@@ -189,11 +190,11 @@ public:
return m_array;
}
- QHash<QString, Qt3DRender::Render::ShaderUniform> buildUniformMap(const QString &blockName)
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> buildUniformMap(const QString &blockName)
{
- QHash<QString, Qt3DRender::Render::ShaderUniform> uniforms;
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> uniforms;
- uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::ShaderUniform());
+ uniforms.insert(blockName + QStringLiteral(".array[0]"), Qt3DRender::Render::OpenGL::ShaderUniform());
return uniforms;
}
@@ -244,12 +245,12 @@ public:
return m_array;
}
- virtual QHash<QString, Qt3DRender::Render::ShaderUniform> buildUniformMap(const QString &blockName)
+ virtual QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> buildUniformMap(const QString &blockName)
{
- QHash<QString, Qt3DRender::Render::ShaderUniform> uniforms;
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> 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;
}
@@ -298,17 +299,17 @@ public:
return m_inner;
}
- QHash<QString, Qt3DRender::Render::ShaderUniform> buildUniformMap(const QString &blockName) override
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> buildUniformMap(const QString &blockName) override
{
- QHash<QString, Qt3DRender::Render::ShaderUniform> innerUniforms;
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> innerUniforms;
StructShaderData *innerData = nullptr;
if ((innerData = qobject_cast<StructShaderData *>(m_inner)) != nullptr)
innerUniforms = innerData->buildUniformMap(QStringLiteral(".inner"));
- QHash<QString, Qt3DRender::Render::ShaderUniform> uniforms = StructShaderData::buildUniformMap(blockName);
- QHash<QString, Qt3DRender::Render::ShaderUniform>::const_iterator it = innerUniforms.begin();
- const QHash<QString, Qt3DRender::Render::ShaderUniform>::const_iterator end = innerUniforms.end();
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform> uniforms = StructShaderData::buildUniformMap(blockName);
+ QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform>::const_iterator it = innerUniforms.begin();
+ const QHash<QString, Qt3DRender::Render::OpenGL::ShaderUniform>::const_iterator end = innerUniforms.end();
while (it != end) {
uniforms.insert(blockName + it.key(), it.value());
@@ -361,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;
@@ -390,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;
@@ -403,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
@@ -432,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;
@@ -463,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;
@@ -476,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
@@ -505,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;
@@ -518,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
@@ -570,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"));
@@ -646,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;
@@ -659,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
@@ -692,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/textures/textures.pro b/tests/auto/render/opengl/textures/textures.pro
index 8a7553a54..a116756af 100644
--- a/tests/auto/render/textures/textures.pro
+++ b/tests/auto/render/opengl/textures/textures.pro
@@ -8,5 +8,8 @@ CONFIG += testcase
SOURCES += tst_textures.cpp
-include(../../core/common/common.pri)
-include(../commons/commons.pri)
+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/textures/tst_textures.cpp b/tests/auto/render/opengl/textures/tst_textures.cpp
index 555bd09a3..5343a6fde 100644
--- a/tests/auto/render/textures/tst_textures.cpp
+++ b/tests/auto/render/opengl/textures/tst_textures.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <qbackendnodetester.h>
#include <qtextureimagedatagenerator.h>
@@ -33,13 +37,13 @@
#include <Qt3DRender/qtextureimage.h>
#include <Qt3DRender/qtexturedata.h>
-#include <Qt3DRender/private/renderer_p.h>
+#include <renderer_p.h>
+#include <glresourcemanagers_p.h>
+#include <gltexture_p.h>
#include <Qt3DRender/private/texture_p.h>
#include <Qt3DRender/private/textureimage_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
-#include <Qt3DRender/private/gltexturemanager_p.h>
-#include <Qt3DRender/private/gltexture_p.h>
#include <Qt3DRender/private/qtexture_p.h>
#include <testrenderer.h>
@@ -218,7 +222,7 @@ private Q_SLOTS:
{
QSKIP("Texture Sharing is now disabled");
QScopedPointer<Qt3DRender::Render::NodeManagers> 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
@@ -238,15 +242,15 @@ 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();
}
void shouldCreateDifferentGLTexturess()
{
QScopedPointer<Qt3DRender::Render::NodeManagers> 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
@@ -274,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<Qt3DRender::Render::GLTexture *> glTextures;
+ QVector<Qt3DRender::Render::OpenGL::GLTexture *> 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);
@@ -301,9 +306,11 @@ private Q_SLOTS:
void shouldCreateDifferentGLTexturesWhenUsingSharedTextureIds()
{
QScopedPointer<Qt3DRender::Render::NodeManagers> 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::OpenGL::GLResourceManagers *glMgrs = renderer.glResourceManagers();
+
// both texture having the same sharedTextureId
{
// GIVEN
@@ -328,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::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());
@@ -359,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::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());
@@ -372,7 +379,7 @@ private Q_SLOTS:
void generatorsShouldCreateSameData()
{
QScopedPointer<Qt3DRender::Render::NodeManagers> 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
@@ -392,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);
@@ -431,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);
@@ -455,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);
{
@@ -587,7 +594,7 @@ private Q_SLOTS:
void checkTextureImageProperlyReleaseGenerator()
{
QScopedPointer<Qt3DRender::Render::NodeManagers> 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());
@@ -627,7 +634,7 @@ private Q_SLOTS:
void checkTextureIsMarkedForDeletion()
{
QScopedPointer<Qt3DRender::Render::NodeManagers> 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());
@@ -661,7 +668,7 @@ private Q_SLOTS:
void checkTextureDestructionReconstructionWithinSameLoop()
{
QScopedPointer<Qt3DRender::Render::NodeManagers> 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());
@@ -700,7 +707,7 @@ private Q_SLOTS:
{
// GIVEN
QScopedPointer<Qt3DRender::Render::NodeManagers> 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/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 <Qt3DRender/QNoPicking>
#include <Qt3DRender/QPickEvent>
#include <Qt3DRender/QPickTriangleEvent>
+#include <Qt3DRender/QPickingSettings>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/qrenderaspect.h>
+#include <Qt3DRender/private/rendersettings_p.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
#include <Qt3DRender/private/pickboundingvolumejob_p.h>
#include <Qt3DRender/private/pickboundingvolumeutils_p.h>
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<Qt3DRender::QBuffer *>(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/proximityfiltering/tst_proximityfiltering.cpp b/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp
index 7ff54f6fa..51b59bffc 100644
--- a/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp
+++ b/tests/auto/render/proximityfiltering/tst_proximityfiltering.cpp
@@ -38,6 +38,10 @@
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/private/filterproximitydistancejob_p.h>
#include <Qt3DRender/private/updatetreeenabledjob_p.h>
+#include <Qt3DRender/private/updateworldtransformjob_p.h>
+#include <Qt3DRender/private/updateworldboundingvolumejob_p.h>
+#include <Qt3DRender/private/calcboundingvolumejob_p.h>
+#include <Qt3DRender/private/expandboundingvolumejob_p.h>
#include <Qt3DRender/qproximityfilter.h>
#include "testaspect.h"
@@ -117,14 +121,20 @@ private Q_SLOTS:
{
Qt3DCore::QEntity *rootEntity = new Qt3DCore::QEntity();
- Qt3DCore::QEntity *childEntity1 = new Qt3DCore::QEntity(rootEntity);
- Qt3DCore::QEntity *childEntity2 = new Qt3DCore::QEntity(rootEntity);
- Qt3DCore::QEntity *childEntity3 = new Qt3DCore::QEntity(rootEntity);
+ Qt3DCore::QEntity *targetEntity = new Qt3DCore::QEntity(rootEntity);
+ Qt3DCore::QEntity *childEntity1 = buildEntityAtDistance(50.0f, rootEntity);
+ Qt3DCore::QEntity *childEntity2 = buildEntityAtDistance(25.0f, rootEntity);
+ Qt3DCore::QEntity *childEntity3 = buildEntityAtDistance(75.0f, rootEntity);
+
+ Qt3DRender::QProximityFilter *proximityFilter = new Qt3DRender::QProximityFilter(rootEntity);
+ proximityFilter->setDistanceThreshold(200.0f);
+ proximityFilter->setEntity(targetEntity);
QTest::newRow("ShouldSelectAll") << rootEntity
- << Qt3DCore::QNodeIdVector()
+ << (Qt3DCore::QNodeIdVector() << proximityFilter->id())
<< (Qt3DCore::QNodeIdVector()
<< rootEntity->id()
+ << targetEntity->id()
<< childEntity1->id()
<< childEntity2->id()
<< childEntity3->id()
diff --git a/tests/auto/render/qabstracttexture/tst_qabstracttexture.cpp b/tests/auto/render/qabstracttexture/tst_qabstracttexture.cpp
index a1973176e..6fad09a0d 100644
--- a/tests/auto/render/qabstracttexture/tst_qabstracttexture.cpp
+++ b/tests/auto/render/qabstracttexture/tst_qabstracttexture.cpp
@@ -26,6 +26,9 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qabstracttexture.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.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 <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/transform_p.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
+#include <Qt3DRender/private/updateworldtransformjob_p.h>
QT_BEGIN_NAMESPACE
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DRender/qgeometryrenderer.h>
diff --git a/tests/auto/render/qgeometry/tst_qgeometry.cpp b/tests/auto/render/qgeometry/tst_qgeometry.cpp
index 017314ecf..e790ba9cc 100644
--- a/tests/auto/render/qgeometry/tst_qgeometry.cpp
+++ b/tests/auto/render/qgeometry/tst_qgeometry.cpp
@@ -26,6 +26,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qnode_p.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qmesh.h>
diff --git a/tests/auto/render/qraycaster/tst_qraycaster.cpp b/tests/auto/render/qraycaster/tst_qraycaster.cpp
index 720c372de..8ac084545 100644
--- a/tests/auto/render/qraycaster/tst_qraycaster.cpp
+++ b/tests/auto/render/qraycaster/tst_qraycaster.cpp
@@ -80,7 +80,7 @@ private Q_SLOTS:
QScopedPointer<Qt3DRender::QRayCaster> rayCaster(new Qt3DRender::QRayCaster());
QVERIFY(!rayCaster->isEnabled());
- QVERIFY(rayCaster->direction().length() > 0.);
+ QVERIFY(rayCaster->direction().length() > 0.f);
QCOMPARE(rayCaster->runMode(), Qt3DRender::QAbstractRayCaster::SingleShot);
// WHEN
@@ -125,13 +125,11 @@ private Q_SLOTS:
QCoreApplication::processEvents();
// THEN
- QCOMPARE(arbiter.events.size(), 1);
- auto addChange = arbiter.events.first().staticCast<Qt3DCore::QPropertyNodeAddedChange>();
- QCOMPARE(addChange->propertyName(), "layer");
- QCOMPARE(addChange->subjectId(), rayCaster->id());
- QCOMPARE(addChange->addedNodeId(), rayCaster->layers().at(0)->id());
- QCOMPARE(addChange->type(), Qt3DCore::PropertyValueAdded);
+ QCOMPARE(arbiter.events.size(), 0);
+ QCOMPARE(arbiter.dirtyNodes.size(), 1);
+ QCOMPARE(arbiter.dirtyNodes.front(), rayCaster.data());
+ arbiter.dirtyNodes.clear();
arbiter.events.clear();
// WHEN
@@ -141,13 +139,11 @@ private Q_SLOTS:
QCoreApplication::processEvents();
// THEN
- QCOMPARE(arbiter.events.size(), 1);
- addChange = arbiter.events.first().staticCast<Qt3DCore::QPropertyNodeAddedChange>();
- QCOMPARE(addChange->propertyName(), "layer");
- QCOMPARE(addChange->subjectId(), rayCaster->id());
- QCOMPARE(addChange->addedNodeId(), rayCaster->layers().at(1)->id());
- QCOMPARE(addChange->type(), Qt3DCore::PropertyValueAdded);
+ QCOMPARE(arbiter.events.size(), 0);
+ QCOMPARE(arbiter.dirtyNodes.size(), 1);
+ QCOMPARE(arbiter.dirtyNodes.front(), rayCaster.data());
+ arbiter.dirtyNodes.clear();
arbiter.events.clear();
// WHEN
@@ -156,13 +152,11 @@ private Q_SLOTS:
QCoreApplication::processEvents();
// THEN
- QCOMPARE(arbiter.events.size(), 1);
- auto removeChange = arbiter.events.first().staticCast<Qt3DCore::QPropertyNodeRemovedChange>();
- QCOMPARE(removeChange->propertyName(), "layer");
- QCOMPARE(removeChange->subjectId(), rayCaster->id());
- QCOMPARE(removeChange->removedNodeId(), layer->id());
- QCOMPARE(removeChange->type(), Qt3DCore::PropertyValueRemoved);
+ QCOMPARE(arbiter.events.size(), 0);
+ QCOMPARE(arbiter.dirtyNodes.size(), 1);
+ QCOMPARE(arbiter.dirtyNodes.front(), rayCaster.data());
+ arbiter.dirtyNodes.clear();
arbiter.events.clear();
}
@@ -209,29 +203,6 @@ private Q_SLOTS:
<< QByteArray(SIGNAL(hitsChanged(const Hits &)))
<< QByteArrayLiteral("hits");
}
-
- void checkBackendUpdates()
- {
- // GIVEN
- QFETCH(QByteArray, signalPrototype);
- QFETCH(QByteArray, propertyName);
- QScopedPointer<MyRayCaster> rayCaster(new MyRayCaster());
- QSignalSpy spy(rayCaster.data(), signalPrototype.constData());
- Qt3DRender::QRayCaster::Hits hits;
-
- // WHEN
- // Create Backend Change and distribute it to frontend node
- Qt3DCore::QPropertyUpdatedChangePtr e(new Qt3DCore::QPropertyUpdatedChange(rayCaster->id()));
- e->setPropertyName(propertyName.constData());
- QVariant v;
- v.setValue<Qt3DRender::QRayCaster::Hits>(hits);
- e->setValue(v);
- rayCaster->sceneChangeEvent(e);
-
- // THEN
- // Check that the QRayCaster triggers the expected signal
- QCOMPARE(spy.count(), 1);
- }
};
QTEST_MAIN(tst_QRayCaster)
diff --git a/tests/auto/render/qrendercapture/tst_qrendercapture.cpp b/tests/auto/render/qrendercapture/tst_qrendercapture.cpp
index 9ed7651fc..35c645d41 100644
--- a/tests/auto/render/qrendercapture/tst_qrendercapture.cpp
+++ b/tests/auto/render/qrendercapture/tst_qrendercapture.cpp
@@ -26,6 +26,9 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <QtTest/QSignalSpy>
diff --git a/tests/auto/render/qsetfence/tst_qsetfence.cpp b/tests/auto/render/qsetfence/tst_qsetfence.cpp
index f5989fcd4..ad92e9fe0 100644
--- a/tests/auto/render/qsetfence/tst_qsetfence.cpp
+++ b/tests/auto/render/qsetfence/tst_qsetfence.cpp
@@ -37,6 +37,10 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
+
#include <QtTest/QTest>
#include <Qt3DRender/qsetfence.h>
#include <Qt3DRender/private/qsetfence_p.h>
diff --git a/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp b/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp
index a261d0860..15be26e8e 100644
--- a/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp
+++ b/tests/auto/render/qshaderprogram/tst_qshaderprogram.cpp
@@ -26,6 +26,9 @@
**
****************************************************************************/
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qshaderprogram.h>
@@ -42,6 +45,13 @@ class tst_QShaderProgram : public Qt3DRender::QShaderProgram
{
Q_OBJECT
+public:
+ tst_QShaderProgram()
+ : Qt3DRender::QShaderProgram()
+ {
+ qRegisterMetaType<Qt3DRender::QShaderProgram::Format>("Format");
+ }
+
private Q_SLOTS:
void checkDefaultConstruction()
@@ -58,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()
@@ -179,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()
@@ -192,6 +222,7 @@ private Q_SLOTS:
shaderProgram.setGeometryShaderCode(QByteArrayLiteral("Geometry"));
shaderProgram.setFragmentShaderCode(QByteArrayLiteral("Fragment"));
shaderProgram.setComputeShaderCode(QByteArrayLiteral("Compute"));
+ shaderProgram.setFormat(QShaderProgram::SPIRV);
// WHEN
QVector<Qt3DCore::QNodeCreatedChangeBasePtr> creationChanges;
@@ -214,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());
@@ -529,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/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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qtexture.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qtextureimage.h>
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 <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qtexture.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 <Qt3DRender/qpickevent.h>
#include <Qt3DRender/qraycaster.h>
#include <Qt3DCore/private/qbackendnode_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include "testpostmanarbiter.h"
#include "testrenderer.h"
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 <Qt3DCore/private/qaspectmanager_p.h>
#include <Qt3DCore/private/qscene_p.h>
#include <Qt3DCore/private/qaspectengine_p.h>
+#include <Qt3DCore/private/qaspectjob_p.h>
#include <QtQuick/qquickwindow.h>
#include <Qt3DRender/QCamera>
diff --git a/tests/auto/render/render.pro b/tests/auto/render/render.pro
index 180ff7ac1..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 \
@@ -42,7 +41,6 @@ qtConfig(private_tests) {
# boundingvolumedebug \
ddstextures \
ktxtextures \
- shadercache \
layerfiltering \
filterentitybycomponent \
genericlambdajob \
@@ -126,19 +124,8 @@ QT_FOR_CONFIG += 3drender-private
qtConfig(qt3d-opengl-renderer):qtConfig(private_tests) {
SUBDIRS += \
- filtercompatibletechniquejob \
- graphicshelpergl3_3 \
- graphicshelpergl3_2 \
- graphicshelpergl2 \
- materialparametergathererjob \
- textures \
- renderer \
- renderviewutils \
- renderviews \
- renderqueue \
- renderviewbuilder \
- sendrendercapturejob \
- gltexture
+ opengl \
+ scene2d
qtConfig(qt3d-extras) {
SUBDIRS += \
@@ -159,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/scene2d/tst_scene2d.cpp b/tests/auto/render/scene2d/tst_scene2d.cpp
index fcb4c0908..b0a7fbeb8 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> testWindow(new TestWindow());
Scene2DSharedObjectPtr sharedObject(new Scene2DSharedObject(nullptr));
+ TestRenderer renderer;
QScopedPointer<Scene2D> scene2d(new Scene2D());
QScopedPointer<NodeManagers> nodeManagers(new NodeManagers());
Qt3DRender::QGeometry *geometry = new Qt3DRender::QGeometry();
@@ -218,7 +219,6 @@ private Q_SLOTS:
Qt3DRender::QBuffer *dataBuffer =new Qt3DRender::QBuffer();
QScopedPointer<Qt3DCore::QEntity> entity(new Qt3DCore::QEntity());
entity->addComponent(geometryRenderer);
- TestRenderer renderer;
renderer.setNodeManagers(nodeManagers.data());
scene2d->setRenderer(&renderer);
scene2d->setEnabled(true);
@@ -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/segmentvisitor/tst_segmentvisitor.cpp b/tests/auto/render/segmentvisitor/tst_segmentvisitor.cpp
index 4db12136a..fc65d0854 100644
--- a/tests/auto/render/segmentvisitor/tst_segmentvisitor.cpp
+++ b/tests/auto/render/segmentvisitor/tst_segmentvisitor.cpp
@@ -426,12 +426,15 @@ private Q_SLOTS:
simulateInitializationSync(dataBuffer.data(), backendBuffer);
QByteArray indexData;
- indexData.resize(sizeof(uint) * 2 * 4);
+ indexData.resize(sizeof(uint) * 7);
uint *iDataPtr = reinterpret_cast<uint *>(indexData.data());
iDataPtr[0] = 0;
iDataPtr[1] = 1;
iDataPtr[2] = 2;
iDataPtr[3] = 3;
+ iDataPtr[4] = static_cast<uint>(-1);
+ iDataPtr[5] = 0;
+ iDataPtr[6] = 1;
indexDataBuffer->setData(indexData);
Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id());
@@ -450,7 +453,7 @@ private Q_SLOTS:
indexAttribute->setBuffer(indexDataBuffer.data());
indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedInt);
- indexAttribute->setCount(4);
+ indexAttribute->setCount(7);
indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute);
geometry->addAttribute(positionAttribute.data());
@@ -458,6 +461,8 @@ private Q_SLOTS:
geometryRenderer->setGeometry(geometry);
geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::LineStrip);
+ geometryRenderer->setPrimitiveRestartEnabled(true);
+ geometryRenderer->setRestartIndexValue(-1);
Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id());
backendAttribute->setRenderer(&renderer);
@@ -480,10 +485,11 @@ private Q_SLOTS:
visitor.apply(backendRenderer, Qt3DCore::QNodeId());
// THEN
- QCOMPARE(visitor.segmentCount(), uint(3));
+ QCOMPARE(visitor.segmentCount(), uint(4));
QVERIFY(visitor.verifySegment(0, 0,1, Vector3D(0,0,0), Vector3D(1,0,0)));
QVERIFY(visitor.verifySegment(1, 1,2, Vector3D(1,0,0), Vector3D(1,1,0)));
QVERIFY(visitor.verifySegment(2, 2,3, Vector3D(1,1,0), Vector3D(0,1,0)));
+ QVERIFY(visitor.verifySegment(3, 0,1, Vector3D(0,0,0), Vector3D(1,0,0)));
}
void testVisitLineLoop()
@@ -588,12 +594,16 @@ private Q_SLOTS:
simulateInitializationSync(dataBuffer.data(), backendBuffer);
QByteArray indexData;
- indexData.resize(sizeof(uint) * 2 * 4);
+ indexData.resize(sizeof(uint) * 8);
uint *iDataPtr = reinterpret_cast<uint *>(indexData.data());
iDataPtr[0] = 0;
iDataPtr[1] = 1;
iDataPtr[2] = 2;
iDataPtr[3] = 3;
+ iDataPtr[4] = static_cast<uint>(-1);
+ iDataPtr[5] = 0;
+ iDataPtr[6] = 1;
+ iDataPtr[7] = 2;
indexDataBuffer->setData(indexData);
Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id());
@@ -612,7 +622,7 @@ private Q_SLOTS:
indexAttribute->setBuffer(indexDataBuffer.data());
indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedInt);
- indexAttribute->setCount(4);
+ indexAttribute->setCount(8);
indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute);
geometry->addAttribute(positionAttribute.data());
@@ -620,6 +630,8 @@ private Q_SLOTS:
geometryRenderer->setGeometry(geometry);
geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::LineLoop);
+ geometryRenderer->setPrimitiveRestartEnabled(true);
+ geometryRenderer->setRestartIndexValue(-1);
Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id());
backendAttribute->setRenderer(&renderer);
@@ -642,11 +654,14 @@ private Q_SLOTS:
visitor.apply(backendRenderer, Qt3DCore::QNodeId());
// THEN
- QCOMPARE(visitor.segmentCount(), uint(4));
+ QCOMPARE(visitor.segmentCount(), uint(7));
QVERIFY(visitor.verifySegment(0, 0,1, Vector3D(0,0,0), Vector3D(1,0,0)));
QVERIFY(visitor.verifySegment(1, 1,2, Vector3D(1,0,0), Vector3D(1,1,0)));
QVERIFY(visitor.verifySegment(2, 2,3, Vector3D(1,1,0), Vector3D(0,1,0)));
QVERIFY(visitor.verifySegment(3, 3,0, Vector3D(0,1,0), Vector3D(0,0,0)));
+ QVERIFY(visitor.verifySegment(4, 0,1, Vector3D(0,0,0), Vector3D(1,0,0)));
+ QVERIFY(visitor.verifySegment(5, 1,2, Vector3D(1,0,0), Vector3D(1,1,0)));
+ QVERIFY(visitor.verifySegment(6, 2,0, Vector3D(1,1,0), Vector3D(0,0,0)));
}
void testVisitLineAdjacency()
diff --git a/tests/auto/render/sendrendercapturejob/sendrendercapturejob.pro b/tests/auto/render/sendrendercapturejob/sendrendercapturejob.pro
deleted file mode 100644
index 6aff0bebd..000000000
--- a/tests/auto/render/sendrendercapturejob/sendrendercapturejob.pro
+++ /dev/null
@@ -1,12 +0,0 @@
-TEMPLATE = app
-
-TARGET = tst_sendrendercapturejob
-
-QT += core-private 3dcore 3dcore-private 3drender 3drender-private testlib
-
-CONFIG += testcase
-
-SOURCES += tst_sendrendercapturejob.cpp
-
-include(../commons/commons.pri)
-include(../../core/common/common.pri)
diff --git a/tests/auto/render/sendrendercapturejob/tst_sendrendercapturejob.cpp b/tests/auto/render/sendrendercapturejob/tst_sendrendercapturejob.cpp
deleted file mode 100644
index 53a646ccd..000000000
--- a/tests/auto/render/sendrendercapturejob/tst_sendrendercapturejob.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 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: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 <QtTest/QTest>
-#include "Qt3DRender/QRenderAspect"
-#include "Qt3DRender/private/renderer_p.h"
-#include "Qt3DRender/private/nodemanagers_p.h"
-#include "Qt3DRender/private/rendercapture_p.h"
-#include <Qt3DRender/private/sendrendercapturejob_p.h>
-#include "testpostmanarbiter.h"
-
-class tst_SendRenderCaptureJob : public QObject
-{
- Q_OBJECT
-private Q_SLOTS:
- void testSendRenderCaptureRequest()
- {
- // GIVEN
- TestArbiter arbiter;
- Qt3DRender::Render::RenderCapture *renderCapture = new Qt3DRender::Render::RenderCapture;
- Qt3DCore::QBackendNodePrivate::get(renderCapture)->setArbiter(&arbiter);
-
- QImage image(10, 10, QImage::Format_ARGB32);
-
- Qt3DRender::Render::Renderer renderer(Qt3DRender::QRenderAspect::Synchronous);
- Qt3DRender::Render::SendRenderCaptureJob job;
-
- Qt3DRender::Render::NodeManagers nodeManagers;
- nodeManagers.frameGraphManager()->appendNode(renderCapture->peerId(), renderCapture);
- renderer.setNodeManagers(&nodeManagers);
- job.setManagers(&nodeManagers);
-
- renderCapture->requestCapture({ 42, QRect() });
- auto request = renderCapture->takeCaptureRequest();
- renderCapture->addRenderCapture(request.captureId, image);
- renderer.addRenderCaptureSendRequest(renderCapture->peerId());
- job.setPendingCaptureRequests(renderer.takePendingRenderCaptureSendRequests());
-
- //WHEN
- job.run();
-
- //THEN
- QCOMPARE(arbiter.events.count(), 1);
- Qt3DCore::QPropertyUpdatedChangePtr change = arbiter.events.first().staticCast<Qt3DCore::QPropertyUpdatedChange>();
- QCOMPARE(change->subjectId(), renderCapture->peerId());
- QCOMPARE(change->propertyName(), "renderCaptureData");
- auto data = change->value().value<Qt3DRender::RenderCaptureDataPtr>();
- QCOMPARE(data.data()->captureId, 42);
- QCOMPARE(data.data()->image.width(), 10);
- QCOMPARE(data.data()->image.height(), 10);
- QCOMPARE(data.data()->image.format(), QImage::Format_ARGB32);
-
- // renderCapture will be deallocated by the nodeManagers destructor
- renderer.shutdown();
- }
-};
-
-QTEST_APPLESS_MAIN(tst_SendRenderCaptureJob)
-
-#include "tst_sendrendercapturejob.moc"
diff --git a/tests/auto/render/setfence/tst_setfence.cpp b/tests/auto/render/setfence/tst_setfence.cpp
index 92f7a0acc..75c414e7f 100644
--- a/tests/auto/render/setfence/tst_setfence.cpp
+++ b/tests/auto/render/setfence/tst_setfence.cpp
@@ -37,7 +37,9 @@
**
****************************************************************************/
-
+// TODO Remove in Qt6
+#include <QtCore/qcompilerdetection.h>
+QT_WARNING_DISABLE_DEPRECATED
#include <QtTest/QTest>
#include <Qt3DRender/qsetfence.h>
diff --git a/tests/auto/render/shader/tst_shader.cpp b/tests/auto/render/shader/tst_shader.cpp
index d1578aee7..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"\
@@ -79,15 +81,10 @@ 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);
+ QCOMPARE(shader->format(), Qt3DRender::QShaderProgram::GLSL);
+ QVERIFY(shader->log().isEmpty());
+ QCOMPARE(shader->isDirty(), false);
}
void tst_RenderShader::matchesFrontendPeer()
@@ -98,17 +95,17 @@ 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],
frontend->shaderCode(static_cast<Qt3DRender::QShaderProgram::ShaderType>(i)));
+ QCOMPARE(backend.format(), frontend->format());
}
void tst_RenderShader::cleanupLeavesACoherentState()
{
- QScopedPointer<Qt3DRender::QShaderProgram> frontend(createFrontendShader());
+ QScopedPointer<Qt3DRender::QShaderProgram> frontend(createFrontendShader(Qt3DRender::QShaderProgram::SPIRV));
TestRenderer renderer;
Qt3DRender::Render::Shader shader;
@@ -117,15 +114,9 @@ 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);
+ QCOMPARE(shader.format(), Qt3DRender::QShaderProgram::GLSL);
}
void tst_RenderShader::dealWithPropertyChanges_data()
@@ -152,7 +143,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 +153,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 +167,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 +176,48 @@ 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::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()
@@ -221,7 +250,6 @@ void tst_RenderShader::allowToChangeShaderCode()
QFETCH(Qt3DRender::QShaderProgram::ShaderType, type);
Qt3DRender::Render::Shader backend;
- backend.setLoaded(true);
TestRenderer renderer;
backend.setRenderer(&renderer);
@@ -230,30 +258,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/shaderbuilder/tst_shaderbuilder.cpp b/tests/auto/render/shaderbuilder/tst_shaderbuilder.cpp
index 7a08fe018..24dbe514a 100644
--- a/tests/auto/render/shaderbuilder/tst_shaderbuilder.cpp
+++ b/tests/auto/render/shaderbuilder/tst_shaderbuilder.cpp
@@ -560,6 +560,7 @@ private slots:
QVERIFY(!Qt3DRender::Render::ShaderBuilder::getPrototypeNames().isEmpty());
QFETCH(Qt3DRender::QShaderProgram::ShaderType, type);
QFETCH(Qt3DRender::QShaderProgram::ShaderType, notificationType);
+ Q_UNUSED(notificationType)
const auto gl3Api = []{
auto api = Qt3DRender::GraphicsApiFilterData();
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 <QtTest/QTest>
-#include <Qt3DRender/private/shadercache_p.h>
-#include <Qt3DCore/qnodeid.h>
-#include <QtGui/qopenglshaderprogram.h>
-#include <QtCore/qobject.h>
-#include <QtCore/qpointer.h>
-
-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<Qt3DCore::QNodeId> 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<QOpenGLShaderProgram> 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<QOpenGLShaderProgram> progPointerA(shaderProgramA);
-
- auto dnaB = ProgramDNA(67890);
- auto nodeIdB = QNodeId::createId();
- auto shaderProgramB = new QOpenGLShaderProgram;
- QPointer<QOpenGLShaderProgram> 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"
diff --git a/tests/auto/render/skeleton/tst_skeleton.cpp b/tests/auto/render/skeleton/tst_skeleton.cpp
index 6af055fb0..63ed51058 100644
--- a/tests/auto/render/skeleton/tst_skeleton.cpp
+++ b/tests/auto/render/skeleton/tst_skeleton.cpp
@@ -34,9 +34,7 @@
#include <Qt3DCore/qskeletonloader.h>
#include <Qt3DCore/private/qnode_p.h>
#include <Qt3DCore/private/qscene_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qbackendnode_p.h>
-#include <Qt3DCore/private/qpropertyupdatedchangebase_p.h>
#include <qbackendnodetester.h>
#include <testpostmanarbiter.h>
#include <testrenderer.h>
@@ -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<QJoint *> &joints)
-{
- joints.push_back(joint);
- for (const auto child : joint->childJoints())
- linearizeTreeHelper(child, joints);
-}
-
-QVector<QJoint *> linearizeTree(QJoint *rootJoint)
-{
- QVector<QJoint *> 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;
@@ -219,70 +198,6 @@ private Q_SLOTS:
joint->setName(name);
QTest::newRow("inverseBind") << m << localPose << name << joint;
}
-
- void checkCreateFrontendJoints_data()
- {
- QTest::addColumn<SkeletonData>("skeletonData");
- QTest::addColumn<QJoint *>("expectedRootJoint");
-
- QTest::newRow("empty") << SkeletonData() << (QJoint*)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<float>(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<float>(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<float>(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<float>(i);
- childJoint->setTranslation(QVector3D(x, x, x));
- previousJoint->addChildJoint(childJoint);
- previousJoint = childJoint;
- }
-
- QTest::newRow("deep") << skeletonData << rootJoint;
- }
};
QTEST_APPLESS_MAIN(tst_Skeleton)
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 <Qt3DRender/qrenderpass.h>
#include <Qt3DRender/private/qtechnique_p.h>
#include <Qt3DRender/private/technique_p.h>
-#include <Qt3DRender/private/shaderparameterpack_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/managers_p.h>
#include <Qt3DRender/private/filterkey_p.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 <Qt3DCore/private/qtransform_p.h>
#include <Qt3DRender/private/transform_p.h>
#include <Qt3DRender/private/updateworldtransformjob_p.h>
-#include <Qt3DCore/qpropertyupdatedchange.h>
#include <private/qbackendnode_p.h>
#include "qbackendnodetester.h"
#include "testrenderer.h"
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 <Qt3DRender/private/shader_p.h>
#include <Qt3DRender/qshaderprogram.h>
#include <Qt3DRender/private/nodemanagers_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DRender/private/geometryrenderermanager_p.h>
diff --git a/tests/auto/render/trianglevisitor/tst_trianglevisitor.cpp b/tests/auto/render/trianglevisitor/tst_trianglevisitor.cpp
index 8dfda0eea..66f67e08a 100644
--- a/tests/auto/render/trianglevisitor/tst_trianglevisitor.cpp
+++ b/tests/auto/render/trianglevisitor/tst_trianglevisitor.cpp
@@ -454,7 +454,7 @@ private Q_SLOTS:
simulateInitializationSync(dataBuffer.data(), backendBuffer);
QByteArray indexData;
- indexData.resize(sizeof(uint) * 3 * 4);
+ indexData.resize(sizeof(uint) * 4 * 4);
uint *iDataPtr = reinterpret_cast<uint *>(indexData.data());
iDataPtr[0] = 0;
iDataPtr[1] = 1;
@@ -468,6 +468,10 @@ private Q_SLOTS:
iDataPtr[9] = 4;
iDataPtr[10] = 3;
iDataPtr[11] = 2;
+ iDataPtr[12] = static_cast<uint>(-1);
+ iDataPtr[13] = 0;
+ iDataPtr[14] = 1;
+ iDataPtr[15] = 2;
indexDataBuffer->setData(indexData);
Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id());
@@ -486,7 +490,7 @@ private Q_SLOTS:
indexAttribute->setBuffer(indexDataBuffer.data());
indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedInt);
- indexAttribute->setCount(3*4);
+ indexAttribute->setCount(4*4);
indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute);
geometry->addAttribute(positionAttribute.data());
@@ -494,6 +498,8 @@ private Q_SLOTS:
geometryRenderer->setGeometry(geometry);
geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleStrip);
+ geometryRenderer->setPrimitiveRestartEnabled(true);
+ geometryRenderer->setRestartIndexValue(-1);
Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id());
backendAttribute->setRenderer(&renderer);
@@ -516,7 +522,7 @@ private Q_SLOTS:
visitor.apply(backendRenderer, Qt3DCore::QNodeId());
// THEN
- QVERIFY(visitor.triangleCount() == 8);
+ QCOMPARE(visitor.triangleCount(), 9U);
QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1)));
QVERIFY(visitor.verifyTriangle(1, 3,2,1, Vector3D(0,0,1), Vector3D(0,1,0), Vector3D(1,0,0)));
QVERIFY(visitor.verifyTriangle(2, 4,3,2, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(0,1,0)));
@@ -525,6 +531,7 @@ private Q_SLOTS:
QVERIFY(visitor.verifyTriangle(5, 4,0,1, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(1,0,0)));
QVERIFY(visitor.verifyTriangle(6, 3,4,0, Vector3D(0,0,1), Vector3D(1,0,0), Vector3D(0,0,1)));
QVERIFY(visitor.verifyTriangle(7, 2,3,4, Vector3D(0,1,0), Vector3D(0,0,1), Vector3D(1,0,0)));
+ QVERIFY(visitor.verifyTriangle(8, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1)));
}
void testVisitTriangleFan()
@@ -643,7 +650,7 @@ private Q_SLOTS:
simulateInitializationSync(dataBuffer.data(), backendBuffer);
QByteArray indexData;
- indexData.resize(sizeof(uint) * 3 * 2);
+ indexData.resize(sizeof(uint) * 10);
uint *iDataPtr = reinterpret_cast<uint *>(indexData.data());
iDataPtr[0] = 0;
iDataPtr[1] = 1;
@@ -651,6 +658,10 @@ private Q_SLOTS:
iDataPtr[3] = 3;
iDataPtr[4] = 4;
iDataPtr[5] = 5;
+ iDataPtr[6] = static_cast<uint>(-1);
+ iDataPtr[7] = 0;
+ iDataPtr[8] = 1;
+ iDataPtr[9] = 2;
indexDataBuffer->setData(indexData);
Buffer *backendIndexBuffer = nodeManagers->bufferManager()->getOrCreateResource(indexDataBuffer->id());
@@ -669,7 +680,7 @@ private Q_SLOTS:
indexAttribute->setBuffer(indexDataBuffer.data());
indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedInt);
- indexAttribute->setCount(3*2);
+ indexAttribute->setCount(10);
indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute);
geometry->addAttribute(positionAttribute.data());
@@ -677,6 +688,8 @@ private Q_SLOTS:
geometryRenderer->setGeometry(geometry);
geometryRenderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleFan);
+ geometryRenderer->setPrimitiveRestartEnabled(true);
+ geometryRenderer->setRestartIndexValue(-1);
Attribute *backendAttribute = nodeManagers->attributeManager()->getOrCreateResource(positionAttribute->id());
backendAttribute->setRenderer(&renderer);
@@ -699,11 +712,12 @@ private Q_SLOTS:
visitor.apply(backendRenderer, Qt3DCore::QNodeId());
// THEN
- QVERIFY(visitor.triangleCount() == 4);
+ QCOMPARE(visitor.triangleCount(), 5U);
QVERIFY(visitor.verifyTriangle(0, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1)));
QVERIFY(visitor.verifyTriangle(1, 3,2,0, Vector3D(0,0,1), Vector3D(0,1,0), Vector3D(0,0,1)));
QVERIFY(visitor.verifyTriangle(2, 4,3,0, Vector3D(1,0,0), Vector3D(0,0,1), Vector3D(0,0,1)));
QVERIFY(visitor.verifyTriangle(3, 5,4,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1)));
+ QVERIFY(visitor.verifyTriangle(4, 2,1,0, Vector3D(0,1,0), Vector3D(1,0,0), Vector3D(0,0,1)));
}
void testVisitTrianglesAdjacency()
diff --git a/tests/auto/render/uniform/tst_uniform.cpp b/tests/auto/render/uniform/tst_uniform.cpp
index 5f946afa3..d7775eb62 100644
--- a/tests/auto/render/uniform/tst_uniform.cpp
+++ b/tests/auto/render/uniform/tst_uniform.cpp
@@ -112,7 +112,7 @@ private Q_SLOTS:
QCOMPARE(v.constData<float>()[0], 572.0f);
QCOMPARE(v.constData<float>()[1], 355.0f);
QCOMPARE(v.constData<float>()[2], 383.0f);
- QCOMPARE(v.constData<float>()[4], 0.0f);
+ QCOMPARE(v.constData<float>()[3], 0.0f);
}
{
// GIVEN
diff --git a/tests/auto/render/vsyncframeadvanceservice/tst_vsyncframeadvanceservice.cpp b/tests/auto/render/vsyncframeadvanceservice/tst_vsyncframeadvanceservice.cpp
index 1238f1800..aafdb36f7 100644
--- a/tests/auto/render/vsyncframeadvanceservice/tst_vsyncframeadvanceservice.cpp
+++ b/tests/auto/render/vsyncframeadvanceservice/tst_vsyncframeadvanceservice.cpp
@@ -71,7 +71,7 @@ private:
bool isReadyToSubmit()
{
m_submitSemaphore.acquire(1);
- return m_running.load() == 1;
+ return m_running.loadRelaxed() == 1;
}
Qt3DRender::Render::VSyncFrameAdvanceService *m_tickService;
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..85b5e8c89 100644
--- a/tests/benchmarks/render/jobs/tst_bench_jobs.cpp
+++ b/tests/benchmarks/render/jobs/tst_bench_jobs.cpp
@@ -41,7 +41,6 @@
#include <Qt3DRender/qcamera.h>
#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
-#include <Qt3DRender/private/renderer_p.h>
#include <Qt3DRender/private/nodemanagers_p.h>
#include <Qt3DRender/private/updateworldtransformjob_p.h>
#include <Qt3DQuick/QQmlAspectEngine>
@@ -50,6 +49,7 @@
#include <Qt3DCore/private/qaspectmanager_p.h>
#include <Qt3DCore/private/qnodevisitor_p.h>
#include <Qt3DCore/private/qnode_p.h>
+#include <renderer_p.h>
#include <QQmlComponent>
#include <QScopedPointer>
@@ -87,32 +87,32 @@ namespace Qt3DRender {
QVector<Qt3DCore::QAspectJobPtr> worldTransformJob()
{
- static_cast<Render::Renderer *>(d_func()->m_renderer)->m_worldTransformJob->setRoot(d_func()->m_renderer->sceneRoot());
- return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::Renderer *>(d_func()->m_renderer)->m_worldTransformJob;
+ static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_worldTransformJob->setRoot(d_func()->m_renderer->sceneRoot());
+ return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_worldTransformJob;
}
QVector<Qt3DCore::QAspectJobPtr> updateBoundingJob()
{
- static_cast<Render::Renderer *>(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob->setManager(d_func()->m_renderer->nodeManagers()->renderNodesManager());
- return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::Renderer *>(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob;
+ static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob->setManager(d_func()->m_renderer->nodeManagers()->renderNodesManager());
+ return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_updateWorldBoundingVolumeJob;
}
QVector<Qt3DCore::QAspectJobPtr> calculateBoundingVolumeJob()
{
- static_cast<Render::Renderer *>(d_func()->m_renderer)->m_calculateBoundingVolumeJob->setRoot(d_func()->m_renderer->sceneRoot());
- return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::Renderer *>(d_func()->m_renderer)->m_calculateBoundingVolumeJob;
+ static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_calculateBoundingVolumeJob->setRoot(d_func()->m_renderer->sceneRoot());
+ return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_calculateBoundingVolumeJob;
}
QVector<Qt3DCore::QAspectJobPtr> framePreparationJob()
{
- static_cast<Render::Renderer *>(d_func()->m_renderer)->m_updateShaderDataTransformJob->setManagers(d_func()->m_renderer->nodeManagers());
- return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::Renderer *>(d_func()->m_renderer)->m_updateShaderDataTransformJob;
+ static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_updateShaderDataTransformJob->setManagers(d_func()->m_renderer->nodeManagers());
+ return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_updateShaderDataTransformJob;
}
QVector<Qt3DCore::QAspectJobPtr> frameCleanupJob()
{
- static_cast<Render::Renderer *>(d_func()->m_renderer)->m_cleanupJob->setRoot(d_func()->m_renderer->sceneRoot());
- return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::Renderer *>(d_func()->m_renderer)->m_cleanupJob;
+ static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_cleanupJob->setRoot(d_func()->m_renderer->sceneRoot());
+ return QVector<Qt3DCore::QAspectJobPtr>() << static_cast<Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_cleanupJob;
}
QVector<Qt3DCore::QAspectJobPtr> renderBinJobs()
@@ -140,7 +140,7 @@ namespace Qt3DRender {
for (const auto &node: nodes)
d_func()->createBackendNode(node);
- static_cast<Qt3DRender::Render::Renderer *>(d_func()->m_renderer)->m_renderSceneRoot =
+ static_cast<Qt3DRender::Render::OpenGL::Renderer *>(d_func()->m_renderer)->m_renderSceneRoot =
d_func()->m_renderer->nodeManagers()
->lookupResource<Qt3DRender::Render::Entity, Qt3DRender::Render::EntityManager>(root->id());
}
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..340bfdda4 100644
--- a/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp
+++ b/tests/benchmarks/render/materialparametergathering/tst_bench_materialparametergathering.cpp
@@ -37,7 +37,7 @@
#include <Qt3DRender/private/entity_p.h>
#include <Qt3DRender/qrenderaspect.h>
#include <Qt3DRender/private/qrenderaspect_p.h>
-#include <Qt3DRender/private/materialparametergathererjob_p.h>
+#include <materialparametergathererjob_p.h>
#include <Qt3DRender/private/technique_p.h>
#include <Qt3DRender/private/techniquemanager_p.h>
#include <Qt3DExtras/qphongmaterial.h>
@@ -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<Qt3DRender::TestAspect> 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 {
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 @@
+<RCC>
+ <qresource prefix="/">
+ <file>main.qml</file>
+ <file>ComputeFrameGraph.qml</file>
+ <file>ComputeMaterial.qml</file>
+ <file>particles.frag</file>
+ <file>particles.vert</file>
+ <file>ParticlesScene.qml</file>
+ <file>particles.comp</file>
+ </qresource>
+</RCC>
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 <QGuiApplication>
+#include <QQuickView>
+
+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-renderloop/main.cpp b/tests/manual/manual-renderloop/main.cpp
new file mode 100644
index 000000000..f2a49cb86
--- /dev/null
+++ b/tests/manual/manual-renderloop/main.cpp
@@ -0,0 +1,211 @@
+/****************************************************************************
+**
+** 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 <QGuiApplication>
+#include <QTimer>
+#include <QOpenGLContext>
+#include <QWindow>
+#include <qmath.h>
+
+#include <Qt3DCore/QNode>
+#include <Qt3DCore/QEntity>
+#include <Qt3DCore/QTransform>
+#include <Qt3DCore/QAspectEngine>
+
+#include <Qt3DExtras/QTorusMesh>
+#include <Qt3DExtras/QForwardRenderer>
+#include <Qt3DExtras/QPhongMaterial>
+
+#include <Qt3DRender/QCamera>
+#include <Qt3DRender/QCameraLens>
+#include <Qt3DRender/QCameraSelector>
+#include <Qt3DRender/QMesh>
+#include <Qt3DRender/QPointLight>
+#include <Qt3DRender/QRenderAspect>
+#include <Qt3DRender/QRenderSettings>
+#include <Qt3DRender/QRenderSurfaceSelector>
+#include <Qt3DRender/private/qrenderaspect_p.h>
+
+
+class ManualRenderer
+{
+public:
+ ManualRenderer()
+ : m_aspectEngine(new Qt3DCore::QAspectEngine())
+ , m_renderAspect(new Qt3DRender::QRenderAspect(Qt3DRender::QRenderAspect::Synchronous))
+ {
+ }
+
+ ~ManualRenderer() {
+ m_aspectEngine->setRootEntity(Qt3DCore::QEntityPtr());
+ m_aspectEngine->unregisterAspect(m_renderAspect);
+ delete m_renderAspect;
+ delete m_aspectEngine;
+ }
+
+ void initialize(QWindow *window, QOpenGLContext *glCtx)
+ {
+ m_aspectEngine->registerAspect(m_renderAspect);
+ m_aspectEngine->setRunMode(Qt3DCore::QAspectEngine::Manual);
+
+ Qt3DRender::QRenderAspectPrivate *dRenderAspect = static_cast<decltype(dRenderAspect)>
+ (Qt3DRender::QRenderAspectPrivate::get(m_renderAspect));
+ dRenderAspect->renderInitialize(glCtx);
+
+ m_rootEntity.reset(createSceneTree(window));
+ m_aspectEngine->setRootEntity(m_rootEntity);
+ }
+
+ void render() {
+ qDebug() << Q_FUNC_INFO << "Updating Scene";
+ updateScene();
+ qDebug() << Q_FUNC_INFO << "Processing Frame";
+ // Launch jobs to process the frame
+ m_aspectEngine->processFrame();
+ qDebug() << Q_FUNC_INFO << "Rendering Frame";
+ // Submit Render Queues
+ Qt3DRender::QRenderAspectPrivate *dRenderAspect = static_cast<decltype(dRenderAspect)>
+ (Qt3DRender::QRenderAspectPrivate::get(m_renderAspect));
+ dRenderAspect->renderSynchronous(true);
+ }
+
+private:
+ Qt3DCore::QEntity *createSceneTree(QWindow *surface) {
+ // Root entity in the 3D scene.
+ Qt3DCore::QEntity *rootEntity = new Qt3DCore::QEntity;
+ auto camera = new Qt3DRender::QCamera(rootEntity);
+ camera->lens()->setPerspectiveProjection(45.0f, 16.0f/9.0f, 0.1f, 1000.0f);
+ camera->setPosition(QVector3D(0, 0, 40.0f));
+ camera->setViewCenter(QVector3D(0, 0, 0));
+
+ // Torus
+ Qt3DCore::QEntity *torusEntity = new Qt3DCore::QEntity(rootEntity);
+ auto material = new Qt3DExtras::QPhongMaterial(rootEntity);
+ auto torusTransform = new Qt3DCore::QTransform;
+ auto torusMesh = new Qt3DExtras::QTorusMesh;
+
+ torusMesh->setRadius(5);
+ torusMesh->setMinorRadius(1);
+ torusMesh->setRings(100);
+ torusMesh->setSlices(20);
+
+ torusTransform->setScale3D(QVector3D(1.5, 1, 0.5));
+ torusTransform->setRotation(QQuaternion::fromAxisAndAngle(QVector3D(1, 0, 0), 45.0f));
+
+ torusEntity->addComponent(torusMesh);
+ torusEntity->addComponent(material);
+ torusEntity->addComponent(torusTransform);
+
+ // FrameGraph
+ auto forwardRenderer = new Qt3DExtras::QForwardRenderer();
+ forwardRenderer->setSurface(surface);
+ forwardRenderer->setCamera(camera);
+ forwardRenderer->setClearColor(QColor(Qt::black));
+
+ auto renderSettings = new Qt3DRender::QRenderSettings();
+ renderSettings->setActiveFrameGraph(forwardRenderer);
+ rootEntity->addComponent(renderSettings);
+
+ return rootEntity;
+ }
+
+ void updateScene()
+ {
+ static int angle = 0;
+ // Update camera position
+ auto camera = m_rootEntity->findChild<Qt3DRender::QCamera *>();
+ Q_ASSERT(camera);
+
+ const double angleRad = qDegreesToRadians(double(angle));
+ const QVector3D newPos(qSin(angleRad), 0.0, qCos(angleRad));
+ camera->setPosition(newPos * 40.0f);
+
+ qDebug() << Q_FUNC_INFO << "Camera Transform Matrix" << camera->transform()->matrix();
+ qDebug() << Q_FUNC_INFO << "Camera ViewMatrix" << camera->viewMatrix();
+
+ angle = (angle + 1) % 360;
+ }
+
+ Qt3DCore::QEntityPtr m_rootEntity;
+ Qt3DCore::QAspectEngine *m_aspectEngine;
+ Qt3DRender::QRenderAspect *m_renderAspect;
+};
+
+int main(int ac, char **av)
+{
+ QSurfaceFormat format = QSurfaceFormat::defaultFormat();
+#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);
+
+ QGuiApplication app(ac, av);
+
+ QWindow win;
+ win.setSurfaceType(QSurface::OpenGLSurface);
+ win.resize(1024, 768);
+ win.setFormat(format);
+ win.show();
+
+ QOpenGLContext ctx;
+ ctx.setFormat(format);
+ const bool ctxCreated = ctx.create();
+
+ if (!ctxCreated) {
+ qWarning() << "Failed to create GL context";
+ return -1;
+ }
+
+ ManualRenderer renderer;
+ renderer.initialize(&win, &ctx);
+
+ QTimer t;
+ QObject::connect(&t, &QTimer::timeout, [&] { renderer.render(); });
+ t.start(16);
+
+ return app.exec();
+}
diff --git a/tests/manual/manual-renderloop/manual-renderloop.pro b/tests/manual/manual-renderloop/manual-renderloop.pro
new file mode 100644
index 000000000..d126a48c5
--- /dev/null
+++ b/tests/manual/manual-renderloop/manual-renderloop.pro
@@ -0,0 +1,8 @@
+!include( ../manual.pri ) {
+ error( "Couldn't find the manual.pri file!" )
+}
+
+QT += 3dcore 3drender 3drender-private 3dinput 3dextras
+
+SOURCES += \
+ main.cpp
diff --git a/tests/manual/manual.pro b/tests/manual/manual.pro
index 1182886d3..2f630e0d9 100644
--- a/tests/manual/manual.pro
+++ b/tests/manual/manual.pro
@@ -67,7 +67,13 @@ SUBDIRS += \
qtbug-76766 \
shader-image-qml \
scene3d-in-sync \
- compressed_textures
+ compressed_textures \
+ subtree-enabler-qml \
+ scene3d-visibility \
+ manual-renderloop
+
+!macos:!uikit: SUBDIRS += compute-manual
+
qtHaveModule(multimedia): {
SUBDIRS += \
diff --git a/tests/manual/rendercapture-qml/main.qml b/tests/manual/rendercapture-qml/main.qml
index 9aff1fefe..98b24e251 100644
--- a/tests/manual/rendercapture-qml/main.qml
+++ b/tests/manual/rendercapture-qml/main.qml
@@ -50,7 +50,7 @@
import QtQuick 2.2
import QtQuick.Layouts 1.3
-import QtQuick.Controls 1.4
+import QtQuick.Controls 2.12
import Qt3D.Render 2.9
import QtQuick.Scene3D 2.0
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 <QGuiApplication>
+#include <QQuickView>
+
+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 @@
+<RCC>
+ <qresource prefix="/">
+ <file>main.qml</file>
+ </qresource>
+</RCC>
diff --git a/tests/manual/sharedtexture/main.cpp b/tests/manual/sharedtexture/main.cpp
index a85f90ee6..6f2ef42f2 100644
--- a/tests/manual/sharedtexture/main.cpp
+++ b/tests/manual/sharedtexture/main.cpp
@@ -137,8 +137,7 @@ int main(int argc, char* argv[])
// Multimedia player
TextureWidget textureWidget;
- VideoPlayerThread *videoPlayer = new VideoPlayerThread(&textureWidget);
- videoPlayer->start();
+ VideoPlayer *videoPlayer = new VideoPlayer(&textureWidget);
textureWidget.resize(800, 600);
textureWidget.show();
diff --git a/tests/manual/sharedtexture/videoplayer.cpp b/tests/manual/sharedtexture/videoplayer.cpp
index f970116b5..2e52b85e0 100644
--- a/tests/manual/sharedtexture/videoplayer.cpp
+++ b/tests/manual/sharedtexture/videoplayer.cpp
@@ -57,8 +57,6 @@ TextureWidget::TextureWidget(QWidget *parent)
: QOpenGLWidget(parent)
, m_texture(QOpenGLTexture::Target2D)
{
- // Lock mutex so that we never process a frame until we have been initialized
- m_mutex.lock();
}
// Main thread
@@ -104,14 +102,11 @@ void TextureWidget::initializeGL()
qDebug() << Q_FUNC_INFO << context()->shareContext();
m_vao.create();
- // Allow rendering/frame acquisition to go on
- m_mutex.unlock();
}
// Main thread
void TextureWidget::paintGL()
{
- QMutexLocker lock(&m_mutex);
glViewport(0, 0, width(), height());
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
@@ -131,12 +126,8 @@ void TextureWidget::paintGL()
m_shader.release();
}
-// Video Player thread
void TextureWidget::setVideoFrame(const QVideoFrame &frame)
{
- // Ensure we won't be rendering while we are processing the frame
- QMutexLocker lock(&m_mutex);
-
QVideoFrame f = frame;
// Map frame
@@ -194,16 +185,14 @@ bool GLVideoSurface::present(const QVideoFrame &frame)
return true;
}
-VideoPlayerThread::VideoPlayerThread(TextureWidget *textureWidget)
- : QThread(textureWidget)
+VideoPlayer::VideoPlayer(TextureWidget *textureWidget)
+ : QObject(textureWidget)
, m_player(new QMediaPlayer(nullptr, QMediaPlayer::VideoSurface))
, m_surface(new GLVideoSurface())
{
- m_player->moveToThread(this);
- m_player->setMedia(QUrl("https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4"));
+ m_player->setMedia(QUrl("https://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"));
// Tell player to render on GLVideoSurface
- m_surface->moveToThread(this);
m_player->setVideoOutput(m_surface.get());
// Display errors
@@ -218,16 +207,13 @@ VideoPlayerThread::VideoPlayerThread(TextureWidget *textureWidget)
m_player->play();
});
- // Start playing when thread starts
- QObject::connect(this, &QThread::started, this, [this] { m_player->play(); });
-
- // Direct connection between 2 objects living in different threads
QObject::connect(m_surface.get(), &GLVideoSurface::onNewFrame,
textureWidget, &TextureWidget::setVideoFrame, Qt::DirectConnection);
+
+ // Start playing
+ m_player->play();
}
-VideoPlayerThread::~VideoPlayerThread()
+VideoPlayer::~VideoPlayer()
{
- exit(0);
- wait();
}
diff --git a/tests/manual/sharedtexture/videoplayer.h b/tests/manual/sharedtexture/videoplayer.h
index 377ea57fe..a96cb16b1 100644
--- a/tests/manual/sharedtexture/videoplayer.h
+++ b/tests/manual/sharedtexture/videoplayer.h
@@ -48,9 +48,6 @@
**
****************************************************************************/
-#include <QThread>
-#include <QMutex>
-
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLVertexArrayObject>
@@ -90,7 +87,6 @@ private:
QOpenGLVertexArrayObject m_vao;
QOpenGLShaderProgram m_shader;
QOpenGLTexture m_texture;
- QMutex m_mutex;
};
@@ -108,12 +104,12 @@ Q_SIGNALS:
};
-class VideoPlayerThread : public QThread
+class VideoPlayer : public QObject
{
Q_OBJECT
public:
- VideoPlayerThread(TextureWidget *textureWidget);
- ~VideoPlayerThread();
+ VideoPlayer(TextureWidget *textureWidget);
+ ~VideoPlayer();
private:
TextureWidget *m_textureWidget;
diff --git a/tests/manual/sharedtextureqml/main.cpp b/tests/manual/sharedtextureqml/main.cpp
index 5c7ae9cff..c0a79e6f8 100644
--- a/tests/manual/sharedtextureqml/main.cpp
+++ b/tests/manual/sharedtextureqml/main.cpp
@@ -108,8 +108,7 @@ int main(int argc, char* argv[])
// Multimedia player
TextureWidget textureWidget;
- VideoPlayerThread *videoPlayer = new VideoPlayerThread(&textureWidget);
- videoPlayer->start();
+ VideoPlayer *videoPlayer = new VideoPlayer(&textureWidget);
textureWidget.resize(800, 600);
textureWidget.show();
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 <Qt3DQuickExtras/qt3dquickwindow.h>
+#include <QGuiApplication>
+
+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 @@
+<RCC>
+ <qresource prefix="/">
+ <file>main.qml</file>
+ <file>FrameGraph.qml</file>
+ <file>SimpleCamera.qml</file>
+ </qresource>
+</RCC>
diff --git a/tools/qgltf/qgltf.cpp b/tools/qgltf/qgltf.cpp
index 814ae7e27..71cdb6b5e 100644
--- a/tools/qgltf/qgltf.cpp
+++ b/tools/qgltf/qgltf.cpp
@@ -2449,10 +2449,16 @@ void GltfExporter::save(const QString &inputFilename)
QString gltfName = opts.outDir + basename + QStringLiteral(".qgltf");
f.setFileName(gltfName);
+
if (opts.showLog)
qDebug().noquote() << "Writing" << gltfName;
- if (f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
+ const QIODevice::OpenMode openMode
+ = QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text;
+ const QByteArray json
+ = m_doc.toJson(opts.compact ? QJsonDocument::Compact : QJsonDocument::Indented);
+
+ if (f.open(openMode)) {
m_files.insert(QFileInfo(f.fileName()).fileName());
QByteArray json = m_doc.toJson(opts.compact ? QJsonDocument::Compact : QJsonDocument::Indented);
f.write(json);
@@ -2499,6 +2505,10 @@ int main(int argc, char **argv)
cmdLine.setApplicationDescription(QString::fromUtf8(description));
QCommandLineOption outDirOpt(QStringLiteral("d"), QStringLiteral("Place all output data into <dir>"), QStringLiteral("dir"));
cmdLine.addOption(outDirOpt);
+#ifndef QT_BOOTSTRAPPED
+ QCommandLineOption binOpt(QStringLiteral("b"), QStringLiteral("Store binary JSON data in the .qgltf file"));
+ cmdLine.addOption(binOpt);
+#endif
QCommandLineOption compactOpt(QStringLiteral("m"), QStringLiteral("Store compact JSON in the .qgltf file"));
cmdLine.addOption(compactOpt);
QCommandLineOption compOpt(QStringLiteral("c"), QStringLiteral("qCompress() vertex/index data in the .bin file"));
diff --git a/tools/utils/exporters/blender/qt3d_animation_export.py b/tools/utils/exporters/blender/qt3d_animation_export.py
index b1987ea95..1e2909c1a 100644
--- a/tools/utils/exporters/blender/qt3d_animation_export.py
+++ b/tools/utils/exporters/blender/qt3d_animation_export.py
@@ -41,8 +41,8 @@
bl_info = {
"name": "Qt3D Animation Exporter",
"author": "Sean Harmer <sean.harmer@kdab.com>, Paul Lemire <paul.lemire@kdab.com>",
- "version": (0, 4),
- "blender": (2, 72, 0),
+ "version": (0, 5),
+ "blender": (2, 80, 0),
"location": "File > Export > Qt3D Animation (.json)",
"description": "Export animations to json to use with Qt3D",
"warning": "",
@@ -426,11 +426,17 @@ def createBlenderMenu(self, context):
# Register against Blender
def register():
bpy.utils.register_class(Qt3DExporter)
- bpy.types.INFO_MT_file_export.append(createBlenderMenu)
+ if bpy.app.version < (2, 80, 0):
+ bpy.types.INFO_MT_file_export.append(createBlenderMenu)
+ else:
+ bpy.types.TOPBAR_MT_file_export.append(createBlenderMenu)
def unregister():
bpy.utils.unregister_class(Qt3DExporter)
- bpy.types.INFO_MT_file_export.remove(createBlenderMenu)
+ if bpy.app.version < (2, 80, 0):
+ bpy.types.INFO_MT_file_export.remove(createBlenderMenu)
+ else:
+ bpy.types.TOPBAR_MT_file_export.remove(createBlenderMenu)
# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):
diff --git a/tools/utils/exporters/blender/qt3d_armature_export.py b/tools/utils/exporters/blender/qt3d_armature_export.py
index de5583220..cea28ad5e 100644
--- a/tools/utils/exporters/blender/qt3d_armature_export.py
+++ b/tools/utils/exporters/blender/qt3d_armature_export.py
@@ -41,8 +41,8 @@
bl_info = {
"name": "Qt3D Armature Exporter",
"author": "Sean Harmer <sean.harmer@kdab.com>, Robert Brock <robert.brock@kdab.com>",
- "version": (0, 1),
- "blender": (2, 78, 0),
+ "version": (0, 2),
+ "blender": (2, 80, 0),
"location": "File > Export > Qt3D Armature Exporter (.json)",
"description": "Export Armature to json to use with Qt3D",
"warning": "",
@@ -75,6 +75,9 @@ def jsonBuilder():
ob = bpy.context.object.data
+ if not hasattr(ob, 'bones'):
+ return bonesList
+
for bone in ob.bones:
#check parent exists
@@ -146,11 +149,17 @@ def createBlenderMenu(self, context):
# Register against Blender
def register():
bpy.utils.register_class(Qt3DArmatureExporter)
- bpy.types.INFO_MT_file_export.append(createBlenderMenu)
+ if bpy.app.version < (2, 80, 0):
+ bpy.types.INFO_MT_file_export.append(createBlenderMenu)
+ else:
+ bpy.types.TOPBAR_MT_file_export.append(createBlenderMenu)
def unregister():
bpy.utils.unregister_class(Qt3DArmatureExporter)
- bpy.types.INFO_MT_file_export.remove(createBlenderMenu)
+ if bpy.app.version < (2, 80, 0):
+ bpy.types.INFO_MT_file_export.remove(createBlenderMenu)
+ else:
+ bpy.types.TOPBAR_MT_file_export.remove(createBlenderMenu)
# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):
diff --git a/tools/utils/exporters/blender/qt3d_path_export.py b/tools/utils/exporters/blender/qt3d_path_export.py
index 7c42fac9a..edb1bc8fa 100644
--- a/tools/utils/exporters/blender/qt3d_path_export.py
+++ b/tools/utils/exporters/blender/qt3d_path_export.py
@@ -41,8 +41,8 @@
bl_info = {
"name": "Qt3D Path Exporter",
"author": "Sean Harmer <sean.harmer@kdab.com>, Robert Brock <robert.brock@kdab.com>",
- "version": (0, 1),
- "blender": (2, 78, 0),
+ "version": (0, 2),
+ "blender": (2, 80, 0),
"location": "File > Export > Qt3D Path Exporter (.json)",
"description": "Export path to json to use with Qt3D",
"warning": "",
@@ -73,6 +73,9 @@ def jsonBuilder():
obj = bpy.context.object
curve = obj.data
+ if not hasattr(curve, 'splines'):
+ return pathList
+
spline = curve.splines.active
for point in spline.points:
@@ -93,7 +96,7 @@ class Qt3DPathDataConverter:
return jsonData
-class Qt3DTDPathExporter(bpy.types.Operator, ExportHelper):
+class Qt3DPathExporter(bpy.types.Operator, ExportHelper):
"""Qt3D Exporter"""
bl_idname = "export_scene.qt3d_td_path_exporter";
bl_label = "Qt3DPathExporter";
@@ -126,11 +129,17 @@ def createBlenderMenu(self, context):
# Register against Blender
def register():
bpy.utils.register_class(Qt3DPathExporter)
- bpy.types.INFO_MT_file_export.append(createBlenderMenu)
+ if bpy.app.version < (2, 80, 0):
+ bpy.types.INFO_MT_file_export.append(createBlenderMenu)
+ else:
+ bpy.types.TOPBAR_MT_file_export.append(createBlenderMenu)
def unregister():
bpy.utils.unregister_class(Qt3DPathExporter)
- bpy.types.INFO_MT_file_export.remove(createBlenderMenu)
+ if bpy.app.version < (2, 80, 0):
+ bpy.types.INFO_MT_file_export.remove(createBlenderMenu)
+ else:
+ bpy.types.TOPBAR_MT_file_export.remove(createBlenderMenu)
# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):