aboutsummaryrefslogtreecommitdiff
path: root/NvCloth/samples
diff options
context:
space:
mode:
authormtamis <[email protected]>2017-02-28 18:24:59 +0100
committermtamis <[email protected]>2017-02-28 18:24:59 +0100
commit5581909a4d19db97304449f66404ff99a0429d3f (patch)
treea90f7eb85c095a8aba45cf5e909c82c1cdbed77d /NvCloth/samples
parentFix cmake visual studio project generation (locate_gw_root.bat) (diff)
downloadnvcloth-5581909a4d19db97304449f66404ff99a0429d3f.tar.xz
nvcloth-5581909a4d19db97304449f66404ff99a0429d3f.zip
Add visual samples.
Diffstat (limited to 'NvCloth/samples')
-rw-r--r--NvCloth/samples/CMakeLists.txt82
-rw-r--r--NvCloth/samples/CmakeGenerateProjects.bat46
-rw-r--r--NvCloth/samples/SampleBase/Main.cpp34
-rw-r--r--NvCloth/samples/SampleBase/Sample.h26
-rw-r--r--NvCloth/samples/SampleBase/core/Application.cpp73
-rw-r--r--NvCloth/samples/SampleBase/core/Application.h55
-rw-r--r--NvCloth/samples/SampleBase/core/DeviceManager.cpp795
-rw-r--r--NvCloth/samples/SampleBase/core/DeviceManager.h166
-rw-r--r--NvCloth/samples/SampleBase/core/SampleController.cpp25
-rw-r--r--NvCloth/samples/SampleBase/core/SampleController.h42
-rw-r--r--NvCloth/samples/SampleBase/core/SampleManager.cpp60
-rw-r--r--NvCloth/samples/SampleBase/core/SampleManager.h91
-rw-r--r--NvCloth/samples/SampleBase/renderer/ClothRenderMesh.cpp211
-rw-r--r--NvCloth/samples/SampleBase/renderer/ClothRenderMesh.h68
-rw-r--r--NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.cpp84
-rw-r--r--NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.h34
-rw-r--r--NvCloth/samples/SampleBase/renderer/CustomRenderMesh.cpp98
-rw-r--r--NvCloth/samples/SampleBase/renderer/CustomRenderMesh.h43
-rw-r--r--NvCloth/samples/SampleBase/renderer/DebugRenderBuffer.h50
-rw-r--r--NvCloth/samples/SampleBase/renderer/Mesh.cpp13
-rw-r--r--NvCloth/samples/SampleBase/renderer/Mesh.h51
-rw-r--r--NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.cpp205
-rw-r--r--NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.h61
-rw-r--r--NvCloth/samples/SampleBase/renderer/PxPhysXCommonConfig.h92
-rw-r--r--NvCloth/samples/SampleBase/renderer/PxRenderBuffer.h157
-rw-r--r--NvCloth/samples/SampleBase/renderer/RenderMaterial.cpp206
-rw-r--r--NvCloth/samples/SampleBase/renderer/RenderMaterial.h118
-rw-r--r--NvCloth/samples/SampleBase/renderer/RenderUtils.h78
-rw-r--r--NvCloth/samples/SampleBase/renderer/Renderable.cpp48
-rw-r--r--NvCloth/samples/SampleBase/renderer/Renderable.h128
-rw-r--r--NvCloth/samples/SampleBase/renderer/Renderer.cpp730
-rw-r--r--NvCloth/samples/SampleBase/renderer/Renderer.h247
-rw-r--r--NvCloth/samples/SampleBase/renderer/RendererHBAO.cpp81
-rw-r--r--NvCloth/samples/SampleBase/renderer/RendererHBAO.h40
-rw-r--r--NvCloth/samples/SampleBase/renderer/RendererShadow.cpp417
-rw-r--r--NvCloth/samples/SampleBase/renderer/RendererShadow.h82
-rw-r--r--NvCloth/samples/SampleBase/renderer/ResourceManager.cpp210
-rw-r--r--NvCloth/samples/SampleBase/renderer/ResourceManager.h93
-rw-r--r--NvCloth/samples/SampleBase/renderer/ShaderUtils.h98
-rw-r--r--NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.cpp217
-rw-r--r--NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.h82
-rw-r--r--NvCloth/samples/SampleBase/scene/Scene.cpp162
-rw-r--r--NvCloth/samples/SampleBase/scene/Scene.h104
-rw-r--r--NvCloth/samples/SampleBase/scene/SceneController.cpp250
-rw-r--r--NvCloth/samples/SampleBase/scene/SceneController.h128
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.cpp116
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.h33
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/FrictionScene.cpp119
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/FrictionScene.h33
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/SimpleScene.cpp94
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/SimpleScene.h32
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/TetherScene.cpp103
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/TetherScene.h36
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/WindScene.cpp124
-rw-r--r--NvCloth/samples/SampleBase/scene/scenes/WindScene.h37
-rw-r--r--NvCloth/samples/SampleBase/ui/CommonUIController.cpp467
-rw-r--r--NvCloth/samples/SampleBase/ui/CommonUIController.h91
-rw-r--r--NvCloth/samples/SampleBase/ui/imgui_impl_dx11.cpp583
-rw-r--r--NvCloth/samples/SampleBase/ui/imgui_impl_dx11.h25
-rw-r--r--NvCloth/samples/SampleBase/utils/CallbackImplementations.cpp110
-rw-r--r--NvCloth/samples/SampleBase/utils/CallbackImplementations.h230
-rw-r--r--NvCloth/samples/SampleBase/utils/ClothMeshGenerator.cpp193
-rw-r--r--NvCloth/samples/SampleBase/utils/ClothMeshGenerator.h54
-rw-r--r--NvCloth/samples/SampleBase/utils/JobManager.cpp136
-rw-r--r--NvCloth/samples/SampleBase/utils/JobManager.h175
-rw-r--r--NvCloth/samples/SampleBase/utils/SampleProfiler.cpp223
-rw-r--r--NvCloth/samples/SampleBase/utils/SampleProfiler.h79
-rw-r--r--NvCloth/samples/SampleBase/utils/SampleTime.h58
-rw-r--r--NvCloth/samples/SampleBase/utils/UIHelpers.h56
-rw-r--r--NvCloth/samples/SampleBase/utils/Utils.cpp13
-rw-r--r--NvCloth/samples/SampleBase/utils/Utils.h89
-rw-r--r--NvCloth/samples/compiler/cmake/SampleBase.cmake193
-rw-r--r--NvCloth/samples/compiler/cmake/windows/CMakeLists.txt82
-rw-r--r--NvCloth/samples/compiler/cmake/windows/SampleBase-AT.cmake7
-rw-r--r--NvCloth/samples/compiler/cmake/windows/SampleBase.cmake45
-rw-r--r--NvCloth/samples/external/CMakeModules/FindDXUT.cmake82
-rw-r--r--NvCloth/samples/external/CMakeModules/FindDirectXTex.cmake66
-rw-r--r--NvCloth/samples/external/CMakeModules/FindPxShared.cmake20
-rw-r--r--NvCloth/samples/external/CMakeModules/Findimgui.cmake44
-rw-r--r--NvCloth/samples/external/CMakeModules/FindnvToolsExt.cmake65
-rw-r--r--NvCloth/samples/external/CMakeModules/SetOutputPaths.cmake95
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/DXUT.libbin0 -> 5459858 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/dxut.pdbbin0 -> 3133440 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/DXUT.libbin0 -> 6150762 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/dxut.pdbbin0 -> 3067904 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/DXUT.libbin0 -> 4043258 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/dxut.pdbbin0 -> 3166208 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/DXUT.libbin0 -> 6151380 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/dxut.pdbbin0 -> 3100672 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.libbin0 -> 5778482 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.pdbbin0 -> 3289088 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.libbin0 -> 6779052 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.pdbbin0 -> 3215360 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.libbin0 -> 4454714 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.pdbbin0 -> 3321856 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.libbin0 -> 6782810 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.pdbbin0 -> 3239936 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/DXUT.libbin0 -> 5460546 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/dxut.pdbbin0 -> 3133440 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/DXUT.libbin0 -> 6151268 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/dxut.pdbbin0 -> 3067904 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/DXUT.libbin0 -> 4029918 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/dxut.pdbbin0 -> 3166208 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/DXUT.libbin0 -> 6151860 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/dxut.pdbbin0 -> 3092480 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.libbin0 -> 5749176 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.pdbbin0 -> 3289088 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.libbin0 -> 6779050 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.pdbbin0 -> 3215360 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.libbin0 -> 4455070 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.pdbbin0 -> 3321856 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.libbin0 -> 6783344 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.pdbbin0 -> 3239936 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/DDSTextureLoader.h133
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUT.h341
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTDevice11.h210
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTmisc.h298
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/ScreenGrab.h43
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/WICTextureLoader.h123
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Core/dxerr.h76
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/DXUTOpt.libbin0 -> 4029542 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/dxutopt.pdbbin0 -> 3215360 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/DXUTOpt.libbin0 -> 4029542 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/dxutopt.pdbbin0 -> 3215360 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/DXUTOpt.libbin0 -> 5068392 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/dxutopt.pdbbin0 -> 3158016 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/DXUTOpt.libbin0 -> 4579914 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/dxutopt.pdbbin0 -> 3248128 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/DXUTOpt.libbin0 -> 5079816 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/dxutopt.pdbbin0 -> 3190784 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.libbin0 -> 4464766 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.pdbbin0 -> 3403776 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.libbin0 -> 5909308 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.pdbbin0 -> 3321856 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.libbin0 -> 5130814 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.pdbbin0 -> 3428352 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.libbin0 -> 5937132 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.pdbbin0 -> 3354624 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/DXUTOpt.libbin0 -> 4030314 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/dxutopt.pdbbin0 -> 3215360 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/DXUTOpt.libbin0 -> 5068966 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/dxutopt.pdbbin0 -> 3158016 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/DXUTOpt.libbin0 -> 4570706 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/dxutopt.pdbbin0 -> 3248128 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/DXUTOpt.libbin0 -> 5080374 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/dxutopt.pdbbin0 -> 3190784 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.libbin0 -> 4437140 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.pdbbin0 -> 3403776 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.libbin0 -> 5909378 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.pdbbin0 -> 3321856 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.libbin0 -> 5131226 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.pdbbin0 -> 3428352 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.libbin0 -> 5937738 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.pdbbin0 -> 3354624 bytes
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTLockFreePipe.h226
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTcamera.h426
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTgui.h1125
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTguiIME.h141
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTres.h17
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTsettingsdlg.h173
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/ImeUi.h126
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmesh.h460
-rw-r--r--NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmisc.h134
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/DirectXTex.libbin0 -> 3669138 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/directxtex.pdbbin0 -> 2019328 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/DirectXTex.libbin0 -> 2528314 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/directxtex.pdbbin0 -> 1970176 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/DirectXTex.libbin0 -> 4075102 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/directxtex.pdbbin0 -> 2052096 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/DirectXTex.libbin0 -> 2761942 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/directxtex.pdbbin0 -> 1994752 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.libbin0 -> 3890820 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.pdbbin0 -> 2117632 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.libbin0 -> 2612246 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.pdbbin0 -> 2060288 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.libbin0 -> 4347448 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.pdbbin0 -> 2134016 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.libbin0 -> 2850202 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.pdbbin0 -> 2076672 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/DirectXTex.libbin0 -> 3636486 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/directxtex.pdbbin0 -> 2019328 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/DirectXTex.libbin0 -> 2521686 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/directxtex.pdbbin0 -> 1970176 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/DirectXTex.libbin0 -> 4076182 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/directxtex.pdbbin0 -> 2052096 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/DirectXTex.libbin0 -> 2762934 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/directxtex.pdbbin0 -> 1994752 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.libbin0 -> 3854162 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.pdbbin0 -> 2117632 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.libbin0 -> 2608060 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.pdbbin0 -> 2060288 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.libbin0 -> 4348528 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.pdbbin0 -> 2134016 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.libbin0 -> 2851230 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.pdbbin0 -> 2076672 bytes
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BC.h891
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BCDirectCompute.h67
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DDS.h243
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.h636
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.inl130
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTexP.h230
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/Filters.h422
-rw-r--r--NvCloth/samples/external/DirectXTex/10.5.2016.2/include/scoped.h32
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaContextManager.h425
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaMemoryManager.h281
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDesc.h86
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDescQueue.h149
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/Px.h92
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAllocatorCallback.h95
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAssert.h95
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBitAndData.h87
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBounds3.h480
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrorCallback.h73
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrors.h93
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFlags.h375
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundation.h147
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundationVersion.h65
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIO.h138
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIntrinsics.h47
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat33.h396
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat44.h376
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMath.h338
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMathUtils.h73
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMemory.h110
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPlane.h145
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPreprocessor.h536
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxProfiler.h116
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxQuat.h403
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxSimpleTypes.h112
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxStrideIterator.h353
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxTransform.h215
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxUnionCast.h64
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec2.h347
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec3.h393
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec4.h376
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/nx/PxNXIntrinsics.h138
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/unix/PxUnixIntrinsics.h181
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsFoundationDelayLoadHook.h71
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsIntrinsics.h188
-rw-r--r--NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/xboxone/PxXboxOneIntrinsics.h188
-rw-r--r--NvCloth/samples/external/hbao/GFSDK_SSAO.h1391
-rw-r--r--NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.dllbin0 -> 965120 bytes
-rw-r--r--NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.libbin0 -> 2328 bytes
-rw-r--r--NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.dllbin0 -> 1068032 bytes
-rw-r--r--NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.libbin0 -> 2326 bytes
-rw-r--r--NvCloth/samples/external/imgui/1.49/.travis.yml18
-rw-r--r--NvCloth/samples/external/imgui/1.49/LICENSE21
-rw-r--r--NvCloth/samples/external/imgui/1.49/README.md184
-rw-r--r--NvCloth/samples/external/imgui/1.49/examples/directx11_example/build_win32.bat4
-rw-r--r--NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj159
-rw-r--r--NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj.filters45
-rw-r--r--NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.cpp583
-rw-r--r--NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.h25
-rw-r--r--NvCloth/samples/external/imgui/1.49/examples/directx11_example/main.cpp197
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/Cousine-Regular.ttfbin0 -> 43912 bytes
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/DroidSans.ttfbin0 -> 190044 bytes
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/Karla-Regular.ttfbin0 -> 16848 bytes
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyClean.ttfbin0 -> 41208 bytes
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyTiny.ttfbin0 -> 35656 bytes
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/README.txt151
-rw-r--r--NvCloth/samples/external/imgui/1.49/extra_fonts/binary_to_compressed_c.cpp368
-rw-r--r--NvCloth/samples/external/imgui/1.49/imconfig.h51
-rw-r--r--NvCloth/samples/external/imgui/1.49/imgui.cpp9724
-rw-r--r--NvCloth/samples/external/imgui/1.49/imgui.h1402
-rw-r--r--NvCloth/samples/external/imgui/1.49/imgui_demo.cpp2538
-rw-r--r--NvCloth/samples/external/imgui/1.49/imgui_draw.cpp2377
-rw-r--r--NvCloth/samples/external/imgui/1.49/imgui_internal.h754
-rw-r--r--NvCloth/samples/external/imgui/1.49/stb_rect_pack.h573
-rw-r--r--NvCloth/samples/external/imgui/1.49/stb_textedit.h1317
-rw-r--r--NvCloth/samples/external/imgui/1.49/stb_truetype.h3263
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/bin/Win32/nvToolsExt32_1.dllbin0 -> 43520 bytes
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/bin/armv7/libnvToolsExt.sobin0 -> 46204 bytes
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/bin/x64/nvToolsExt64_1.dllbin0 -> 42496 bytes
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExt.h674
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtCuda.h128
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtOpenCL.h191
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/include/stdint/stdint.h247
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/lib/Win32/nvToolsExt32_1.libbin0 -> 9714 bytes
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/lib/armv7/libnvToolsExt.abin0 -> 139570 bytes
-rw-r--r--NvCloth/samples/external/nvToolsExt/1.0/lib/x64/nvToolsExt64_1.libbin0 -> 9196 bytes
-rw-r--r--NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib.h865
-rw-r--r--NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_Common.h416
-rw-r--r--NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.dllbin0 -> 3326464 bytes
-rw-r--r--NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.libbin0 -> 2384 bytes
-rw-r--r--NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.dllbin0 -> 3354624 bytes
-rw-r--r--NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.libbin0 -> 2382 bytes
-rw-r--r--NvCloth/samples/resources/shaders/common_buffers.hlsl28
-rw-r--r--NvCloth/samples/resources/shaders/debug_primitive.hlsl31
-rw-r--r--NvCloth/samples/resources/shaders/lighting.hlsl51
-rw-r--r--NvCloth/samples/resources/shaders/model_simple.hlsl42
-rw-r--r--NvCloth/samples/resources/shaders/model_simple_textured.hlsl76
-rw-r--r--NvCloth/samples/resources/shaders/model_skinned.hlsl54
-rw-r--r--NvCloth/samples/resources/shaders/model_skinned_textured.hlsl54
-rw-r--r--NvCloth/samples/resources/shaders/physx_primitive.hlsl37
-rw-r--r--NvCloth/samples/resources/shaders/physx_primitive_plane.hlsl64
-rw-r--r--NvCloth/samples/resources/shaders/physx_primitive_transparent.hlsl40
-rw-r--r--NvCloth/samples/resources/shaders/pointsprite.hlsl106
-rw-r--r--NvCloth/samples/resources/shaders/unlit_transparent.hlsl27
298 files changed, 53015 insertions, 0 deletions
diff --git a/NvCloth/samples/CMakeLists.txt b/NvCloth/samples/CMakeLists.txt
new file mode 100644
index 0000000..3f9d60a
--- /dev/null
+++ b/NvCloth/samples/CMakeLists.txt
@@ -0,0 +1,82 @@
+cmake_minimum_required(VERSION 3.3)
+
+project(NvClothSamples CXX)
+
+CMAKE_POLICY(SET CMP0057 NEW) # Enable IN_LIST
+
+IF(NOT DEFINED SAMPLES_ROOT_DIR)
+
+ STRING(REPLACE "\\" "/" BRD_TEMP $ENV{SAMPLES_ROOT_DIR})
+
+ # This env variable is set by GenerateProjects.bat, and is no longer available when CMake rebuilds, so this stores it in the cache
+ SET(SAMPLES_ROOT_DIR ${BRD_TEMP} CACHE INTERNAL "Root of the Samples source tree")
+
+ENDIF()
+
+IF(NOT EXISTS ${SAMPLES_ROOT_DIR})
+ MESSAGE(FATAL_ERROR "SAMPLES_ROOT_DIR environment variable wasn't set or was invalid.")
+ENDIF()
+
+SET(GW_DEPS_ROOT "${SAMPLES_ROOT_DIR}/external")
+
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${GW_DEPS_ROOT}/CMakeModules")
+
+MESSAGE("Module path:" ${CMAKE_MODULE_PATH})
+
+
+IF(CMAKE_CONFIGURATION_TYPES)
+ SET(CMAKE_CONFIGURATION_TYPES debug profile checked release)
+ SET(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING
+ "Reset config to what we need"
+ FORCE)
+
+ SET(CMAKE_SHARED_LINKER_FLAGS_CHECKED "")
+ SET(CMAKE_SHARED_LINKER_FLAGS_PROFILE "")
+
+ SET(CMAKE_EXE_LINKER_FLAGS_CHECKED "")
+ SET(CMAKE_EXE_LINKER_FLAGS_PROFILE "")
+
+ENDIF()
+
+# Default to appending "DEBUG", "PROFILE", etc to produced artifacts
+IF(NOT DEFINED APPEND_CONFIG_NAME)
+ SET(APPEND_CONFIG_NAME ON)
+ENDIF()
+
+IF (APPEND_CONFIG_NAME)
+ MESSAGE("Appending config to output names")
+
+ SET(CMAKE_DEBUG_POSTFIX "DEBUG")
+ SET(CMAKE_PROFILE_POSTFIX "PROFILE")
+ SET(CMAKE_CHECKED_POSTFIX "CHECKED")
+ SET(CMAKE_RELEASE_POSTFIX "")
+ENDIF()
+
+INCLUDE(SetOutputPaths)
+
+# Either have to define a single output path, or each one.
+
+IF(NOT DEFINED BL_OUTPUT_DIR)
+ IF (NOT DEFINED BL_LIB_OUTPUT_DIR)
+ MESSAGE(FATAL_ERROR "BL_LIB_OUTPUT_DIR not defined - Define either BL_OUTPUT_DIR or BL_LIB_OUTPUT_DIR and BL_DLL_OUTPUT_DIR and BL_EXE_OUTPUT_DIR")
+ ENDIF()
+
+ IF (NOT DEFINED BL_DLL_OUTPUT_DIR)
+ MESSAGE(FATAL_ERROR "BL_DLL_OUTPUT_DIR not defined - Define either BL_OUTPUT_DIR or BL_LIB_OUTPUT_DIR and BL_DLL_OUTPUT_DIR and BL_EXE_OUTPUT_DIR")
+ ENDIF()
+
+ IF (NOT DEFINED BL_EXE_OUTPUT_DIR)
+ MESSAGE(FATAL_ERROR "BL_EXE_OUTPUT_DIR not defined - Define either BL_OUTPUT_DIR or BL_LIB_OUTPUT_DIR and BL_DLL_OUTPUT_DIR and BL_EXE_OUTPUT_DIR")
+ ENDIF()
+
+ SetLibOutputPath(${BL_LIB_OUTPUT_DIR})
+ SetDllOutputPath(${BL_DLL_OUTPUT_DIR})
+ SetExeOutputPath(${BL_EXE_OUTPUT_DIR})
+ELSE()
+ SetSingleOutputPath(${BL_OUTPUT_DIR})
+ENDIF()
+
+SET(PROJECT_CMAKE_FILES_DIR compiler/cmake/)
+
+# Include the platform specific configuration
+INCLUDE(${PROJECT_CMAKE_FILES_DIR}${TARGET_BUILD_PLATFORM}/CMakeLists.txt OPTIONAL)
diff --git a/NvCloth/samples/CmakeGenerateProjects.bat b/NvCloth/samples/CmakeGenerateProjects.bat
new file mode 100644
index 0000000..d63cde8
--- /dev/null
+++ b/NvCloth/samples/CmakeGenerateProjects.bat
@@ -0,0 +1,46 @@
+rem @echo off
+
+CD /D %~dp0
+echo "Note: You need to run this with admin rights for the first time to set GW_DEPS_ROOT globally."
+call "../scripts/locate_gw_root.bat" GW_DEPS_ROOT_F
+@echo on
+setx GW_DEPS_ROOT "%GW_DEPS_ROOT_F%
+echo GW_DEPS_ROOT = %GW_DEPS_ROOT%
+call "../scripts/locate_cmake.bat" CMAKE_PATH_F
+echo CMAKE_PATH_F = %CMAKE_PATH_F%
+
+
+SET PATH=%PATH%;"%CMAKE_PATH_F%"
+
+REM Make sure the various variables that we need are set
+
+IF EXIST %~dp0..\Externals\CMakeModules (
+ set GW_DEPS_ROOT=%~dp0..\
+)
+
+IF NOT DEFINED GW_DEPS_ROOT GOTO GW_DEPS_ROOT_UNDEFINED
+
+set PX_OUTPUT_ROOT=%~dp0
+
+set OUTPUT_ROOT=%~dp0
+set SAMPLES_ROOT_DIR=%~dp0
+
+REM Generate projects here
+
+rmdir /s /q compiler\vc14win32-cmake\
+mkdir compiler\vc14win32-cmake\
+pushd compiler\vc14win32-cmake\
+cmake ..\.. -G "Visual Studio 14 2015" -AWin32 -DTARGET_BUILD_PLATFORM=Windows -DSTATIC_WINCRT=0 -DBL_DLL_OUTPUT_DIR=%OUTPUT_ROOT%\bin\vc14win32-cmake -DBL_LIB_OUTPUT_DIR=%OUTPUT_ROOT%\lib\vc14win32-cmake -DBL_EXE_OUTPUT_DIR=%OUTPUT_ROOT%\bin\vc14win32-cmake
+popd
+
+rmdir /s /q compiler\vc14win64-cmake\
+mkdir compiler\vc14win64-cmake\
+pushd compiler\vc14win64-cmake\
+cmake ..\.. -G "Visual Studio 14 2015" -Ax64 -DTARGET_BUILD_PLATFORM=Windows -DSTATIC_WINCRT=0 -DBL_DLL_OUTPUT_DIR=%OUTPUT_ROOT%\bin\vc14win64-cmake -DBL_LIB_OUTPUT_DIR=%OUTPUT_ROOT%\lib\vc14win64-cmake -DBL_EXE_OUTPUT_DIR=%OUTPUT_ROOT%\bin\vc14win64-cmake
+popd
+
+
+GOTO :End
+
+:End
+pause \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/Main.cpp b/NvCloth/samples/SampleBase/Main.cpp
new file mode 100644
index 0000000..433ed88
--- /dev/null
+++ b/NvCloth/samples/SampleBase/Main.cpp
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "Sample.h"
+#include <sstream>
+
+#include <Windows.h>
+
+
+using namespace std;
+
+int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
+{
+ // Enable run-time memory check for debug builds.
+#if defined(DEBUG) | defined(_DEBUG)
+ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
+ AllocConsole();
+#endif
+
+ SampleConfig config;
+ config.sampleName = L"NvCloth Samples Viewer";
+ //config.additionalResourcesDir.push_back(alternatePathArg.getValue().c_str());
+
+ int result = runSample(config);
+
+ return result;
+}
diff --git a/NvCloth/samples/SampleBase/Sample.h b/NvCloth/samples/SampleBase/Sample.h
new file mode 100644
index 0000000..9c9c502
--- /dev/null
+++ b/NvCloth/samples/SampleBase/Sample.h
@@ -0,0 +1,26 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SAMPLE_H
+#define SAMPLE_H
+
+#include <string>
+#include <vector>
+
+
+struct SampleConfig
+{
+ std::wstring sampleName;
+ std::vector<std::string> additionalResourcesDir;
+};
+
+int runSample(const SampleConfig& config);
+
+#endif //SAMPLE_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/core/Application.cpp b/NvCloth/samples/SampleBase/core/Application.cpp
new file mode 100644
index 0000000..a7f81f1
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/Application.cpp
@@ -0,0 +1,73 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "Application.h"
+#include <DirectXMath.h>
+#include "XInput.h"
+#include "DXUTMisc.h"
+
+
+Application::Application(std::wstring sampleName)
+: m_sampleName(sampleName)
+{
+ m_deviceManager = new DeviceManager();
+}
+
+void Application::addControllerToFront(IApplicationController* controller)
+{
+ m_controllers.push_back(controller);
+}
+
+int Application::run()
+{
+ // FirstPersonCamera uses this timer, without it it will be FPS-dependent
+ DXUTGetGlobalTimer()->Start();
+
+ for (auto it = m_controllers.begin(); it != m_controllers.end(); it++)
+ m_deviceManager->AddControllerToFront(*it);
+
+ DeviceCreationParameters deviceParams;
+ deviceParams.swapChainFormat = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
+ deviceParams.swapChainSampleCount = 4;
+ deviceParams.startFullscreen = false;
+ deviceParams.backBufferWidth = 1600;
+ deviceParams.backBufferHeight = 900;
+#if defined(DEBUG) | defined(_DEBUG)
+ deviceParams.createDeviceFlags = D3D11_CREATE_DEVICE_DEBUG;
+#endif
+ deviceParams.featureLevel = D3D_FEATURE_LEVEL_11_0;
+
+ if (FAILED(m_deviceManager->CreateWindowDeviceAndSwapChain(deviceParams, m_sampleName.c_str())))
+ {
+ MessageBoxA(nullptr, "Cannot initialize the D3D11 device with the requested parameters", "Error",
+ MB_OK | MB_ICONERROR);
+ return 1;
+ }
+
+ for (auto it = m_controllers.begin(); it != m_controllers.end(); it++)
+ (*it)->onInitialize();
+
+ for (auto it = m_controllers.begin(); it != m_controllers.end(); it++)
+ (*it)->onSampleStart();
+
+ m_deviceManager->SetVsyncEnabled(false);
+ m_deviceManager->MessageLoop();
+
+ for (auto it = m_controllers.rbegin(); it != m_controllers.rend(); it++)
+ (*it)->onSampleStop();
+
+ for (auto it = m_controllers.rbegin(); it != m_controllers.rend(); it++)
+ (*it)->onTerminate();
+
+ m_deviceManager->Shutdown();
+ delete m_deviceManager;
+
+ return 0;
+}
diff --git a/NvCloth/samples/SampleBase/core/Application.h b/NvCloth/samples/SampleBase/core/Application.h
new file mode 100644
index 0000000..286b40f
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/Application.h
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef APPLICATION_H
+#define APPLICATION_H
+
+#include <DeviceManager.h>
+#include <vector>
+#include <string>
+
+/**
+ISampleController adds more onstart and onstop callbacks to IVisualController
+*/
+class IApplicationController : public IVisualController
+{
+ public:
+ virtual void onInitialize() {}
+ virtual void onSampleStart() {}
+ virtual void onSampleStop() {}
+ virtual void onTerminate() {}
+};
+
+
+/**
+Main manager which runs sample.
+You have to add controllers to it which will receive all the start, animate, render etc. callbacks.
+*/
+class Application
+{
+public:
+ Application(std::wstring sampleName);
+ void addControllerToFront(IApplicationController* controller);
+
+ const std::vector<IApplicationController*>& getControllers() const
+ {
+ return m_controllers;
+ }
+
+ int run();
+
+private:
+ DeviceManager* m_deviceManager;
+ std::vector<IApplicationController*> m_controllers;
+ std::wstring m_sampleName;
+};
+
+
+#endif //APPLICATION_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/core/DeviceManager.cpp b/NvCloth/samples/SampleBase/core/DeviceManager.cpp
new file mode 100644
index 0000000..26f9fbb
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/DeviceManager.cpp
@@ -0,0 +1,795 @@
+// TAGRELEASE: PUBLIC
+
+#include "DeviceManager.h"
+#include <WinUser.h>
+#include <Windows.h>
+#include <assert.h>
+#include <sstream>
+#include <algorithm>
+#include "SampleProfiler.h"
+
+#ifndef SAFE_RELEASE
+#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } }
+#endif
+
+#define WINDOW_CLASS_NAME L"NvDX11"
+
+#define WINDOW_STYLE_NORMAL (WS_OVERLAPPEDWINDOW | WS_VISIBLE)
+#define WINDOW_STYLE_FULLSCREEN (WS_POPUP | WS_SYSMENU | WS_VISIBLE)
+
+// A singleton, sort of... To pass the events from WindowProc to the object.
+DeviceManager* g_DeviceManagerInstance = NULL;
+
+#undef min
+#undef max
+
+LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ if(g_DeviceManagerInstance)
+ return g_DeviceManagerInstance->MsgProc(hWnd, uMsg, wParam, lParam);
+ else
+ return DefWindowProc(hWnd, uMsg, wParam, lParam);
+}
+
+DeviceManager* GetDeviceManager()
+{
+ return g_DeviceManagerInstance;
+}
+
+namespace
+{
+ bool IsNvDeviceID(UINT id)
+ {
+ return id == 0x10DE;
+ }
+
+ // Find an adapter whose name contains the given string.
+ IDXGIAdapter* FindAdapter(const WCHAR* targetName, bool& isNv)
+ {
+ IDXGIAdapter* targetAdapter = NULL;
+ IDXGIFactory* IDXGIFactory_0001 = NULL;
+ HRESULT hres = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&IDXGIFactory_0001);
+ if (hres != S_OK)
+ {
+ printf("ERROR in CreateDXGIFactory, %s@%d.\nFor more info, get log from debug D3D runtime: (1) Install DX SDK, and enable Debug D3D from DX Control Panel Utility. (2) Install and start DbgView. (3) Try running the program again.\n",__FILE__,__LINE__);
+ return targetAdapter;
+ }
+
+ unsigned int adapterNo = 0;
+ while (SUCCEEDED(hres))
+ {
+ IDXGIAdapter* pAdapter = NULL;
+ hres = IDXGIFactory_0001->EnumAdapters(adapterNo, (IDXGIAdapter**)&pAdapter);
+
+ if (SUCCEEDED(hres))
+ {
+ DXGI_ADAPTER_DESC aDesc;
+ pAdapter->GetDesc(&aDesc);
+
+ // If no name is specified, return the first adapater. This is the same behaviour as the
+ // default specified for D3D11CreateDevice when no adapter is specified.
+ if (wcslen(targetName) == 0)
+ {
+ targetAdapter = pAdapter;
+ isNv = IsNvDeviceID(aDesc.VendorId);
+ break;
+ }
+
+ std::wstring aName = aDesc.Description;
+ if (aName.find(targetName) != std::string::npos)
+ {
+ targetAdapter = pAdapter;
+ isNv = IsNvDeviceID(aDesc.VendorId);
+ }
+ else
+ {
+ pAdapter->Release();
+ }
+ }
+
+ adapterNo++;
+ }
+
+ if (IDXGIFactory_0001)
+ IDXGIFactory_0001->Release();
+
+ return targetAdapter;
+ }
+
+ // Adjust window rect so that it is centred on the given adapter. Clamps to fit if it's too big.
+ RECT MoveWindowOntoAdapter(IDXGIAdapter* targetAdapter, const RECT& rect)
+ {
+ assert(targetAdapter != NULL);
+
+ RECT result = rect;
+ HRESULT hres = S_OK;
+ unsigned int outputNo = 0;
+ while (SUCCEEDED(hres))
+ {
+ IDXGIOutput* pOutput = NULL;
+ hres = targetAdapter->EnumOutputs(outputNo++, &pOutput);
+
+ if (SUCCEEDED(hres) && pOutput)
+ {
+ DXGI_OUTPUT_DESC OutputDesc;
+ pOutput->GetDesc( &OutputDesc );
+ const RECT desktop = OutputDesc.DesktopCoordinates;
+ const int centreX = (int) desktop.left + (int)(desktop.right - desktop.left) / 2;
+ const int centreY = (int) desktop.top + (int)(desktop.bottom - desktop.top) / 2;
+ const int winW = rect.right - rect.left;
+ const int winH = rect.bottom - rect.top;
+ int left = centreX - winW/2;
+ int right = left + winW;
+ int top = centreY - winH/2;
+ int bottom = top + winH;
+ result.left = std::max(left, (int) desktop.left);
+ result.right = std::min(right, (int) desktop.right);
+ result.bottom = std::min(bottom, (int) desktop.bottom);
+ result.top = std::max(top, (int) desktop.top);
+ pOutput->Release();
+
+ // If there is more than one output, go with the first found. Multi-monitor support could go here.
+ break;
+ }
+ }
+ return result;
+ }
+}
+
+HRESULT
+DeviceManager::CreateWindowDeviceAndSwapChain(const DeviceCreationParameters& params, std::wstring title)
+{
+ g_DeviceManagerInstance = this;
+ m_WindowTitle = title;
+
+ HINSTANCE hInstance = GetModuleHandle(NULL);
+ WNDCLASSEX windowClass = { sizeof(WNDCLASSEX), CS_HREDRAW | CS_VREDRAW, WindowProc,
+ 0L, 0L, hInstance, NULL, NULL, NULL, NULL, WINDOW_CLASS_NAME, NULL };
+
+ windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
+
+ RegisterClassEx(&windowClass);
+
+ UINT windowStyle = params.startFullscreen
+ ? WINDOW_STYLE_FULLSCREEN
+ : params.startMaximized
+ ? (WINDOW_STYLE_NORMAL | WS_MAXIMIZE)
+ : WINDOW_STYLE_NORMAL;
+
+ RECT rect = { 0, 0, params.backBufferWidth, params.backBufferHeight };
+ AdjustWindowRect(&rect, windowStyle, FALSE);
+
+ IDXGIAdapter* targetAdapter = FindAdapter(params.adapterNameSubstring, m_IsNvidia);
+ if (targetAdapter)
+ {
+ rect = MoveWindowOntoAdapter(targetAdapter, rect);
+ }
+ else
+ {
+ // We could silently use a default adapter in this case. I think it's better to choke.
+ std::wostringstream ostr;
+ ostr << L"Could not find an adapter matching \"" << params.adapterNameSubstring << "\"" << std::ends;
+ MessageBox(NULL, ostr.str().c_str(), m_WindowTitle.c_str(), MB_OK | MB_ICONERROR);
+ return E_FAIL;
+ }
+
+ m_hWnd = CreateWindowEx(
+ 0,
+ WINDOW_CLASS_NAME,
+ title.c_str(),
+ windowStyle,
+ rect.left,
+ rect.top,
+ rect.right - rect.left,
+ rect.bottom - rect.top,
+ GetDesktopWindow(),
+ NULL,
+ hInstance,
+ NULL
+ );
+
+ if(!m_hWnd)
+ {
+#ifdef DEBUG
+ DWORD errorCode = GetLastError();
+ printf("CreateWindowEx error code = 0x%x\n", errorCode);
+#endif
+
+ MessageBox(NULL, L"Cannot create window", m_WindowTitle.c_str(), MB_OK | MB_ICONERROR);
+ return E_FAIL;
+ }
+
+ UpdateWindow(m_hWnd);
+
+ HRESULT hr = E_FAIL;
+
+ RECT clientRect;
+ GetClientRect(m_hWnd, &clientRect);
+ UINT width = clientRect.right - clientRect.left;
+ UINT height = clientRect.bottom - clientRect.top;
+
+ ZeroMemory(&m_SwapChainDesc, sizeof(m_SwapChainDesc));
+ m_SwapChainDesc.BufferCount = params.swapChainBufferCount;
+ m_SwapChainDesc.BufferDesc.Width = width;
+ m_SwapChainDesc.BufferDesc.Height = height;
+ m_SwapChainDesc.BufferDesc.Format = params.swapChainFormat;
+ m_SwapChainDesc.BufferDesc.RefreshRate.Numerator = params.refreshRate;
+ m_SwapChainDesc.BufferDesc.RefreshRate.Denominator = 0;
+ m_SwapChainDesc.BufferUsage = params.swapChainUsage;
+ m_SwapChainDesc.OutputWindow = m_hWnd;
+ m_SwapChainDesc.SampleDesc.Count = params.swapChainSampleCount;
+ m_SwapChainDesc.SampleDesc.Quality = params.swapChainSampleQuality;
+ m_SwapChainDesc.Windowed = !params.startFullscreen;
+ m_SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
+
+ // The D3D documentation says that if adapter is non-null, driver type must be unknown. Why not put
+ // this logic in the CreateDevice fns then?!?
+ const D3D_DRIVER_TYPE dType = (targetAdapter)? D3D_DRIVER_TYPE_UNKNOWN: params.driverType;
+
+ hr = D3D11CreateDeviceAndSwapChain(
+ targetAdapter, // pAdapter
+ dType, // DriverType
+ NULL, // Software
+ params.createDeviceFlags, // Flags
+ &params.featureLevel, // pFeatureLevels
+ 1, // FeatureLevels
+ D3D11_SDK_VERSION, // SDKVersion
+ &m_SwapChainDesc, // pSwapChainDesc
+ &m_SwapChain, // ppSwapChain
+ &m_Device, // ppDevice
+ NULL, // pFeatureLevel
+ &m_ImmediateContext // ppImmediateContext
+ );
+
+ if (targetAdapter)
+ targetAdapter->Release();
+
+ if(FAILED(hr))
+ return hr;
+
+ m_DepthStencilDesc.ArraySize = 1;
+ m_DepthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
+ m_DepthStencilDesc.CPUAccessFlags = 0;
+ m_DepthStencilDesc.Format = params.depthStencilFormat;
+ m_DepthStencilDesc.Width = width;
+ m_DepthStencilDesc.Height = height;
+ m_DepthStencilDesc.MipLevels = 1;
+ m_DepthStencilDesc.MiscFlags = 0;
+ m_DepthStencilDesc.SampleDesc.Count = params.swapChainSampleCount;
+ m_DepthStencilDesc.SampleDesc.Quality = 0;
+ m_DepthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
+
+ hr = CreateRenderTargetAndDepthStencil();
+
+ if(FAILED(hr))
+ return hr;
+
+ DeviceCreated();
+ BackBufferResized();
+
+ return S_OK;
+}
+
+void
+DeviceManager::Shutdown()
+{
+ if(m_SwapChain && GetWindowState() == kWindowFullscreen)
+ m_SwapChain->SetFullscreenState(false, NULL);
+
+ DeviceDestroyed();
+
+ SAFE_RELEASE(m_BackBufferRTV);
+ SAFE_RELEASE(m_DepthStencilDSV);
+ SAFE_RELEASE(m_DepthStencilBuffer);
+
+ g_DeviceManagerInstance = NULL;
+ SAFE_RELEASE(m_ImmediateContext);
+ SAFE_RELEASE(m_SwapChain);
+
+ ID3D11Debug * d3dDebug = nullptr;
+ if (nullptr != m_Device)
+ {
+ ID3D11DeviceContext* pCtx;
+ m_Device->GetImmediateContext(&pCtx);
+ pCtx->ClearState();
+ pCtx->Flush();
+ pCtx->Release();
+ if (SUCCEEDED(m_Device->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&d3dDebug))))
+ {
+ d3dDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
+ d3dDebug->Release();
+ }
+ }
+ SAFE_RELEASE(m_Device);
+
+ if(m_hWnd)
+ {
+ DestroyWindow(m_hWnd);
+ m_hWnd = NULL;
+ }
+}
+
+HRESULT
+DeviceManager::CreateRenderTargetAndDepthStencil()
+{
+ HRESULT hr;
+
+ ID3D11Texture2D *backBuffer = NULL;
+ hr = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer);
+ if (FAILED(hr))
+ return hr;
+
+ hr = m_Device->CreateRenderTargetView(backBuffer, NULL, &m_BackBufferRTV);
+ backBuffer->Release();
+ if (FAILED(hr))
+ return hr;
+
+ if(m_DepthStencilDesc.Format != DXGI_FORMAT_UNKNOWN)
+ {
+ hr = m_Device->CreateTexture2D(&m_DepthStencilDesc, NULL, &m_DepthStencilBuffer);
+ if (FAILED(hr))
+ return hr;
+
+ hr = m_Device->CreateDepthStencilView(m_DepthStencilBuffer, NULL, &m_DepthStencilDSV);
+ if (FAILED(hr))
+ return hr;
+ }
+
+ return S_OK;
+}
+
+void
+DeviceManager::MessageLoop()
+{
+ MSG msg = {0};
+
+ LARGE_INTEGER perfFreq, previousTime;
+ QueryPerformanceFrequency(&perfFreq);
+ QueryPerformanceCounter(&previousTime);
+
+ while (WM_QUIT != msg.message)
+ {
+ if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
+ else
+ {
+ PROFILER_BEGIN("Main Loop");
+
+ LARGE_INTEGER newTime;
+ QueryPerformanceCounter(&newTime);
+
+ double elapsedSeconds = (m_FixedFrameInterval >= 0)
+ ? m_FixedFrameInterval
+ : (double)(newTime.QuadPart - previousTime.QuadPart) / (double)perfFreq.QuadPart;
+
+ if(m_SwapChain && GetWindowState() != kWindowMinimized)
+ {
+ Animate(elapsedSeconds);
+ Render();
+ m_SwapChain->Present(m_SyncInterval, 0);
+ Sleep(0);
+ }
+ else
+ {
+ // Release CPU resources when idle
+ Sleep(1);
+ }
+
+ {
+ m_vFrameTimes.push_back(elapsedSeconds);
+ double timeSum = 0;
+ for(auto it = m_vFrameTimes.begin(); it != m_vFrameTimes.end(); it++)
+ timeSum += *it;
+
+ if(timeSum > m_AverageTimeUpdateInterval)
+ {
+ m_AverageFrameTime = timeSum / (double)m_vFrameTimes.size();
+ m_vFrameTimes.clear();
+ }
+ }
+
+ previousTime = newTime;
+
+ PROFILER_END();
+ PROFILER_RESET();
+ }
+
+ }
+}
+
+LRESULT
+DeviceManager::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ switch(uMsg)
+ {
+ case WM_DESTROY:
+ case WM_CLOSE:
+ PostQuitMessage(0);
+ return 0;
+
+ case WM_SYSKEYDOWN:
+ if(wParam == VK_F4)
+ {
+ PostQuitMessage(0);
+ return 0;
+ }
+ break;
+
+ case WM_ENTERSIZEMOVE:
+ m_InSizingModalLoop = true;
+ m_NewWindowSize.cx = m_SwapChainDesc.BufferDesc.Width;
+ m_NewWindowSize.cy = m_SwapChainDesc.BufferDesc.Height;
+ break;
+
+ case WM_EXITSIZEMOVE:
+ m_InSizingModalLoop = false;
+ ResizeSwapChain();
+ break;
+
+ case WM_SIZE:
+ // Ignore the WM_SIZE event if there is no device,
+ // or if the window has been minimized (size == 0),
+ // or if it has been restored to the previous size (this part is tested inside ResizeSwapChain)
+ if (m_Device && (lParam != 0))
+ {
+ m_NewWindowSize.cx = LOWORD(lParam);
+ m_NewWindowSize.cy = HIWORD(lParam);
+
+ if(!m_InSizingModalLoop)
+ ResizeSwapChain();
+ }
+ }
+
+ if( uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST ||
+ uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST )
+ {
+ // processing messages front-to-back
+ for(auto it = m_vControllers.begin(); it != m_vControllers.end(); it++)
+ {
+ if((*it)->IsEnabled())
+ {
+ // for kb/mouse messages, 0 means the message has been handled
+ if(0 == (*it)->MsgProc(hWnd, uMsg, wParam, lParam))
+ return 0;
+ }
+ }
+ }
+
+ return DefWindowProc(hWnd, uMsg, wParam, lParam);
+}
+
+void
+DeviceManager::ResizeSwapChain()
+{
+ if(m_NewWindowSize.cx == (LONG)m_SwapChainDesc.BufferDesc.Width &&
+ m_NewWindowSize.cy == (LONG)m_SwapChainDesc.BufferDesc.Height)
+ return;
+
+ m_SwapChainDesc.BufferDesc.Width = m_NewWindowSize.cx;
+ m_SwapChainDesc.BufferDesc.Height = m_NewWindowSize.cy;
+
+ ID3D11RenderTargetView *nullRTV = NULL;
+ m_ImmediateContext->OMSetRenderTargets(1, &nullRTV, NULL);
+ SAFE_RELEASE(m_BackBufferRTV);
+ SAFE_RELEASE(m_DepthStencilDSV);
+ SAFE_RELEASE(m_DepthStencilBuffer);
+
+ if (m_SwapChain)
+ {
+ // Resize the swap chain
+ m_SwapChain->ResizeBuffers(m_SwapChainDesc.BufferCount, m_SwapChainDesc.BufferDesc.Width,
+ m_SwapChainDesc.BufferDesc.Height, m_SwapChainDesc.BufferDesc.Format,
+ m_SwapChainDesc.Flags);
+
+ m_DepthStencilDesc.Width = m_NewWindowSize.cx;
+ m_DepthStencilDesc.Height = m_NewWindowSize.cy;
+
+ CreateRenderTargetAndDepthStencil();
+
+ BackBufferResized();
+ }
+}
+
+void
+DeviceManager::Render()
+{
+ PROFILER_SCOPED_FUNCTION();
+
+ D3D11_VIEWPORT viewport = { 0.0f, 0.0f, (float)m_SwapChainDesc.BufferDesc.Width, (float)m_SwapChainDesc.BufferDesc.Height, 0.0f, 1.0f };
+
+ // rendering back-to-front
+ for(auto it = m_vControllers.rbegin(); it != m_vControllers.rend(); it++)
+ {
+ if((*it)->IsEnabled())
+ {
+ m_ImmediateContext->OMSetRenderTargets(1, &m_BackBufferRTV, m_DepthStencilDSV);
+ m_ImmediateContext->RSSetViewports(1, &viewport);
+
+ (*it)->Render(m_Device, m_ImmediateContext, m_BackBufferRTV, m_DepthStencilDSV);
+ }
+ }
+
+ m_ImmediateContext->OMSetRenderTargets(0, NULL, NULL);
+}
+
+void
+DeviceManager::Animate(double fElapsedTimeSeconds)
+{
+ PROFILER_SCOPED_FUNCTION();
+
+ // front-to-back, but the order shouldn't matter
+ for(auto it = m_vControllers.begin(); it != m_vControllers.end(); it++)
+ {
+ if((*it)->IsEnabled())
+ {
+ (*it)->Animate(fElapsedTimeSeconds);
+ }
+ }
+}
+
+void
+DeviceManager::DeviceCreated()
+{
+ // creating resources front-to-back
+ for(auto it = m_vControllers.begin(); it != m_vControllers.end(); it++)
+ {
+ (*it)->DeviceCreated(m_Device);
+ }
+}
+
+void
+DeviceManager::DeviceDestroyed()
+{
+ // releasing resources back-to-front
+ for(auto it = m_vControllers.rbegin(); it != m_vControllers.rend(); it++)
+ {
+ (*it)->DeviceDestroyed();
+ }
+}
+
+void
+DeviceManager::BackBufferResized()
+{
+ if(m_SwapChain == NULL)
+ return;
+
+ DXGI_SURFACE_DESC backSD;
+ backSD.Format = m_SwapChainDesc.BufferDesc.Format;
+ backSD.Width = m_SwapChainDesc.BufferDesc.Width;
+ backSD.Height = m_SwapChainDesc.BufferDesc.Height;
+ backSD.SampleDesc = m_SwapChainDesc.SampleDesc;
+
+ for(auto it = m_vControllers.begin(); it != m_vControllers.end(); it++)
+ {
+ (*it)->BackBufferResized(m_Device, &backSD);
+ }
+}
+
+HRESULT
+DeviceManager::ChangeBackBufferFormat(DXGI_FORMAT format, UINT sampleCount)
+{
+ HRESULT hr = E_FAIL;
+
+ if((format == DXGI_FORMAT_UNKNOWN || format == m_SwapChainDesc.BufferDesc.Format) &&
+ (sampleCount == 0 || sampleCount == m_SwapChainDesc.SampleDesc.Count))
+ return S_FALSE;
+
+ if(m_Device)
+ {
+ bool fullscreen = (GetWindowState() == kWindowFullscreen);
+ if(fullscreen)
+ m_SwapChain->SetFullscreenState(false, NULL);
+
+ IDXGISwapChain* newSwapChain = NULL;
+ DXGI_SWAP_CHAIN_DESC newSwapChainDesc = m_SwapChainDesc;
+
+ if(format != DXGI_FORMAT_UNKNOWN)
+ newSwapChainDesc.BufferDesc.Format = format;
+ if(sampleCount != 0)
+ newSwapChainDesc.SampleDesc.Count = sampleCount;
+
+ IDXGIAdapter* pDXGIAdapter = GetDXGIAdapter();
+
+ IDXGIFactory* pDXGIFactory = NULL;
+ pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&pDXGIFactory));
+
+ hr = pDXGIFactory->CreateSwapChain(m_Device, &newSwapChainDesc, &newSwapChain);
+
+ pDXGIFactory->Release();
+ pDXGIAdapter->Release();
+
+ if (FAILED(hr))
+ {
+ if(fullscreen)
+ m_SwapChain->SetFullscreenState(true, NULL);
+
+ return hr;
+ }
+
+ SAFE_RELEASE(m_BackBufferRTV);
+ SAFE_RELEASE(m_SwapChain);
+ SAFE_RELEASE(m_DepthStencilBuffer);
+ SAFE_RELEASE(m_DepthStencilDSV);
+
+ m_SwapChain = newSwapChain;
+ m_SwapChainDesc = newSwapChainDesc;
+
+ m_DepthStencilDesc.SampleDesc.Count = sampleCount;
+
+ if(fullscreen)
+ m_SwapChain->SetFullscreenState(true, NULL);
+
+ CreateRenderTargetAndDepthStencil();
+ BackBufferResized();
+ }
+
+ return S_OK;
+}
+
+void
+DeviceManager::AddControllerToFront(IVisualController* pController)
+{
+ m_vControllers.remove(pController);
+ m_vControllers.push_front(pController);
+}
+
+void
+DeviceManager::AddControllerToBack(IVisualController* pController)
+{
+ m_vControllers.remove(pController);
+ m_vControllers.push_back(pController);
+}
+
+void
+DeviceManager::RemoveController(IVisualController* pController)
+{
+ m_vControllers.remove(pController);
+}
+
+HRESULT
+DeviceManager::ResizeWindow(int width, int height)
+{
+ if(m_SwapChain == NULL)
+ return E_FAIL;
+
+ RECT rect;
+ GetWindowRect(m_hWnd, &rect);
+
+ ShowWindow(m_hWnd, SW_RESTORE);
+
+ if(!MoveWindow(m_hWnd, rect.left, rect.top, width, height, true))
+ return E_FAIL;
+
+ // No need to call m_SwapChain->ResizeBackBuffer because MoveWindow will send WM_SIZE, which calls that function.
+
+ return S_OK;
+}
+
+HRESULT
+DeviceManager::EnterFullscreenMode(int width, int height)
+{
+ if(m_SwapChain == NULL)
+ return E_FAIL;
+
+ if(GetWindowState() == kWindowFullscreen)
+ return S_FALSE;
+
+ if(width <= 0 || height <= 0)
+ {
+ width = m_SwapChainDesc.BufferDesc.Width;
+ height = m_SwapChainDesc.BufferDesc.Height;
+ }
+
+ SetWindowLong(m_hWnd, GWL_STYLE, WINDOW_STYLE_FULLSCREEN);
+ MoveWindow(m_hWnd, 0, 0, width, height, true);
+
+ HRESULT hr = m_SwapChain->SetFullscreenState(true, NULL);
+
+ if(FAILED(hr))
+ {
+ SetWindowLong(m_hWnd, GWL_STYLE, WINDOW_STYLE_NORMAL);
+ return hr;
+ }
+
+ UpdateWindow(m_hWnd);
+ m_SwapChain->GetDesc(&m_SwapChainDesc);
+
+ return S_OK;
+}
+
+HRESULT
+DeviceManager::LeaveFullscreenMode(int windowWidth, int windowHeight)
+{
+ if(m_SwapChain == NULL)
+ return E_FAIL;
+
+ if(GetWindowState() != kWindowFullscreen)
+ return S_FALSE;
+
+ HRESULT hr = m_SwapChain->SetFullscreenState(false, NULL);
+ if(FAILED(hr)) return hr;
+
+ SetWindowLong(m_hWnd, GWL_STYLE, WINDOW_STYLE_NORMAL);
+
+ if(windowWidth <= 0 || windowHeight <= 0)
+ {
+ windowWidth = m_SwapChainDesc.BufferDesc.Width;
+ windowHeight = m_SwapChainDesc.BufferDesc.Height;
+ }
+
+ RECT rect = { 0, 0, windowWidth, windowHeight };
+ AdjustWindowRect(&rect, WINDOW_STYLE_NORMAL, FALSE);
+ MoveWindow(m_hWnd, 0, 0, rect.right - rect.left, rect.bottom - rect.top, true);
+ UpdateWindow(m_hWnd);
+
+ m_SwapChain->GetDesc(&m_SwapChainDesc);
+
+ return S_OK;
+}
+
+HRESULT
+DeviceManager::ToggleFullscreen()
+{
+ if(GetWindowState() == kWindowFullscreen)
+ return LeaveFullscreenMode();
+ else
+ return EnterFullscreenMode();
+}
+
+DeviceManager::WindowState
+DeviceManager::GetWindowState()
+{
+ if(m_SwapChain && !m_SwapChainDesc.Windowed)
+ return kWindowFullscreen;
+
+ if(m_hWnd == INVALID_HANDLE_VALUE)
+ return kWindowNone;
+
+ if(IsZoomed(m_hWnd))
+ return kWindowMaximized;
+
+ if(IsIconic(m_hWnd))
+ return kWindowMinimized;
+
+ return kWindowNormal;
+}
+
+HRESULT
+DeviceManager::GetDisplayResolution(int& width, int& height)
+{
+ if(m_hWnd != INVALID_HANDLE_VALUE)
+ {
+ HMONITOR monitor = MonitorFromWindow(m_hWnd, MONITOR_DEFAULTTOPRIMARY);
+ MONITORINFO info;
+ info.cbSize = sizeof(MONITORINFO);
+
+ if(GetMonitorInfo(monitor, &info))
+ {
+ width = info.rcMonitor.right - info.rcMonitor.left;
+ height = info.rcMonitor.bottom - info.rcMonitor.top;
+ return S_OK;
+ }
+ }
+
+ return E_FAIL;
+}
+
+IDXGIAdapter*
+DeviceManager::GetDXGIAdapter()
+{
+ if(!m_Device)
+ return NULL;
+
+ IDXGIDevice* pDXGIDevice = NULL;
+ m_Device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&pDXGIDevice));
+
+ IDXGIAdapter* pDXGIAdapter = NULL;
+ pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&pDXGIAdapter));
+
+ pDXGIDevice->Release();
+
+ return pDXGIAdapter;
+}
diff --git a/NvCloth/samples/SampleBase/core/DeviceManager.h b/NvCloth/samples/SampleBase/core/DeviceManager.h
new file mode 100644
index 0000000..98b8eee
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/DeviceManager.h
@@ -0,0 +1,166 @@
+// TAGRELEASE: PUBLIC
+
+#pragma once
+#include <Windows.h>
+#include <DXGI.h>
+#include <D3D11.h>
+#include <list>
+
+
+struct DeviceCreationParameters
+{
+ bool startMaximized;
+ bool startFullscreen;
+ int backBufferWidth;
+ int backBufferHeight;
+ int refreshRate;
+ int swapChainBufferCount;
+ DXGI_FORMAT swapChainFormat;
+ DXGI_FORMAT depthStencilFormat;
+ DXGI_USAGE swapChainUsage;
+ int swapChainSampleCount;
+ int swapChainSampleQuality;
+ UINT createDeviceFlags;
+ D3D_DRIVER_TYPE driverType;
+ D3D_FEATURE_LEVEL featureLevel;
+
+ // For use in the case of multiple adapters. If this is non-null, device creation will try to match
+ // the given string against an adapter name. If the specified string exists as a sub-string of the
+ // adapter name, the device and window will be created on that adapter. Case sensitive.
+ const WCHAR* adapterNameSubstring;
+
+ DeviceCreationParameters()
+ : startMaximized(false)
+ , startFullscreen(false)
+ , backBufferWidth(1280)
+ , backBufferHeight(720)
+ , refreshRate(0)
+ , swapChainBufferCount(1)
+ , swapChainFormat(DXGI_FORMAT_R8G8B8A8_UNORM)
+ , depthStencilFormat(DXGI_FORMAT_D24_UNORM_S8_UINT)
+ , swapChainUsage(DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_RENDER_TARGET_OUTPUT)
+ , swapChainSampleCount(1)
+ , swapChainSampleQuality(0)
+ , createDeviceFlags(0)
+ , driverType(D3D_DRIVER_TYPE_HARDWARE)
+ , featureLevel(D3D_FEATURE_LEVEL_11_0)
+ , adapterNameSubstring(L"")
+ { }
+};
+
+#pragma warning(push)
+#pragma warning(disable: 4100) // unreferenced formal parameter
+class IVisualController
+{
+private:
+ bool m_Enabled;
+public:
+ IVisualController() : m_Enabled(true) { }
+
+ virtual LRESULT MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return 1; }
+ virtual void Render(ID3D11Device* pDevice, ID3D11DeviceContext* pDeviceContext, ID3D11RenderTargetView* pRTV, ID3D11DepthStencilView* pDSV) { }
+ virtual void Animate(double fElapsedTimeSeconds) { }
+ virtual HRESULT DeviceCreated(ID3D11Device* pDevice) { return S_OK; }
+ virtual void DeviceDestroyed() { }
+ virtual void BackBufferResized(ID3D11Device* pDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc) { }
+
+ virtual void EnableController() { m_Enabled = true; }
+ virtual void DisableController() { m_Enabled = false; }
+ virtual bool IsEnabled() { return m_Enabled; }
+};
+#pragma warning(pop)
+
+class DeviceManager
+{
+public:
+ enum WindowState
+ {
+ kWindowNone,
+ kWindowNormal,
+ kWindowMinimized,
+ kWindowMaximized,
+ kWindowFullscreen
+ };
+
+protected:
+ ID3D11Device* m_Device;
+ ID3D11DeviceContext* m_ImmediateContext;
+ IDXGISwapChain* m_SwapChain;
+ ID3D11RenderTargetView* m_BackBufferRTV;
+ ID3D11Texture2D* m_DepthStencilBuffer;
+ ID3D11DepthStencilView* m_DepthStencilDSV;
+ DXGI_SWAP_CHAIN_DESC m_SwapChainDesc;
+ D3D11_TEXTURE2D_DESC m_DepthStencilDesc;
+ bool m_IsNvidia;
+ HWND m_hWnd;
+ std::list<IVisualController*> m_vControllers;
+ std::wstring m_WindowTitle;
+ double m_FixedFrameInterval;
+ UINT m_SyncInterval;
+ std::list<double> m_vFrameTimes;
+ double m_AverageFrameTime;
+ double m_AverageTimeUpdateInterval;
+ bool m_InSizingModalLoop;
+ SIZE m_NewWindowSize;
+private:
+ HRESULT CreateRenderTargetAndDepthStencil();
+ void ResizeSwapChain();
+public:
+
+ DeviceManager()
+ : m_Device(NULL)
+ , m_ImmediateContext(NULL)
+ , m_SwapChain(NULL)
+ , m_BackBufferRTV(NULL)
+ , m_DepthStencilBuffer(NULL)
+ , m_DepthStencilDSV(NULL)
+ , m_IsNvidia(false)
+ , m_hWnd(NULL)
+ , m_WindowTitle(L"")
+ , m_FixedFrameInterval(-1)
+ , m_SyncInterval(0)
+ , m_AverageFrameTime(0)
+ , m_AverageTimeUpdateInterval(0.5)
+ , m_InSizingModalLoop(false)
+ { }
+
+ virtual ~DeviceManager()
+ { Shutdown(); }
+
+ virtual HRESULT CreateWindowDeviceAndSwapChain(const DeviceCreationParameters& params, std::wstring windowTitle);
+ virtual HRESULT ChangeBackBufferFormat(DXGI_FORMAT format, UINT sampleCount);
+ virtual HRESULT ResizeWindow(int width, int height);
+ virtual HRESULT EnterFullscreenMode(int width = 0, int height = 0);
+ virtual HRESULT LeaveFullscreenMode(int windowWidth = 0, int windowHeight = 0);
+ virtual HRESULT ToggleFullscreen();
+
+ virtual void Shutdown();
+ virtual void MessageLoop();
+ virtual LRESULT MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ virtual void Render();
+ virtual void Animate(double fElapsedTimeSeconds);
+ virtual void DeviceCreated();
+ virtual void DeviceDestroyed();
+ virtual void BackBufferResized();
+
+ void AddControllerToFront(IVisualController* pController);
+ void AddControllerToBack(IVisualController* pController);
+ void RemoveController(IVisualController* pController);
+
+ void SetFixedFrameInterval(double seconds) { m_FixedFrameInterval = seconds; }
+ void DisableFixedFrameInterval() { m_FixedFrameInterval = -1; }
+
+ bool IsNvidia() const { return m_IsNvidia; }
+ HWND GetHWND() { return m_hWnd; }
+ ID3D11Device* GetDevice() { return m_Device; }
+ WindowState GetWindowState();
+ bool GetVsyncEnabled() { return m_SyncInterval > 0; }
+ void SetVsyncEnabled(bool enabled) { m_SyncInterval = enabled ? 1 : 0; }
+ HRESULT GetDisplayResolution(int& width, int& height);
+ IDXGIAdapter* GetDXGIAdapter();
+ double GetAverageFrameTime() { return m_AverageFrameTime; }
+ void SetAverageTimeUpdateInterval(double value) { m_AverageTimeUpdateInterval = value; }
+};
+
+
+DeviceManager* GetDeviceManager();
diff --git a/NvCloth/samples/SampleBase/core/SampleController.cpp b/NvCloth/samples/SampleBase/core/SampleController.cpp
new file mode 100644
index 0000000..82278d3
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/SampleController.cpp
@@ -0,0 +1,25 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "SampleController.h"
+#include "SceneController.h"
+#include "CommonUIController.h"
+
+SampleController::SampleController()
+{
+}
+
+SampleController::~SampleController()
+{
+}
+
+void SampleController::onSampleStart()
+{
+}
diff --git a/NvCloth/samples/SampleBase/core/SampleController.h b/NvCloth/samples/SampleBase/core/SampleController.h
new file mode 100644
index 0000000..2178a3a
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/SampleController.h
@@ -0,0 +1,42 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SAMPLE_CONTROLLER_H
+#define SAMPLE_CONTROLLER_H
+
+#include "SampleManager.h"
+
+class SampleController : public ISampleController
+{
+public:
+ SampleController();
+ virtual ~SampleController();
+
+ virtual void onSampleStart();
+
+private:
+ SampleController& operator= (SampleController&);
+
+
+ //////// used controllers ////////
+
+ SceneController& getSceneController() const
+ {
+ return getManager()->getSceneController();
+ }
+
+ CommonUIController& getCommonUIController() const
+ {
+ return getManager()->getCommonUIController();
+ }
+
+};
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/core/SampleManager.cpp b/NvCloth/samples/SampleBase/core/SampleManager.cpp
new file mode 100644
index 0000000..86438c6
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/SampleManager.cpp
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "SampleManager.h"
+
+#include "Utils.h"
+
+#include "Renderer.h"
+#include "CommonUIController.h"
+#include "SceneController.h"
+#include "SampleController.h"
+
+
+SampleManager::SampleManager(const SampleConfig& config)
+: m_config(config)
+{
+}
+
+int SampleManager::run()
+{
+ Application app(getConfig().sampleName);
+
+ m_renderer = new Renderer();
+ m_sceneController = new SceneController();
+ m_sampleController = new SampleController();
+ m_commonUIController = new CommonUIController();
+
+ app.addControllerToFront(m_renderer);
+ app.addControllerToFront(m_sceneController);
+ app.addControllerToFront(m_sampleController);
+ app.addControllerToFront(m_commonUIController);
+
+ for (IApplicationController* c : app.getControllers())
+ {
+ (static_cast<ISampleController*>(c))->setManager(this);
+ }
+
+ int result = app.run();
+
+ delete m_renderer;
+ delete m_sceneController;
+ delete m_sampleController;
+ delete m_commonUIController;
+
+ return result;
+}
+
+
+int runSample(const SampleConfig& config)
+{
+ SampleManager sampleManager(config);
+ return sampleManager.run();
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/core/SampleManager.h b/NvCloth/samples/SampleBase/core/SampleManager.h
new file mode 100644
index 0000000..653d285
--- /dev/null
+++ b/NvCloth/samples/SampleBase/core/SampleManager.h
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SAMPLE_MANAGER_H
+#define SAMPLE_MANAGER_H
+
+#include "Application.h"
+#include "Sample.h"
+
+
+class SampleManager;
+
+class ISampleController : public IApplicationController
+{
+public:
+
+ void setManager(SampleManager* manager)
+ {
+ m_manager = manager;
+ }
+protected:
+
+ SampleManager* getManager() const
+ {
+ return m_manager;
+ }
+
+private:
+ SampleManager* m_manager;
+};
+
+
+class Renderer;
+class PhysXController;
+class SceneController;
+class SampleController;
+class CommonUIController;
+
+
+/**
+*/
+class SampleManager
+{
+ public:
+ SampleManager(const SampleConfig& config);
+ int run();
+
+ Renderer& getRenderer()
+ {
+ return *m_renderer;
+ }
+
+ SceneController& getSceneController() const
+ {
+ return *m_sceneController;
+ }
+
+ SampleController& getSampleController() const
+ {
+ return *m_sampleController;
+ }
+
+ CommonUIController& getCommonUIController() const
+ {
+ return *m_commonUIController;
+ }
+
+ const SampleConfig& getConfig() const
+ {
+ return m_config;
+ }
+
+
+ private:
+ Renderer* m_renderer;
+ SceneController* m_sceneController;
+ SampleController* m_sampleController;
+ CommonUIController* m_commonUIController;
+
+ const SampleConfig& m_config;
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/ClothRenderMesh.cpp b/NvCloth/samples/SampleBase/renderer/ClothRenderMesh.cpp
new file mode 100644
index 0000000..60bb5f3
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ClothRenderMesh.cpp
@@ -0,0 +1,211 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "ClothRenderMesh.h"
+#include "Renderer.h"
+
+#include <NvClothExt/ClothFabricCooker.h>
+#include "foundation/PxStrideIterator.h"
+
+using namespace nv;
+using namespace cloth;
+
+
+template <typename T>
+void gatherIndices(std::vector<uint16_t>& indices,
+ const BoundedData& triangles, const BoundedData& quads)
+{
+ PxStrideIterator<const T> tIt, qIt;
+
+ indices.reserve(triangles.count * 3 + quads.count * 6);
+
+ tIt = PxMakeIterator(reinterpret_cast<const T*>(triangles.data), triangles.stride);
+ for (PxU32 i = 0; i < triangles.count; ++i, ++tIt)
+ {
+ indices.push_back(static_cast<uint16_t>(tIt.ptr()[0]));
+ indices.push_back(static_cast<uint16_t>(tIt.ptr()[1]));
+ indices.push_back(static_cast<uint16_t>(tIt.ptr()[2]));
+ }
+ qIt = PxMakeIterator(reinterpret_cast<const T*>(quads.data), quads.stride);
+ for (PxU32 i = 0; i < quads.count; ++i, ++qIt)
+ {
+ indices.push_back(static_cast<uint16_t>(qIt.ptr()[0]));
+ indices.push_back(static_cast<uint16_t>(qIt.ptr()[1]));
+ indices.push_back(static_cast<uint16_t>(qIt.ptr()[2]));
+ indices.push_back(static_cast<uint16_t>(qIt.ptr()[0]));
+ indices.push_back(static_cast<uint16_t>(qIt.ptr()[2]));
+ indices.push_back(static_cast<uint16_t>(qIt.ptr()[3]));
+ }
+}
+
+ClothRenderMesh::ClothRenderMesh(const ClothMeshDesc& desc)
+{
+ uint32_t numVertices = desc.points.count;
+ mVertices.resize(numVertices);
+
+ PxStrideIterator<const PxVec3> pIt(reinterpret_cast<const PxVec3*>(desc.points.data), desc.points.stride);
+ for (PxU32 i = 0; i < numVertices; ++i)
+ {
+ mVertices[i].position = *pIt++;
+ mVertices[i].normal = PxVec3(0.f);
+ }
+
+ // build triangle indices
+ if (desc.flags & MeshFlag::e16_BIT_INDICES)
+ gatherIndices<PxU16>(mIndices, desc.triangles, desc.quads);
+ else
+ gatherIndices<PxU32>(mIndices, desc.triangles, desc.quads);
+
+ for (PxU32 i = 0; i < mIndices.size(); i += 3)
+ {
+ auto p0 = mVertices[mIndices[i]].position;
+ auto p1 = mVertices[mIndices[i + 1]].position;
+ auto p2 = mVertices[mIndices[i + 2]].position;
+
+ auto normal = ((p2 - p0).cross(p1 - p0)).getNormalized();
+
+ mVertices[mIndices[i]].normal += normal;
+ mVertices[mIndices[i + 1]].normal += normal;
+ mVertices[mIndices[i + 2]].normal += normal;
+ }
+
+ for (PxU32 i = 0; i < numVertices; ++i)
+ mVertices[i].normal.normalize();
+
+ std::vector<D3D11_INPUT_ELEMENT_DESC> layout;
+ layout.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ layout.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+
+ initialize(mVertices.data(), (uint32_t)mVertices.size(), sizeof(Vertex), layout, mIndices.data(), (uint32_t)mIndices.size() / 3);
+}
+
+ClothRenderMesh::ClothRenderMesh()
+ : mIndexBuffer(nullptr)
+{
+}
+
+ClothRenderMesh::ClothRenderMesh(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces, uint32_t numFaces)
+ : mIndexBuffer(nullptr)
+{
+ initialize(vertices, numVertices, vertexSize, inputDesc, faces, numFaces);
+}
+
+void ClothRenderMesh::initialize(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces, uint32_t numFaces)
+{
+ mDevice = GetDeviceManager()->GetDevice();
+
+ mInputDesc = inputDesc;
+ mNumVertices = numVertices;
+ mVertexSize = vertexSize;
+ mNumFaces = numFaces;
+
+ // VB
+ {
+ D3D11_SUBRESOURCE_DATA vertexBufferData;
+
+ ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
+ vertexBufferData.pSysMem = vertices;
+
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ bufferDesc.ByteWidth = vertexSize * numVertices;
+ bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
+
+ V(mDevice->CreateBuffer(&bufferDesc, &vertexBufferData, &mVertexBuffer));
+ }
+
+ // IB
+ if (faces != nullptr)
+ {
+ D3D11_SUBRESOURCE_DATA indexBufferData;
+
+ ZeroMemory(&indexBufferData, sizeof(indexBufferData));
+ indexBufferData.pSysMem = faces;
+
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
+ bufferDesc.ByteWidth = sizeof(uint16_t) * numFaces*3;
+ bufferDesc.CPUAccessFlags = 0;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
+
+ V(mDevice->CreateBuffer(&bufferDesc, &indexBufferData, &mIndexBuffer));
+ }
+}
+
+ClothRenderMesh::~ClothRenderMesh()
+{
+ SAFE_RELEASE(mVertexBuffer);
+ SAFE_RELEASE(mIndexBuffer);
+}
+
+void ClothRenderMesh::update(const PxVec3* positions, uint32_t numVertices)
+{
+ PxStrideIterator<const PxVec3> pIt(positions, sizeof(PxVec3));
+ for (PxU32 i = 0; i < numVertices; ++i)
+ {
+ mVertices[i].position = *pIt++;
+ mVertices[i].normal = PxVec3(0.f);
+ }
+
+ for (PxU32 i = 0; i < mIndices.size(); i += 3)
+ {
+ auto p0 = mVertices[mIndices[i]].position;
+ auto p1 = mVertices[mIndices[i + 1]].position;
+ auto p2 = mVertices[mIndices[i + 2]].position;
+
+ auto normal = ((p2 - p0).cross(p1 - p0)).getNormalized();
+
+ mVertices[mIndices[i]].normal += normal;
+ mVertices[mIndices[i + 1]].normal += normal;
+ mVertices[mIndices[i + 2]].normal += normal;
+ }
+
+ for (PxU32 i = 0; i < numVertices; ++i)
+ mVertices[i].normal.normalize();
+
+ ID3D11DeviceContext* context;
+ mDevice->GetImmediateContext(&context);
+
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
+
+ V(context->Map(mVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mappedResource));
+ memcpy(mappedResource.pData, mVertices.data(), sizeof(Vertex) * mVertices.size());
+
+ context->Unmap(mVertexBuffer, 0);
+ }
+}
+
+void ClothRenderMesh::render(ID3D11DeviceContext& context) const
+{
+ context.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+
+ UINT strides[1] = { mVertexSize };
+ UINT offsets[1] = { 0 };
+ context.IASetVertexBuffers(0, 1, &mVertexBuffer, strides, offsets);
+
+ context.IASetIndexBuffer(mIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
+
+ if (mIndexBuffer)
+ context.DrawIndexed(mNumFaces*3, 0, 0);
+ else
+ context.Draw(mNumVertices, 0);
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/ClothRenderMesh.h b/NvCloth/samples/SampleBase/renderer/ClothRenderMesh.h
new file mode 100644
index 0000000..1af0027
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ClothRenderMesh.h
@@ -0,0 +1,68 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef CLOTH_RENDER_MESH_H
+#define CLOTH_RENDER_MESH_H
+
+#include "Renderable.h"
+
+namespace nv
+{
+namespace cloth
+{
+ class ClothMeshDesc;
+}
+}
+
+struct Vertex
+{
+ PxVec3 position;
+ PxVec3 normal;
+};
+
+/**
+Simple �loth render mesh
+*/
+class ClothRenderMesh : public IRenderMesh
+{
+public:
+ ClothRenderMesh(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces = nullptr, uint32_t numFaces = 0);
+ ClothRenderMesh(const nv::cloth::ClothMeshDesc& desc);
+ virtual ~ClothRenderMesh();
+
+ void update(const PxVec3* positions, uint32_t numVertices);
+
+ const std::vector<D3D11_INPUT_ELEMENT_DESC>& getInputElementDesc() const { return mInputDesc; }
+ void render(ID3D11DeviceContext& context) const;
+
+protected:
+ ClothRenderMesh();
+ void initialize(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces, uint32_t numFaces);
+
+private:
+ ID3D11Device* mDevice;
+
+ ID3D11Buffer* mVertexBuffer;
+ ID3D11Buffer* mIndexBuffer;
+
+ std::vector<Vertex> mVertices;
+ std::vector<uint16_t> mIndices;
+
+ uint32_t mNumFaces;
+ uint32_t mNumVertices;
+ uint32_t mVertexSize;
+
+ std::vector<D3D11_INPUT_ELEMENT_DESC> mInputDesc;
+};
+
+
+#endif //CLOTH_RENDER_MESH_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.cpp b/NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.cpp
new file mode 100644
index 0000000..11ba43b
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.cpp
@@ -0,0 +1,84 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#if 0
+#include "ConvexRenderMesh.h"
+#include "Renderer.h"
+#include "PxConvexMesh.h"
+
+
+struct Vertex
+{
+ PxVec3 position;
+ PxVec3 normal;
+};
+
+ConvexRenderMesh::ConvexRenderMesh(const PxConvexMesh* mesh)
+{
+ const uint32_t nbPolygons = mesh->getNbPolygons();
+ const uint8_t* indexBuffer = mesh->getIndexBuffer();
+ const PxVec3* meshVertices = mesh->getVertices();
+
+ uint32_t nbVerts = 0;
+ uint32_t nbFaces = 0;
+
+ for (uint32_t i = 0; i < nbPolygons; i++)
+ {
+ PxHullPolygon data;
+ mesh->getPolygonData(i, data);
+ uint32_t nbPolyVerts = data.mNbVerts;
+ nbVerts += nbPolyVerts;
+ nbFaces += (nbPolyVerts - 2) * 3;
+ }
+
+ std::vector<Vertex> vertices;
+ std::vector<uint16_t> faces;
+
+ vertices.resize(nbVerts);
+ faces.resize(nbFaces);
+
+ uint32_t vertCounter = 0;
+ uint32_t facesCounter = 0;
+ for (uint32_t i = 0; i < nbPolygons; i++)
+ {
+ PxHullPolygon data;
+ mesh->getPolygonData(i, data);
+
+ PxVec3 normal(data.mPlane[0], data.mPlane[1], data.mPlane[2]);
+
+ uint32_t vI0 = vertCounter;
+ for (uint32_t vI = 0; vI < data.mNbVerts; vI++)
+ {
+ vertices[vertCounter].position = meshVertices[indexBuffer[data.mIndexBase + vI]];
+ vertices[vertCounter].normal = normal;
+ vertCounter++;
+ }
+
+ for (uint32_t vI = 1; vI < uint32_t(data.mNbVerts) - 1; vI++)
+ {
+ faces[facesCounter++] = uint16_t(vI0);
+ faces[facesCounter++] = uint16_t(vI0 + vI + 1);
+ faces[facesCounter++] = uint16_t(vI0 + vI);
+ }
+ }
+
+ std::vector<D3D11_INPUT_ELEMENT_DESC> layout;
+ layout.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ layout.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+
+ initialize(vertices.data(), (uint32_t)vertices.size(), sizeof(Vertex), layout, faces.data(), nbFaces);
+}
+
+
+ConvexRenderMesh::~ConvexRenderMesh()
+{
+}
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.h b/NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.h
new file mode 100644
index 0000000..b6935d6
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ConvexRenderMesh.h
@@ -0,0 +1,34 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef CONVEX_RENDER_MESH_H
+#define CONVEX_RENDER_MESH_H
+
+#include "CustomRenderMesh.h"
+
+namespace physx
+{
+class PxConvexMesh;
+}
+
+
+/**
+PxConvexMesh render mesh
+(this class relates to PhysX more then to Renderer)
+*/
+class ConvexRenderMesh : public CustomRenderMesh
+{
+public:
+ ConvexRenderMesh(const PxConvexMesh* mesh);
+ virtual ~ConvexRenderMesh();
+};
+
+
+#endif //CONVEX_RENDER_MESH_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/CustomRenderMesh.cpp b/NvCloth/samples/SampleBase/renderer/CustomRenderMesh.cpp
new file mode 100644
index 0000000..8dfbbb6
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/CustomRenderMesh.cpp
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "CustomRenderMesh.h"
+
+
+CustomRenderMesh::CustomRenderMesh()
+ : m_indexBuffer(nullptr)
+{
+}
+
+CustomRenderMesh::CustomRenderMesh(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces, uint32_t numFaces)
+ : m_indexBuffer(nullptr)
+{
+ initialize(vertices, numVertices, vertexSize, inputDesc, faces, numFaces);
+}
+
+void CustomRenderMesh::initialize(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces, uint32_t numFaces)
+{
+ ID3D11Device* device = GetDeviceManager()->GetDevice();
+
+ m_inputDesc = inputDesc;
+ m_numVertices = numVertices;
+ m_vertexSize = vertexSize;
+ m_numFaces = numFaces;
+
+ // VB
+ {
+ D3D11_SUBRESOURCE_DATA vertexBufferData;
+
+ ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
+ vertexBufferData.pSysMem = vertices;
+
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ bufferDesc.ByteWidth = vertexSize * numVertices;
+ bufferDesc.CPUAccessFlags = 0;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
+
+ V(device->CreateBuffer(&bufferDesc, &vertexBufferData, &m_vertexBuffer));
+ }
+
+ // IB
+ if (faces != nullptr)
+ {
+ D3D11_SUBRESOURCE_DATA indexBufferData;
+
+ ZeroMemory(&indexBufferData, sizeof(indexBufferData));
+ indexBufferData.pSysMem = faces;
+
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
+ bufferDesc.ByteWidth = sizeof(uint16_t) * numFaces;
+ bufferDesc.CPUAccessFlags = 0;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
+
+ V(device->CreateBuffer(&bufferDesc, &indexBufferData, &m_indexBuffer));
+ }
+}
+
+CustomRenderMesh::~CustomRenderMesh()
+{
+ SAFE_RELEASE(m_vertexBuffer);
+ SAFE_RELEASE(m_indexBuffer);
+}
+
+
+void CustomRenderMesh::render(ID3D11DeviceContext& context) const
+{
+ context.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+
+ UINT strides[1] = { m_vertexSize };
+ UINT offsets[1] = { 0 };
+ context.IASetVertexBuffers(0, 1, &m_vertexBuffer, strides, offsets);
+
+ context.IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R16_UINT, 0);
+
+ if (m_indexBuffer)
+ context.DrawIndexed(m_numFaces, 0, 0);
+ else
+ context.Draw(m_numVertices, 0);
+}
+
diff --git a/NvCloth/samples/SampleBase/renderer/CustomRenderMesh.h b/NvCloth/samples/SampleBase/renderer/CustomRenderMesh.h
new file mode 100644
index 0000000..c00eafc
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/CustomRenderMesh.h
@@ -0,0 +1,43 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef CUSTOM_RENDER_MESH_H
+#define CUSTOM_RENDER_MESH_H
+
+#include "Renderable.h"
+
+
+class CustomRenderMesh : public IRenderMesh
+{
+public:
+ const std::vector<D3D11_INPUT_ELEMENT_DESC>& getInputElementDesc() const { return m_inputDesc; }
+ void render(ID3D11DeviceContext& context) const;
+
+ CustomRenderMesh(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces = nullptr, uint32_t numFaces = 0);
+ virtual ~CustomRenderMesh();
+
+protected:
+ CustomRenderMesh();
+ void initialize(const void* vertices, uint32_t numVertices, uint32_t vertexSize,
+ std::vector<D3D11_INPUT_ELEMENT_DESC>& inputDesc, const uint16_t* faces, uint32_t numFaces);
+
+private:
+ ID3D11Buffer* m_vertexBuffer;
+ ID3D11Buffer* m_indexBuffer;
+ uint32_t m_numFaces;
+ uint32_t m_numVertices;
+ uint32_t m_vertexSize;
+
+ std::vector<D3D11_INPUT_ELEMENT_DESC> m_inputDesc;
+};
+
+
+#endif //CUSTOM_RENDER_MESH_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/DebugRenderBuffer.h b/NvCloth/samples/SampleBase/renderer/DebugRenderBuffer.h
new file mode 100644
index 0000000..1ec11e8
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/DebugRenderBuffer.h
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef DEBUGRENDERBUFFER_H
+#define DEBUGRENDERBUFFER_H
+
+#include "PxRenderBuffer.h"
+#include <vector>
+
+using namespace physx;
+
+
+/**
+Simple PxRenderBuffer implementation for easy debug primitives adding
+*/
+class DebugRenderBuffer : public PxRenderBuffer
+{
+public:
+ ~DebugRenderBuffer() {}
+
+ virtual PxU32 getNbPoints() const { return 0; }
+ virtual const PxDebugPoint* getPoints() const { return nullptr; }
+
+ virtual PxU32 getNbLines() const { return static_cast<PxU32>(m_lines.size()); }
+ virtual const PxDebugLine* getLines() const { return m_lines.data(); }
+
+ virtual PxU32 getNbTriangles() const { return 0; }
+ virtual const PxDebugTriangle* getTriangles() const { return nullptr; }
+
+ virtual PxU32 getNbTexts() const { return 0; }
+ virtual const PxDebugText* getTexts() const { return nullptr; }
+
+ virtual void append(const PxRenderBuffer& other) {}
+ virtual void clear()
+ {
+ m_lines.clear();
+ }
+
+ std::vector<PxDebugLine> m_lines;
+};
+
+
+#endif //DEBUGRENDERBUFFER_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/Mesh.cpp b/NvCloth/samples/SampleBase/renderer/Mesh.cpp
new file mode 100644
index 0000000..687249e
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/Mesh.cpp
@@ -0,0 +1,13 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "Mesh.h"
+
diff --git a/NvCloth/samples/SampleBase/renderer/Mesh.h b/NvCloth/samples/SampleBase/renderer/Mesh.h
new file mode 100644
index 0000000..cdc595d
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/Mesh.h
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef MESH_H
+#define MESH_H
+
+#include <vector>
+#include "PxVec2.h"
+#include "PxVec3.h"
+
+
+class Mesh
+{
+ virtual uint32_t getVertexStride() = 0;
+ // ... TBD
+};
+
+/**
+SimpleMesh: position + normal + uv
+We use only this type everywhere, once other versions will be required we should generalize Mesh and refactor code.
+*/
+class SimpleMesh : public Mesh
+{
+public:
+
+ class Vertex
+ {
+ public:
+ physx::PxVec3 position;
+ physx::PxVec3 normal;
+ physx::PxVec2 uv;
+ };
+
+ virtual uint32_t getVertexStride() { return sizeof(Vertex); }
+
+ std::vector<Vertex> vertices;
+ std::vector<uint16_t> indices;
+
+ physx::PxVec3 extents;
+ physx::PxVec3 center;
+};
+
+
+#endif //MESH_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.cpp b/NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.cpp
new file mode 100644
index 0000000..3d324f8
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.cpp
@@ -0,0 +1,205 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "PrimitiveRenderMesh.h"
+#include "Renderer.h"
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Base Mesh internal class
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+PrimitiveRenderMesh::PrimitiveRenderMesh(const float v[], UINT numVertices)
+{
+ std::vector<D3D11_INPUT_ELEMENT_DESC> layout;
+ layout.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ layout.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+
+ initialize(v, numVertices, sizeof(float) * 6, layout, nullptr, 0);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Box Mesh
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+const float boxVertices[] =
+{
+ -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
+ 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
+ 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
+ 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
+ -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
+ -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
+
+ -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
+ 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
+ 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
+ 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
+ -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
+ -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
+
+ -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f,
+ -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,
+ -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f,
+ -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,
+ -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f,
+ -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f,
+
+ 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
+ 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
+ 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
+ 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
+ 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
+ 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
+
+ -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f,
+ 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f,
+ 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f,
+ 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f,
+ -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f,
+ -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f,
+
+ -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
+ 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
+ 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
+ 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
+ -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
+ -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f
+};
+
+BoxRenderMesh::BoxRenderMesh() : PrimitiveRenderMesh(boxVertices, sizeof(boxVertices) / (6 * sizeof(boxVertices[0]))) {}
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Plane Mesh
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+const float planeSize = 1.0f; // we use scaling instead
+const float planeTilesCount = 1000.0f;
+
+const float planeVertices[] =
+{
+ 0, planeSize, planeSize, 1.0f, 0.0f, 0.0f, planeTilesCount, planeTilesCount,
+ 0, planeSize, -planeSize, 1.0f, 0.0f, 0.0f, planeTilesCount, -planeTilesCount,
+ 0, -planeSize, -planeSize, 1.0f, 0.0f, 0.0f, -planeTilesCount, -planeTilesCount,
+ 0, -planeSize, -planeSize, 1.0f, 0.0f, 0.0f, -planeTilesCount, -planeTilesCount,
+ 0, -planeSize, planeSize, 1.0f, 0.0f, 0.0f, -planeTilesCount, planeTilesCount,
+ 0, planeSize, planeSize, 1.0f, 0.0f, 0.0f, planeTilesCount, planeTilesCount
+};
+
+PlaneRenderMesh::PlaneRenderMesh()
+{
+ std::vector<D3D11_INPUT_ELEMENT_DESC> layout;
+ layout.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ layout.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ layout.push_back({ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+
+ initialize(planeVertices, sizeof(planeVertices) / (8 * sizeof(planeVertices[0])), sizeof(float) * 8, layout, nullptr, 0);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Sphere Mesh
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+const uint32_t g_numSlices = 8; // along lines of longitude
+const uint32_t g_numStacks = 16; // along lines of latitude
+
+const uint32_t g_numSphereVertices = (g_numSlices * 2 + 1)*(g_numStacks + 1);
+const uint32_t g_numSphereIndices = g_numSlices * 2 * g_numStacks * 6;
+
+const uint32_t g_numConeVertices = (g_numSlices * 2 + 1) * 2;
+const uint32_t g_numConeIndices = g_numSlices * 2 * 6;
+
+PxVec3 g_spherePositions[g_numSphereVertices];
+uint16_t g_sphereIndices[g_numSphereIndices];
+
+void generateSphereMesh(uint16_t slices, uint16_t stacks, PxVec3* positions, uint16_t* indices)
+{
+ const PxF32 thetaStep = PxPi / stacks;
+ const PxF32 phiStep = PxTwoPi / (slices * 2);
+
+ PxF32 theta = 0.0f;
+
+ // generate vertices
+ for (uint16_t y = 0; y <= stacks; ++y)
+ {
+ PxF32 phi = 0.0f;
+
+ PxF32 cosTheta = PxCos(theta);
+ PxF32 sinTheta = PxSin(theta);
+
+ for (uint16_t x = 0; x <= slices * 2; ++x)
+ {
+ PxF32 cosPhi = PxCos(phi);
+ PxF32 sinPhi = PxSin(phi);
+
+ PxVec3 p(cosPhi*sinTheta, cosTheta, sinPhi*sinTheta);
+
+ // write vertex
+ *(positions++) = p;
+
+ phi += phiStep;
+ }
+
+ theta += thetaStep;
+ }
+
+ const uint16_t numRingQuads = 2 * slices;
+ const uint16_t numRingVerts = 2 * slices + 1;
+
+ // add faces
+ for (uint16_t y = 0; y < stacks; ++y)
+ {
+ for (uint16_t i = 0; i < numRingQuads; ++i)
+ {
+ // add a quad
+ *(indices++) = (y + 0)*numRingVerts + i;
+ *(indices++) = (y + 1)*numRingVerts + i;
+ *(indices++) = (y + 1)*numRingVerts + i + 1;
+
+ *(indices++) = (y + 1)*numRingVerts + i + 1;
+ *(indices++) = (y + 0)*numRingVerts + i + 1;
+ *(indices++) = (y + 0)*numRingVerts + i;
+ }
+ }
+}
+
+
+struct SphereVertex
+{
+ PxVec3 position;
+ PxVec3 normal;
+};
+
+SphereRenderMesh::SphereRenderMesh()
+{
+ generateSphereMesh(g_numSlices, g_numStacks, g_spherePositions, g_sphereIndices);
+
+ std::vector<SphereVertex> vertices;
+ for (uint32_t i = 0; i < g_numSphereVertices; i++)
+ {
+ vertices.push_back({ g_spherePositions[i], g_spherePositions[i] });
+ }
+
+ std::vector<D3D11_INPUT_ELEMENT_DESC> layout;
+ layout.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ layout.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+
+ initialize(vertices.data(), (uint32_t)vertices.size(), sizeof(SphereVertex), layout, g_sphereIndices, g_numSphereIndices);
+}
+
+
+SphereRenderMesh::~SphereRenderMesh()
+{
+}
diff --git a/NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.h b/NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.h
new file mode 100644
index 0000000..965e6cf
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/PrimitiveRenderMesh.h
@@ -0,0 +1,61 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef PRIMITIVE_RENDER_MESH_H
+#define PRIMITIVE_RENDER_MESH_H
+
+#include "Utils.h"
+#include <DirectXMath.h>
+
+#include <vector>
+#include "Renderable.h"
+#include "CustomRenderMesh.h"
+
+
+class PrimitiveRenderMesh : public CustomRenderMesh
+{
+protected:
+ PrimitiveRenderMesh(const float v[], UINT numVertices);
+};
+
+class BoxRenderMesh : public PrimitiveRenderMesh
+{
+public:
+ BoxRenderMesh();
+};
+
+
+class PlaneRenderMesh : public CustomRenderMesh
+{
+public:
+ PlaneRenderMesh();
+};
+
+
+class SphereRenderMesh : public CustomRenderMesh
+{
+public:
+ SphereRenderMesh();
+ virtual ~SphereRenderMesh();
+};
+
+
+struct PrimitiveRenderMeshType
+{
+ enum Enum
+ {
+ Box,
+ Plane,
+ Sphere,
+ Count
+ };
+};
+
+#endif //PRIMITIVE_RENDER_MESH_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/PxPhysXCommonConfig.h b/NvCloth/samples/SampleBase/renderer/PxPhysXCommonConfig.h
new file mode 100644
index 0000000..213eedd
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/PxPhysXCommonConfig.h
@@ -0,0 +1,92 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+
+#ifndef PX_PHYSICS_COMMON_NX
+#define PX_PHYSICS_COMMON_NX
+
+/** \addtogroup common
+@{ */
+
+#include "foundation/Px.h"
+
+
+// define API function declaration (public API only needed because of extensions)
+#if defined PX_PHYSX_STATIC_LIB || defined PX_PHYSX_CORE_STATIC_LIB
+ #define PX_PHYSX_CORE_API
+#else
+ #if PX_WINDOWS
+ #if defined PX_PHYSX_CORE_EXPORTS
+ #define PX_PHYSX_CORE_API __declspec(dllexport)
+ #else
+ #define PX_PHYSX_CORE_API __declspec(dllimport)
+ #endif
+ #elif PX_UNIX_FAMILY
+ #define PX_PHYSX_CORE_API PX_UNIX_EXPORT
+ #else
+ #define PX_PHYSX_CORE_API
+ #endif
+#endif
+
+#if PX_WINDOWS && !defined(__CUDACC__)
+ #if defined PX_PHYSX_COMMON_EXPORTS
+ #define PX_PHYSX_COMMON_API __declspec(dllexport)
+ #else
+ #define PX_PHYSX_COMMON_API __declspec(dllimport)
+ #endif
+#elif PX_UNIX_FAMILY
+ #define PX_PHYSX_COMMON_API PX_UNIX_EXPORT
+#else
+ #define PX_PHYSX_COMMON_API
+#endif
+
+// Changing these parameters requires recompilation of the SDK
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+ class PxCollection;
+ class PxBase;
+
+ class PxHeightField;
+ class PxHeightFieldDesc;
+
+ class PxTriangleMesh;
+ class PxConvexMesh;
+
+ typedef PxU32 PxTriangleID;
+ typedef PxU16 PxMaterialTableIndex;
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif
diff --git a/NvCloth/samples/SampleBase/renderer/PxRenderBuffer.h b/NvCloth/samples/SampleBase/renderer/PxRenderBuffer.h
new file mode 100644
index 0000000..8bbb37a
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/PxRenderBuffer.h
@@ -0,0 +1,157 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+
+#ifndef PX_FOUNDATION_PXRENDERBUFFER_H
+#define PX_FOUNDATION_PXRENDERBUFFER_H
+
+/** \addtogroup common
+@{
+*/
+
+#include "PxPhysXCommonConfig.h"
+#include "foundation/PxVec3.h"
+#include "foundation/PxMat33.h"
+#include "foundation/PxBounds3.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Default color values used for debug rendering.
+*/
+struct PxDebugColor
+{
+ enum Enum
+ {
+ eARGB_BLACK = 0xff000000,
+ eARGB_RED = 0xffff0000,
+ eARGB_GREEN = 0xff00ff00,
+ eARGB_BLUE = 0xff0000ff,
+ eARGB_YELLOW = 0xffffff00,
+ eARGB_MAGENTA = 0xffff00ff,
+ eARGB_CYAN = 0xff00ffff,
+ eARGB_WHITE = 0xffffffff,
+ eARGB_GREY = 0xff808080,
+ eARGB_DARKRED = 0x88880000,
+ eARGB_DARKGREEN = 0x88008800,
+ eARGB_DARKBLUE = 0x88000088
+ };
+};
+
+/**
+\brief Used to store a single point and colour for debug rendering.
+*/
+struct PxDebugPoint
+{
+ PxDebugPoint(const PxVec3& p, const PxU32& c)
+ : pos(p), color(c) {}
+
+ PxVec3 pos;
+ PxU32 color;
+};
+
+/**
+\brief Used to store a single line and colour for debug rendering.
+*/
+struct PxDebugLine
+{
+ PxDebugLine(const PxVec3& p0, const PxVec3& p1, const PxU32& c)
+ : pos0(p0), color0(c), pos1(p1), color1(c) {}
+
+ PxVec3 pos0;
+ PxU32 color0;
+ PxVec3 pos1;
+ PxU32 color1;
+};
+
+/**
+\brief Used to store a single triangle and colour for debug rendering.
+*/
+struct PxDebugTriangle
+{
+ PxDebugTriangle(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxU32& c)
+ : pos0(p0), color0(c), pos1(p1), color1(c), pos2(p2), color2(c) {}
+
+ PxVec3 pos0;
+ PxU32 color0;
+ PxVec3 pos1;
+ PxU32 color1;
+ PxVec3 pos2;
+ PxU32 color2;
+};
+
+/**
+\brief Used to store a text for debug rendering. Doesn't own 'string' array.
+*/
+struct PxDebugText
+{
+ PxDebugText() : string(0) {}
+
+ PxDebugText(const PxVec3& p, const PxReal& s, const PxU32& c, const char* str)
+ : position(p), size(s), color(c), string(str) {}
+
+ PxVec3 position;
+ PxReal size;
+ PxU32 color;
+ const char* string;
+};
+
+/**
+\brief Interface for points, lines, triangles, and text buffer.
+*/
+class PxRenderBuffer
+{
+public:
+ virtual ~PxRenderBuffer() {}
+
+ virtual PxU32 getNbPoints() const = 0;
+ virtual const PxDebugPoint* getPoints() const = 0;
+
+ virtual PxU32 getNbLines() const = 0;
+ virtual const PxDebugLine* getLines() const = 0;
+
+ virtual PxU32 getNbTriangles() const = 0;
+ virtual const PxDebugTriangle* getTriangles() const = 0;
+
+ virtual PxU32 getNbTexts() const = 0;
+ virtual const PxDebugText* getTexts() const = 0;
+
+ virtual void append(const PxRenderBuffer& other) = 0;
+ virtual void clear() = 0;
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif
diff --git a/NvCloth/samples/SampleBase/renderer/RenderMaterial.cpp b/NvCloth/samples/SampleBase/renderer/RenderMaterial.cpp
new file mode 100644
index 0000000..eb07c84
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RenderMaterial.cpp
@@ -0,0 +1,206 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "RenderMaterial.h"
+#include <DirectXMath.h>
+#include "ShaderUtils.h"
+#include "Renderer.h"
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// RenderMaterial
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+RenderMaterial::RenderMaterial(ResourceManager& resourceCallback, const char* shaderFileName,
+ const char* textureFileName, BlendMode blendMode)
+{
+ this->initialize(resourceCallback, shaderFileName, textureFileName, blendMode);
+}
+
+void RenderMaterial::initialize(ResourceManager& resourceCallback, const char* shaderFileName, const char* textureFileName, BlendMode blendMode)
+{
+ std::vector<std::string> v;
+ v.push_back(shaderFileName);
+ initialize(resourceCallback, v, textureFileName, blendMode);
+}
+
+void RenderMaterial::initialize(ResourceManager& resourceCallback, std::vector<std::string> shaderFileNames, const char* textureFileName, BlendMode blendMode)
+{
+ mTextureSRV = nullptr;
+ mTexture = nullptr;
+ mBlendState = nullptr;
+ mTextureFileName = textureFileName;
+
+ for (uint32_t i = 0; i < shaderFileNames.size(); i++)
+ {
+ const ShaderFileResource* resource = resourceCallback.requestShaderFile(shaderFileNames[i].c_str());
+ if (resource)
+ {
+ std::string shaderFilePath = resource->path;
+ mShaderFilePathes.push_back(shaderFilePath);
+ }
+ }
+ mShaderGroups.reserve(mShaderFilePathes.size());
+
+ if (!mTextureFileName.empty())
+ {
+ mTexture = resourceCallback.requestTexture(mTextureFileName.c_str());
+ }
+
+ setBlending(blendMode);
+
+ reload();
+}
+
+void RenderMaterial::releaseReloadableResources()
+{
+ for (std::vector<ShaderGroup*>::iterator it = mShaderGroups.begin(); it != mShaderGroups.end(); it++)
+ {
+ delete *it;
+ }
+ mShaderGroups.clear();
+
+ SAFE_RELEASE(mTextureSRV);
+}
+
+RenderMaterial::~RenderMaterial()
+{
+ releaseReloadableResources();
+ SAFE_RELEASE(mBlendState);
+}
+
+void RenderMaterial::setBlending(BlendMode blendMode)
+{
+ mBlendMode = blendMode;
+
+ SAFE_RELEASE(mBlendState);
+
+ D3D11_BLEND_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+
+ switch (blendMode)
+ {
+ case BLEND_NONE:
+ desc.RenderTarget[0].BlendEnable = FALSE;
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
+ break;
+ case BLEND_ALPHA_BLENDING:
+ desc.AlphaToCoverageEnable = FALSE;
+ desc.IndependentBlendEnable = TRUE;
+ desc.RenderTarget[0].BlendEnable = TRUE;
+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
+ break;
+ case BLEND_ADDITIVE: // actually, is's additive by alpha
+ desc.AlphaToCoverageEnable = FALSE;
+ desc.IndependentBlendEnable = TRUE;
+ desc.RenderTarget[0].BlendEnable = TRUE;
+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;
+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
+ break;
+ default:
+ PX_ALWAYS_ASSERT_MESSAGE("Unknown blend mode");
+ }
+
+ ID3D11Device* device = GetDeviceManager()->GetDevice();
+ V(device->CreateBlendState(&desc, &mBlendState));
+}
+
+void RenderMaterial::reload()
+{
+ releaseReloadableResources();
+
+ // load shaders
+ ID3D11Device* device = GetDeviceManager()->GetDevice();
+
+ for (std::vector<std::string>::iterator it = mShaderFilePathes.begin(); it != mShaderFilePathes.end(); it++)
+ {
+ const char* shaderFilePath = (*it).c_str();
+ ShaderGroup* shaderGroup = new ShaderGroup();
+ V(createShaderFromFile(device, shaderFilePath, "VS", &(shaderGroup->vs), shaderGroup->buffer));
+ createShaderFromFile(device, shaderFilePath, "PS", &shaderGroup->ps);
+ createShaderFromFile(device, shaderFilePath, "GS", &shaderGroup->gs);
+ mShaderGroups.push_back(shaderGroup);
+ }
+
+ // load texture
+ if (mTexture)
+ {
+ V(DirectX::CreateShaderResourceView(device, mTexture->image.GetImages(), mTexture->image.GetImageCount(),
+ mTexture->metaData, &mTextureSRV));
+ }
+}
+
+
+
+RenderMaterial::InstancePtr RenderMaterial::getMaterialInstance(const IRenderMesh* mesh)
+{
+ // look in cache
+ auto it = mRenderMeshToInstanceMap.find(mesh);
+ if (it != mRenderMeshToInstanceMap.end())
+ {
+ if (!(*it).second.expired())
+ {
+ return (*it).second.lock();
+ }
+ }
+
+ // create new
+ const std::vector<D3D11_INPUT_ELEMENT_DESC>& descs = mesh->getInputElementDesc();
+ RenderMaterial::InstancePtr instance = getMaterialInstance(&descs[0], (uint32_t)descs.size());
+ mRenderMeshToInstanceMap[mesh] = instance;
+ return instance;
+}
+
+RenderMaterial::InstancePtr RenderMaterial::getMaterialInstance(const D3D11_INPUT_ELEMENT_DESC* elementDescs, uint32_t numElements)
+{
+ ID3D11Device* device = GetDeviceManager()->GetDevice();
+
+ for (uint32_t i = 0; i < mShaderGroups.size(); i++)
+ {
+ if (mShaderGroups[i]->buffer == NULL)
+ continue;
+
+ ID3D11InputLayout* inputLayout = NULL;
+ device->CreateInputLayout(elementDescs, numElements, mShaderGroups[i]->buffer->GetBufferPointer(), mShaderGroups[i]->buffer->GetBufferSize(), &inputLayout);
+
+ if (inputLayout)
+ {
+ RenderMaterial::InstancePtr materialInstance(new Instance(*this, inputLayout, i));
+ return materialInstance;
+ }
+ }
+ PX_ALWAYS_ASSERT();
+ return NULL;
+}
+
+void RenderMaterial::Instance::bind(ID3D11DeviceContext& context, uint32_t slot, bool depthStencilOnly)
+{
+ mMaterial.mShaderGroups[mShaderNum]->Set(&context, !depthStencilOnly);
+
+ context.OMSetBlendState(mMaterial.mBlendState, nullptr, 0xFFFFFFFF);
+ context.PSSetShaderResources(slot, 1, &(mMaterial.mTextureSRV));
+ context.IASetInputLayout(mInputLayout);
+}
+
+bool RenderMaterial::Instance::isValid()
+{
+ return mMaterial.mShaderGroups.size() > 0 && mMaterial.mShaderGroups[mShaderNum]->IsValid();
+}
diff --git a/NvCloth/samples/SampleBase/renderer/RenderMaterial.h b/NvCloth/samples/SampleBase/renderer/RenderMaterial.h
new file mode 100644
index 0000000..3f95389
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RenderMaterial.h
@@ -0,0 +1,118 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RENDER_MATERIAL_H
+#define RENDER_MATERIAL_H
+
+#include "Utils.h"
+#include "DirectXTex.h"
+
+#include <string>
+#include <vector>
+#include <list>
+#include <map>
+#include <memory>
+
+
+class IRenderMesh;
+class ResourceManager;
+struct TextureResource;
+
+
+class RenderMaterial
+{
+ public:
+
+ enum BlendMode
+ {
+ BLEND_NONE,
+ BLEND_ALPHA_BLENDING,
+ BLEND_ADDITIVE
+ };
+
+ RenderMaterial(ResourceManager& resourceProvider, const char* shaderFileName, const char* textureFileName = "", BlendMode blendMode = BLEND_NONE);
+ ~RenderMaterial();
+
+ void setBlending(BlendMode blendMode);
+ BlendMode getBlending() const { return mBlendMode; }
+
+ void reload();
+
+ class Instance
+ {
+ public:
+ Instance(RenderMaterial& material, ID3D11InputLayout* inputLayout, uint32_t shaderNum = 0) : mMaterial(material), mInputLayout(inputLayout), mShaderNum(shaderNum) {}
+ ~Instance() { SAFE_RELEASE(mInputLayout); }
+
+ bool isValid();
+ void bind(ID3D11DeviceContext& context, uint32_t slot, bool depthStencilOnly = false);
+ RenderMaterial& getMaterial() const { return mMaterial; }
+ private:
+ RenderMaterial& mMaterial;
+ ID3D11InputLayout* mInputLayout;
+ uint32_t mShaderNum;
+ };
+
+ typedef std::shared_ptr<Instance> InstancePtr;
+
+ InstancePtr getMaterialInstance(const IRenderMesh* mesh);
+ InstancePtr getMaterialInstance(const D3D11_INPUT_ELEMENT_DESC* elementDescs, uint32_t numElements);
+
+ private:
+ void initialize(ResourceManager& resourceCallback, const char* shaderFileName, const char* textureFileName, BlendMode blendMode);
+ void initialize(ResourceManager&resourceProvider, std::vector<std::string> shaderFileNames, const char* textureFileName, BlendMode blendMode);
+
+ void releaseReloadableResources();
+
+ std::string mShaderFileName;
+ std::string mTextureFileName;
+
+ struct ShaderGroup
+ {
+ ShaderGroup() : vs(nullptr), gs(nullptr), ps(nullptr), buffer(nullptr)
+ {
+ }
+ ~ShaderGroup()
+ {
+ Release();
+ }
+ void Release()
+ {
+ SAFE_RELEASE(vs);
+ SAFE_RELEASE(gs);
+ SAFE_RELEASE(ps);
+ SAFE_RELEASE(buffer);
+ }
+ void Set(ID3D11DeviceContext* c, bool setPixelShader = true)
+ {
+ c->VSSetShader(vs, nullptr, 0);
+ c->GSSetShader(gs, nullptr, 0);
+ c->PSSetShader(setPixelShader ? ps : nullptr, nullptr, 0);
+ }
+ bool IsValid()
+ {
+ return vs != nullptr;
+ }
+ ID3D11VertexShader* vs;
+ ID3D11GeometryShader* gs;
+ ID3D11PixelShader* ps;
+ ID3DBlob* buffer;
+ };
+
+ std::map<const IRenderMesh*, std::weak_ptr<Instance>> mRenderMeshToInstanceMap;
+ const TextureResource* mTexture;
+ ID3D11ShaderResourceView* mTextureSRV;
+ std::vector<std::string> mShaderFilePathes;
+ std::vector<ShaderGroup*> mShaderGroups;
+ ID3D11BlendState* mBlendState;
+ BlendMode mBlendMode;
+};
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/RenderUtils.h b/NvCloth/samples/SampleBase/renderer/RenderUtils.h
new file mode 100644
index 0000000..f4d007b
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RenderUtils.h
@@ -0,0 +1,78 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RENDER_UTILS_H
+#define RENDER_UTILS_H
+
+#include "DirectXTex.h"
+#include <DirectXMath.h>
+#include "PxMat44.h"
+#include "PxVec3.h"
+#include "PxVec4.h"
+
+static DirectX::XMFLOAT4 getRandomPastelColor()
+{
+ float r = ((double)rand() / (RAND_MAX)) * 0.5f + 0.5f;
+ float g = ((double)rand() / (RAND_MAX)) * 0.5f + 0.5f;
+ float b = ((double)rand() / (RAND_MAX)) * 0.5f + 0.5f;
+ return DirectX::XMFLOAT4(r, g, b, 1.0f);
+}
+
+static physx::PxMat44 XMMATRIXToPxMat44(const DirectX::XMMATRIX& mat)
+{
+ physx::PxMat44 m;
+ memcpy(const_cast<float*>(m.front()), &mat.r[0], 4 * 4 * sizeof(float));
+ return m;
+}
+
+static DirectX::XMMATRIX PxMat44ToXMMATRIX(const physx::PxMat44& mat)
+{
+ return DirectX::XMMATRIX(mat.front());
+}
+
+static physx::PxVec4 XMVECTORToPxVec4(const DirectX::XMVECTOR& vec)
+{
+ DirectX::XMFLOAT4 f;
+ DirectX::XMStoreFloat4(&f, vec);
+ return physx::PxVec4(f.x, f.y, f.z, f.w);
+}
+
+static physx::PxVec3 XMFLOAT3ToPxVec3(const DirectX::XMFLOAT3& vec)
+{
+ return physx::PxVec3(vec.x, vec.y, vec.z);
+}
+
+static physx::PxVec4 XMFLOAT4ToPxVec4(const DirectX::XMFLOAT4& vec)
+{
+ return physx::PxVec4(vec.x, vec.y, vec.z, vec.w);
+}
+
+static uint32_t XMFLOAT4ToU32Color(const DirectX::XMFLOAT4& color)
+{
+ uint32_t c = 0;
+ c |= (int)(color.w * 255); c <<= 8;
+ c |= (int)(color.z * 255); c <<= 8;
+ c |= (int)(color.y * 255); c <<= 8;
+ c |= (int)(color.x * 255);
+ return c;
+}
+
+static DirectX::XMFLOAT4 XMFLOAT4Lerp(const DirectX::XMFLOAT4 v0, const DirectX::XMFLOAT4 v1, float val)
+{
+ DirectX::XMFLOAT4 v(
+ v0.x * (1 - val) + v1.x * val,
+ v0.y * (1 - val) + v1.y * val,
+ v0.z * (1 - val) + v1.z * val,
+ v0.w * (1 - val) + v1.w * val
+ );
+ return v;
+}
+
+#endif //RENDER_UTILS_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/Renderable.cpp b/NvCloth/samples/SampleBase/renderer/Renderable.cpp
new file mode 100644
index 0000000..51a151d
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/Renderable.cpp
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "Renderable.h"
+#include "Renderer.h"
+#include "RenderUtils.h"
+
+const DirectX::XMFLOAT4 DEFAULT_COLOR(0.5f, 0.5f, 0.5f, 1.0f);
+
+Renderable::Renderable(IRenderMesh& mesh, RenderMaterial& material) : m_mesh(mesh), m_scale(1, 1, 1), m_color(DEFAULT_COLOR), m_hidden(false), m_transform(PxIdentity)
+{
+ setMaterial(material);
+}
+
+void Renderable::setMaterial(RenderMaterial& material)
+{
+ m_materialInstance = material.getMaterialInstance(&m_mesh);
+}
+
+void Renderable::render(Renderer& renderer, bool depthStencilOnly) const
+{
+ if (!m_materialInstance->isValid())
+ {
+ PX_ALWAYS_ASSERT();
+ return;
+ }
+
+ m_materialInstance->bind(*renderer.m_context, 0, depthStencilOnly);
+
+ // setup object CB
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ renderer.m_context->Map(renderer.m_objectCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
+ Renderer::CBObject* objectBuffer = (Renderer::CBObject*)mappedResource.pData;
+ objectBuffer->world = PxMat44ToXMMATRIX(getModelMatrix());
+ objectBuffer->color = getColor();
+ renderer.m_context->Unmap(renderer.m_objectCB, 0);
+ }
+
+ m_mesh.render(*renderer.m_context);
+}
diff --git a/NvCloth/samples/SampleBase/renderer/Renderable.h b/NvCloth/samples/SampleBase/renderer/Renderable.h
new file mode 100644
index 0000000..da94144
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/Renderable.h
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RENDERABLE_H
+#define RENDERABLE_H
+
+#include "RenderMaterial.h"
+#include <DirectXMath.h>
+#include "PxMat44.h"
+#include "PxVec3.h"
+#include "PxVec4.h"
+
+using namespace physx;
+
+class Renderer;
+
+/**
+RenderMesh interface, used by Renderable
+*/
+class IRenderMesh
+{
+public:
+ virtual ~IRenderMesh() {}
+ virtual const std::vector<D3D11_INPUT_ELEMENT_DESC>& getInputElementDesc() const = 0;
+ virtual void render(ID3D11DeviceContext& context) const = 0;
+};
+
+/**
+Renderable, represents single object renderer by Renderer.
+Basically Renderable = RenderMaterial + RenderMesh
+*/
+class Renderable
+{
+public:
+ //////// public API ////////
+
+ void setMaterial(RenderMaterial& material);
+
+ PxMat44 getModelMatrix() const
+ {
+ return PxMat44(m_transform) * PxMat44(PxVec4(m_scale, 1));
+ }
+
+ void setTransform(PxTransform& transform)
+ {
+ m_transform = transform;
+ }
+
+ const PxTransform& getTransform() const
+ {
+ return m_transform;
+ }
+
+ void setScale(PxVec3 scale)
+ {
+ m_scale = scale;
+ }
+
+ const PxVec3& getScale() const
+ {
+ return m_scale;
+ }
+
+ void setColor(DirectX::XMFLOAT4 color)
+ {
+ m_color = color;
+ }
+ DirectX::XMFLOAT4 getColor() const
+ {
+ return m_color;
+ }
+
+ void setHidden(bool hidden)
+ {
+ m_hidden = hidden;
+ }
+
+ bool isHidden() const
+ {
+ return m_hidden;
+ }
+
+ bool isTransparent() const
+ {
+ return !(m_materialInstance->getMaterial().getBlending() == RenderMaterial::BLEND_NONE);
+ }
+
+ RenderMaterial& getMaterial() const { return m_materialInstance->getMaterial(); }
+
+private:
+ //////// methods used by Renderer ////////
+
+ friend class Renderer;
+
+ void render(Renderer& renderer) const
+ {
+ render(renderer, false);
+ }
+
+ void renderDepthStencilOnly(Renderer& renderer) const
+ {
+ render(renderer, true);
+ }
+
+ Renderable(IRenderMesh& mesh, RenderMaterial& material);
+
+ void render(Renderer& renderer, bool depthStencilOnly) const;
+
+
+ //////// internal data ////////
+
+ DirectX::XMFLOAT4 m_color;
+ PxTransform m_transform;
+ PxVec3 m_scale;
+
+ RenderMaterial::InstancePtr m_materialInstance;
+ IRenderMesh& m_mesh;
+ bool m_hidden;
+};
+
+#endif //RENDERABLE_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/Renderer.cpp b/NvCloth/samples/SampleBase/renderer/Renderer.cpp
new file mode 100644
index 0000000..48685d9
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/Renderer.cpp
@@ -0,0 +1,730 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "Renderer.h"
+#include "RenderUtils.h"
+#include "UIHelpers.h"
+#include "SampleProfiler.h"
+
+#include "PxRenderBuffer.h"
+using namespace physx;
+
+#include <set>
+
+
+const float CAMERA_CLIP_NEAR = 1.0f;
+const float CAMERA_CLIP_FAR = 1000.00f;
+
+const float CLEAR_SCENE_COLOR[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Renderer
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+Renderer::Renderer()
+: m_cameraCB(nullptr)
+, m_worldCB(nullptr)
+, m_objectCB(nullptr)
+, m_RSState(nullptr)
+, m_opaqueRenderDSState(nullptr)
+, m_transparencyRenderDSState(nullptr)
+, m_DSTexture(nullptr)
+, m_DSView(nullptr)
+, m_DSTextureSRV(nullptr)
+, m_pointSampler(nullptr)
+, m_linearSampler(nullptr)
+, m_wireframeMode(false)
+, m_debugPrimitiveVB(nullptr)
+, m_debugPrimitiveVBVerticesCount(0)
+, m_shadowEnabled(true)
+, m_HBAOEnabled(true)
+, m_visibleOpaqueRenderablesCount(0)
+, m_visibleTransparentRenderablesCount(0)
+{
+ m_worldCBData.ambientColor = DirectX::XMFLOAT3(0.21f, 0.21f, 0.22f);
+ m_worldCBData.pointLightColor = DirectX::XMFLOAT3(1.0f, 1.0f, 1.0f);
+ m_worldCBData.pointLightPos = DirectX::XMFLOAT3(0.0f, 30.0f, 12.0f);
+ m_worldCBData.dirLightColor = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f);
+ m_worldCBData.dirLightDir = DirectX::XMFLOAT3(-0.08f, -0.34f, -0.91f);
+ m_worldCBData.specularPower = 140.0f;
+ m_worldCBData.specularIntensity = 0.4f;
+
+ toggleCameraSpeed(false);
+}
+
+Renderer::~Renderer()
+{
+}
+
+void Renderer::initializeDefaultRSState()
+{
+ SAFE_RELEASE(m_RSState);
+ D3D11_RASTERIZER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.CullMode = D3D11_CULL_NONE;
+ desc.FillMode = m_wireframeMode ? D3D11_FILL_WIREFRAME : D3D11_FILL_SOLID;
+ desc.AntialiasedLineEnable = FALSE;
+ desc.DepthBias = 0;
+ desc.DepthBiasClamp = 0;
+ desc.DepthClipEnable = TRUE;
+ desc.FrontCounterClockwise = FALSE;
+ desc.MultisampleEnable = TRUE;
+ desc.ScissorEnable = FALSE;
+ desc.SlopeScaledDepthBias = 0;
+
+ V(m_device->CreateRasterizerState(&desc, &m_RSState));
+}
+
+HRESULT Renderer::DeviceCreated(ID3D11Device* device)
+{
+ m_device = device;
+
+ // Camera constant buffer
+ {
+ D3D11_BUFFER_DESC buffer_desc;
+ ZeroMemory(&buffer_desc, sizeof(buffer_desc));
+ buffer_desc.Usage = D3D11_USAGE_DYNAMIC;
+ buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ buffer_desc.ByteWidth = sizeof(CBCamera);
+ _ASSERT((buffer_desc.ByteWidth % 16) == 0);
+
+ V(device->CreateBuffer(&buffer_desc, nullptr, &m_cameraCB));
+ }
+
+ // World constant buffer
+ {
+ D3D11_BUFFER_DESC buffer_desc;
+ ZeroMemory(&buffer_desc, sizeof(buffer_desc));
+ buffer_desc.Usage = D3D11_USAGE_DYNAMIC;
+ buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ buffer_desc.ByteWidth = sizeof(CBWorld);
+ _ASSERT((buffer_desc.ByteWidth % 16) == 0);
+
+ V(device->CreateBuffer(&buffer_desc, nullptr, &m_worldCB));
+ }
+
+ // Object constant buffer
+ {
+ D3D11_BUFFER_DESC buffer_desc;
+ ZeroMemory(&buffer_desc, sizeof(buffer_desc));
+ buffer_desc.Usage = D3D11_USAGE_DYNAMIC;
+ buffer_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ buffer_desc.ByteWidth = sizeof(CBObject);
+ _ASSERT((buffer_desc.ByteWidth % 16) == 0);
+
+ V(device->CreateBuffer(&buffer_desc, nullptr, &m_objectCB));
+ }
+
+ // Opaque Render Depth-Stencil state
+ {
+ D3D11_DEPTH_STENCIL_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.StencilEnable = FALSE;
+ desc.DepthEnable = TRUE;
+ desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
+ desc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
+
+ V(device->CreateDepthStencilState(&desc, &m_opaqueRenderDSState));
+ }
+
+ // Transparency Render Depth-Stencil state
+ {
+ D3D11_DEPTH_STENCIL_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.StencilEnable = FALSE;
+ desc.DepthEnable = TRUE;
+ desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
+ desc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
+
+ V(device->CreateDepthStencilState(&desc, &m_transparencyRenderDSState));
+ }
+
+ // Linear sampler
+ {
+ D3D11_SAMPLER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
+ desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
+ desc.MaxAnisotropy = 1;
+ desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
+ desc.MinLOD = 0;
+ desc.MaxLOD = D3D11_FLOAT32_MAX;
+ V(device->CreateSamplerState(&desc, &m_linearSampler));
+ }
+
+ // Point sampler
+ {
+ D3D11_SAMPLER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
+ desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
+ desc.MaxAnisotropy = 1;
+ desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
+ desc.MinLOD = 0;
+ desc.MaxLOD = D3D11_FLOAT32_MAX;
+ V(device->CreateSamplerState(&desc, &m_pointSampler));
+ }
+
+ // Rasterizer state
+ initializeDefaultRSState();
+
+ // init primitive render meshes
+ for (uint32_t i = 0; i < PrimitiveRenderMeshType::Count; i++)
+ {
+ m_primitiveRenderMeshes[i] = nullptr;
+ }
+
+ // init shadows
+ ID3D11DeviceContext* pd3dDeviceContext;
+ m_device->GetImmediateContext(&pd3dDeviceContext);
+ m_shadow.createResources(m_device, pd3dDeviceContext, &m_camera);
+
+ // init hbao
+ m_HBAO.createResources(m_device);
+
+ return S_OK;
+}
+
+void Renderer::DeviceDestroyed()
+{
+ SAFE_RELEASE(m_cameraCB);
+ SAFE_RELEASE(m_worldCB);
+ SAFE_RELEASE(m_objectCB);
+ SAFE_RELEASE(m_RSState);
+ SAFE_RELEASE(m_opaqueRenderDSState);
+ SAFE_RELEASE(m_transparencyRenderDSState);
+ SAFE_RELEASE(m_pointSampler);
+ SAFE_RELEASE(m_linearSampler);
+ SAFE_RELEASE(m_debugPrimitiveVB);
+ SAFE_RELEASE(m_DSTexture);
+ SAFE_RELEASE(m_DSView);
+ SAFE_RELEASE(m_DSTextureSRV);
+
+ for (uint32_t i = 0; i < PrimitiveRenderMeshType::Count; i++)
+ {
+ SAFE_DELETE(m_primitiveRenderMeshes[i]);
+ }
+}
+
+void Renderer::onInitialize()
+{
+ // search paths
+ m_resourceManager.addSearchDir("..\\..\\samples\\resources");
+ m_resourceManager.addSearchDir("..\\..\\..\\samples\\resources");
+ for (const std::string& d : getManager()->getConfig().additionalResourcesDir)
+ {
+ m_resourceManager.addSearchDir(d.c_str());
+ }
+
+ // debug primitive render material and input layout
+ {
+ m_debugPrimitiveRenderMaterial = new RenderMaterial(m_resourceManager, "debug_primitive", "");
+
+ D3D11_INPUT_ELEMENT_DESC layout[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
+ };
+
+ m_debugPrimitiveRenderMaterialInstance = m_debugPrimitiveRenderMaterial->getMaterialInstance(layout, ARRAYSIZE(layout));
+ }
+}
+
+void Renderer::onTerminate()
+{
+ SAFE_DELETE(m_debugPrimitiveRenderMaterial);
+}
+
+void Renderer::BackBufferResized(ID3D11Device* /*device*/, const DXGI_SURFACE_DESC* sd)
+{
+ // Setup the camera's projection parameters
+ m_screenWidth = sd->Width;
+ m_screenHeight = sd->Height;
+ float fAspectRatio = m_screenWidth / m_screenHeight;
+ m_camera.SetProjParams(DirectX::XM_PIDIV4, fAspectRatio, CAMERA_CLIP_NEAR, CAMERA_CLIP_FAR);
+
+ SAFE_RELEASE(m_DSTexture);
+ SAFE_RELEASE(m_DSView);
+ SAFE_RELEASE(m_DSTextureSRV);
+
+ // create a new Depth-Stencil texture
+ {
+ D3D11_TEXTURE2D_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Width = sd->Width;
+ desc.Height = sd->Height;
+ desc.MipLevels = 1;
+ desc.ArraySize = 1;
+ desc.Format = DXGI_FORMAT_R32_TYPELESS; // Use a typeless type here so that it can be both depth-stencil and shader resource.
+ desc.SampleDesc.Count = sd->SampleDesc.Count;
+ desc.SampleDesc.Quality = sd->SampleDesc.Quality;
+ desc.Usage = D3D11_USAGE_DEFAULT;
+ desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
+ desc.CPUAccessFlags = 0;
+ desc.MiscFlags = 0;
+ V(m_device->CreateTexture2D(&desc, NULL, &m_DSTexture));
+ }
+
+ // create Depth-Stencil view
+ {
+ D3D11_DEPTH_STENCIL_VIEW_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.ViewDimension = sd->SampleDesc.Count > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D;
+ desc.Format = DXGI_FORMAT_D32_FLOAT; // Make the view see this as D32_FLOAT instead of typeless
+ desc.Texture2D.MipSlice = 0;
+ V(m_device->CreateDepthStencilView(m_DSTexture, &desc, &m_DSView));
+ }
+
+ // create Depth-Stencil shader resource view
+ {
+ D3D11_SHADER_RESOURCE_VIEW_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Format = DXGI_FORMAT_R32_FLOAT; // Make the shaders see this as R32_FLOAT instead of typeless
+ desc.ViewDimension = sd->SampleDesc.Count > 1 ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
+ desc.Texture2D.MipLevels = 1;
+ desc.Texture2D.MostDetailedMip = 0;
+ V(m_device->CreateShaderResourceView(m_DSTexture, &desc, &m_DSTextureSRV));
+ }
+
+ // setup viewport
+ m_viewport.Width = (FLOAT)sd->Width;
+ m_viewport.Height = (FLOAT)sd->Height;
+ m_viewport.MinDepth = 0;
+ m_viewport.MaxDepth = 1;
+ m_viewport.TopLeftX = 0;
+ m_viewport.TopLeftY = 0;
+
+ // setup shadows
+ m_shadow.setScreenResolution(0, sd->Width, sd->Height, sd->SampleDesc.Count, nullptr);
+}
+
+void Renderer::setAllConstantBuffers(ID3D11DeviceContext* ctx)
+{
+ ID3D11Buffer* cbs[3] = { m_cameraCB, m_worldCB, m_objectCB };
+ ctx->VSSetConstantBuffers(0, 3, cbs);
+ ctx->GSSetConstantBuffers(0, 3, cbs);
+ ctx->PSSetConstantBuffers(0, 3, cbs);
+}
+
+void Renderer::Render(ID3D11Device* /*device*/, ID3D11DeviceContext* ctx, ID3D11RenderTargetView* pRTV,
+ ID3D11DepthStencilView*)
+{
+ PROFILER_SCOPED_FUNCTION();
+
+ m_context = ctx;
+
+ ctx->ClearRenderTargetView(pRTV, CLEAR_SCENE_COLOR);
+ ctx->ClearDepthStencilView(m_DSView, D3D11_CLEAR_DEPTH, 1.0, 0);
+ ctx->RSSetViewports(1, &m_viewport);
+
+ // needed matrices
+ DirectX::XMMATRIX viewMatrix = m_camera.GetViewMatrix();
+ DirectX::XMMATRIX projMatrix = m_camera.GetProjMatrix();
+ DirectX::XMMATRIX projMatrixInv = DirectX::XMMatrixInverse(NULL, projMatrix);
+ DirectX::XMMATRIX viewProjMatrix = viewMatrix * projMatrix;
+
+ // Fill Camera constant buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ ctx->Map(m_cameraCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
+ CBCamera* cameraBuffer = (CBCamera*)mappedResource.pData;
+ cameraBuffer->viewProjection = viewProjMatrix;
+ cameraBuffer->projectionInv = projMatrixInv;
+ DirectX::XMStoreFloat3(&(cameraBuffer->viewPos), m_camera.GetEyePt());
+ ctx->Unmap(m_cameraCB, 0);
+ }
+
+ // Fill World constant buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ ctx->Map(m_worldCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
+ CBWorld* worldBuffer = (CBWorld*)mappedResource.pData;
+ memcpy(worldBuffer, &m_worldCBData, sizeof(m_worldCBData));
+ //worldBuffer->ambientColor = m_CBWorldData.ambientColor;
+ //worldBuffer->pointLightPos = m_CBWorldData.pointLightPos;
+ //worldBuffer->pointLightColor = m_CBWorldData.pointLightColor;
+ //worldBuffer->dirLightDir = m_CBWorldData.dirLightDir;
+ //worldBuffer->specularPower = m_CBWorldData.specularPower;
+ //worldBuffer->dirLightColor = m_CBWorldData.dirLightColor;
+ //worldBuffer->specularIntensity = m_CBWorldData.specularIntensity;
+ ctx->Unmap(m_worldCB, 0);
+ }
+
+ ctx->RSSetState(m_RSState);
+ ctx->PSSetSamplers(0, 1, &m_linearSampler);
+ ctx->PSSetSamplers(1, 1, &m_pointSampler);
+
+
+ if (m_shadowEnabled)
+ {
+ // render depth only
+ {
+ ctx->OMSetRenderTargets(0, nullptr, m_DSView);
+ ctx->OMSetDepthStencilState(m_opaqueRenderDSState, 0xFF);
+
+ // set constants buffers
+ setAllConstantBuffers(ctx);
+
+ for (auto it = m_renderables.begin(); it != m_renderables.end(); it++)
+ {
+ if (!(*it)->isTransparent() && !(*it)->isHidden())
+ (*it)->renderDepthStencilOnly(*this);
+ }
+ }
+
+ // render shadow map
+ m_shadow.renderShadowMaps(this);
+
+ // render shadow buffer
+ ctx->OMSetRenderTargets(0, nullptr, nullptr);
+ m_shadow.renderShadowBuffer(m_DSTextureSRV, nullptr);
+ }
+
+ // Opaque render
+ {
+ ctx->RSSetViewports(1, &m_viewport);
+ ctx->RSSetState(m_RSState);
+ ctx->OMSetRenderTargets(1, &pRTV, m_DSView);
+ ctx->OMSetDepthStencilState(m_opaqueRenderDSState, 0xFF);
+
+ // set constants buffers
+ setAllConstantBuffers(ctx);
+
+ // Fill Camera constant buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ ctx->Map(m_cameraCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
+ CBCamera* cameraBuffer = (CBCamera*)mappedResource.pData;
+ cameraBuffer->viewProjection = viewProjMatrix;
+ cameraBuffer->projectionInv = projMatrixInv;
+ DirectX::XMStoreFloat3(&(cameraBuffer->viewPos), m_camera.GetEyePt());
+ ctx->Unmap(m_cameraCB, 0);
+ }
+
+ // Render opaque renderables
+ m_visibleOpaqueRenderablesCount = 0;
+ for (auto it = m_renderables.begin(); it != m_renderables.end(); it++)
+ {
+ if (!(*it)->isTransparent() && !(*it)->isHidden())
+ {
+ (*it)->render(*this);
+ m_visibleOpaqueRenderablesCount++;
+ }
+ }
+ }
+
+ // modulate shadows
+ if (m_shadowEnabled)
+ {
+ m_shadow.modulateShadowBuffer(pRTV);
+ }
+
+ // render AO
+ if (m_HBAOEnabled)
+ {
+ m_HBAO.renderAO(m_context, pRTV, m_DSTextureSRV, projMatrix);
+ }
+
+ ctx->RSSetViewports(1, &m_viewport);
+
+ // render debug render buffers
+ while (m_queuedRenderBuffers.size() > 0)
+ {
+ render(m_queuedRenderBuffers.back());
+ m_queuedRenderBuffers.pop_back();
+ }
+
+ // Transparency render
+ ctx->OMSetRenderTargets(1, &pRTV, m_DSView);
+ ctx->OMSetDepthStencilState(m_transparencyRenderDSState, 0xFF);
+
+ // depth as SRV isn't used now (uncommenting will produce a warning, probably need readonly depth?)
+ //ctx->PSSetShaderResources(1, 1, &mDSTextureSRV);
+
+ // Render transparent renderables
+ m_visibleTransparentRenderablesCount = 0;
+ for (auto it = m_renderables.begin(); it != m_renderables.end(); it++)
+ {
+ if ((*it)->isTransparent() && !(*it)->isHidden())
+ {
+ (*it)->render(*this);
+ m_visibleTransparentRenderablesCount++;
+ }
+ }
+
+ // shadows debug render
+ if (0)
+ {
+ m_shadow.displayMapFrustums(pRTV, m_DSView);
+ }
+
+ // Reset RT and SRV state
+ ID3D11ShaderResourceView* nullAttach[16] = { nullptr };
+ ctx->PSSetShaderResources(0, 16, nullAttach);
+ ctx->OMSetRenderTargets(0, nullptr, nullptr);
+}
+
+LRESULT Renderer::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ PX_UNUSED(hWnd);
+ PX_UNUSED(wParam);
+ PX_UNUSED(lParam);
+
+ if (uMsg == WM_KEYDOWN || uMsg == WM_KEYUP)
+ {
+ // Camera overspeed event
+ int iKeyPressed = static_cast<int>(wParam);
+ if (iKeyPressed == VK_SHIFT)
+ {
+ toggleCameraSpeed(uMsg == WM_KEYDOWN);
+ }
+ }
+
+ // Camera events
+ return m_camera.HandleMessages(hWnd, uMsg, wParam, lParam);
+}
+
+void Renderer::Animate(double fElapsedTimeSeconds)
+{
+ PROFILER_SCOPED_FUNCTION();
+
+ m_camera.FrameMove((float)fElapsedTimeSeconds);
+}
+
+void Renderer::renderDepthOnly(DirectX::XMMATRIX* viewProjectionSubstitute)
+{
+ // Fill Camera constant buffer
+ if (viewProjectionSubstitute)
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ m_context->Map(m_cameraCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
+ CBCamera* cameraBuffer = (CBCamera*)mappedResource.pData;
+ cameraBuffer->viewProjection = *viewProjectionSubstitute;
+ m_context->Unmap(m_cameraCB, 0);
+ }
+
+ // set constants buffers
+ setAllConstantBuffers(m_context);
+
+ // render
+ for (auto it = m_renderables.begin(); it != m_renderables.end(); it++)
+ {
+ if (!(*it)->isTransparent() && !(*it)->isHidden())
+ (*it)->renderDepthStencilOnly(*this);
+ }
+}
+
+void Renderer::render(const PxRenderBuffer* renderBuffer)
+{
+ // points
+ uint32_t pointsCount = renderBuffer->getNbPoints();
+ if (pointsCount > 0)
+ {
+ RenderDebugVertex* verts = new RenderDebugVertex[pointsCount];
+ const PxDebugPoint* points = renderBuffer->getPoints();
+ for (uint32_t i = 0; i < pointsCount; i++)
+ {
+ verts[i].mPos = points[i].pos;
+ verts[i].mColor = points[i].color;
+ }
+
+ renderDebugPrimitive(verts, pointsCount, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
+ delete[] verts;
+ }
+
+ // lines
+ uint32_t linesCount = renderBuffer->getNbLines();
+ if (linesCount > 0)
+ {
+ RenderDebugVertex* verts = new RenderDebugVertex[linesCount * 2];
+ const PxDebugLine* lines = renderBuffer->getLines();
+ for (uint32_t i = 0; i < linesCount; i++)
+ {
+ verts[i * 2].mPos = lines[i].pos0;
+ verts[i * 2].mColor = lines[i].color0;
+ verts[i * 2 + 1].mPos = lines[i].pos1;
+ verts[i * 2 + 1].mColor = lines[i].color1;
+ }
+
+ renderDebugPrimitive(verts, linesCount * 2, D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
+ delete[] verts;
+ }
+
+ // triangles
+ uint32_t trianglesCount = renderBuffer->getNbTriangles();
+ if (trianglesCount > 0)
+ {
+ RenderDebugVertex* verts = new RenderDebugVertex[trianglesCount * 3];
+ const PxDebugTriangle* triangles = renderBuffer->getTriangles();
+ for (uint32_t i = 0; i < trianglesCount; i++)
+ {
+ verts[i * 3].mPos = triangles[i].pos0;
+ verts[i * 3].mColor = triangles[i].color0;
+ verts[i * 3 + 1].mPos = triangles[i].pos1;
+ verts[i * 3 + 1].mColor = triangles[i].color1;
+ verts[i * 3 + 2].mPos = triangles[i].pos2;
+ verts[i * 3 + 2].mColor = triangles[i].color2;
+ }
+
+ renderDebugPrimitive(verts, trianglesCount * 3, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ delete[] verts;
+ }
+
+ // texts?
+ // ....
+}
+
+void Renderer::renderDebugPrimitive(const Renderer::RenderDebugVertex *vertices, uint32_t verticesCount, D3D11_PRIMITIVE_TOPOLOGY topology)
+{
+ m_context->IASetPrimitiveTopology(topology);
+
+ m_debugPrimitiveRenderMaterialInstance->bind(*m_context, 0);
+
+ D3D11_MAPPED_SUBRESOURCE mappedResource;
+ m_context->Map(m_objectCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
+ CBObject* objectBuffer = (CBObject*)mappedResource.pData;
+
+ objectBuffer->world = PxMat44ToXMMATRIX(PxMat44(PxIdentity));
+
+ m_context->Unmap(m_objectCB, 0);
+
+ if (m_debugPrimitiveVBVerticesCount < verticesCount)
+ {
+ m_debugPrimitiveVBVerticesCount = verticesCount;
+ SAFE_RELEASE(m_debugPrimitiveVB);
+
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ bufferDesc.ByteWidth = sizeof(Renderer::RenderDebugVertex) * m_debugPrimitiveVBVerticesCount;
+ bufferDesc.CPUAccessFlags = 0;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_DEFAULT;
+
+ V(m_device->CreateBuffer(&bufferDesc, NULL, &m_debugPrimitiveVB));
+ }
+
+ CD3D11_BOX box(0, 0, 0, (LONG)(sizeof(Renderer::RenderDebugVertex) * verticesCount), 1, 1);
+ m_context->UpdateSubresource(m_debugPrimitiveVB, 0, &box, vertices, 0, 0);
+
+ ID3D11Buffer* pBuffers[1] = { m_debugPrimitiveVB };
+ UINT strides[1] = { sizeof(RenderDebugVertex) };
+ UINT offsets[1] = { 0 };
+ m_context->IASetVertexBuffers(0, 1, pBuffers, strides, offsets);
+
+ m_context->Draw(verticesCount, 0);
+}
+
+IRenderMesh* Renderer::getPrimitiveRenderMesh(PrimitiveRenderMeshType::Enum type)
+{
+ if (m_primitiveRenderMeshes[type] == NULL)
+ {
+ switch (type)
+ {
+ case PrimitiveRenderMeshType::Box:
+ m_primitiveRenderMeshes[type] = new BoxRenderMesh();
+ break;
+ case PrimitiveRenderMeshType::Plane:
+ m_primitiveRenderMeshes[type] = new PlaneRenderMesh();
+ break;
+ case PrimitiveRenderMeshType::Sphere:
+ m_primitiveRenderMeshes[type] = new SphereRenderMesh();
+ break;
+ default:
+ PX_ALWAYS_ASSERT_MESSAGE("Unsupported PxGeometryType");
+ return NULL;
+ }
+ }
+
+ return m_primitiveRenderMeshes[type];
+}
+
+
+Renderable* Renderer::createRenderable(IRenderMesh& mesh, RenderMaterial& material)
+{
+ Renderable* renderable = new Renderable(mesh, material);
+ m_renderables.emplace(renderable);
+ return renderable;
+}
+
+void Renderer::removeRenderable(Renderable* r)
+{
+ m_renderables.erase(m_renderables.find(r));
+ delete r;
+}
+
+void Renderer::toggleCameraSpeed(bool overspeed)
+{
+ m_camera.SetScalers(0.002f, overspeed ? 150.f : 25.f);
+}
+
+void Renderer::reloadShaders()
+{
+ // iterate Renderables materials and call reload()
+ std::set<RenderMaterial*> materials;
+ for (auto it = m_renderables.begin(); it != m_renderables.end(); it++)
+ {
+ materials.emplace(&((*it)->getMaterial()));
+ }
+ for (std::set<RenderMaterial*>::iterator it = materials.begin(); it != materials.end(); it++)
+ {
+ (*it)->reload();
+ }
+}
+
+void Renderer::drawUI()
+{
+ // Lighting
+ if (ImGui::TreeNode("Lighting"))
+ {
+ ImGui::ColorEdit3("Ambient Color", &(m_worldCBData.ambientColor.x));
+ ImGui::ColorEdit3("Point Light Color", &(m_worldCBData.pointLightColor.x));
+ ImGui::DragFloat3("Point Light Pos", &(m_worldCBData.pointLightPos.x));
+ ImGui::ColorEdit3("Dir Light Color", &(m_worldCBData.dirLightColor.x));
+ ImGui_DragFloat3Dir("Dir Light Dir", &(m_worldCBData.dirLightDir.x));
+ ImGui::DragFloat("Specular Power", &(m_worldCBData.specularPower), 1.0f, 1.0f, 500.0f);
+ ImGui::DragFloat("Specular Intensity", &(m_worldCBData.specularIntensity), 0.01f, 0.0f, 2.0f);
+
+ ImGui::TreePop();
+ }
+
+ // Shadow
+ if (ImGui::TreeNode("Shadow"))
+ {
+ ImGui::Checkbox("Shadows Enabled", &m_shadowEnabled);
+ if (m_shadowEnabled)
+ {
+ m_shadow.drawUI();
+ }
+
+ ImGui::TreePop();
+ }
+
+ // HBAO+
+ if (ImGui::TreeNode("HBAO+"))
+ {
+ ImGui::Checkbox("HBAO Enabled", &(m_HBAOEnabled));
+ if (m_HBAOEnabled)
+ {
+ m_HBAO.drawUI();
+ }
+
+ ImGui::TreePop();
+ }
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/Renderer.h b/NvCloth/samples/SampleBase/renderer/Renderer.h
new file mode 100644
index 0000000..3dc8e56
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/Renderer.h
@@ -0,0 +1,247 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RENDERER_H
+#define RENDERER_H
+
+#include "RenderMaterial.h"
+#include <DirectXMath.h>
+#include "XInput.h"
+#include "DXUTMisc.h"
+#include "DXUTCamera.h"
+#include "SampleManager.h"
+#include "Utils.h"
+#include "ResourceManager.h"
+#include "PrimitiveRenderMesh.h"
+#include "RendererShadow.h"
+#include "RendererHBAO.h"
+#include <unordered_set>
+
+class CFirstPersonCamera;
+class PhysXPrimitive;
+class RenderDebugImpl;
+
+namespace physx
+{
+class PxRenderBuffer;
+};
+
+/**
+3D World Renderer
+- use createRenderable() to add objects to render.
+- use queueRenderBuffer() every frame to render debug primitives.
+- contains ResourceManager to search for file and load resources.
+- contains RendererShadow and RendererHBAO, use them through getters to control shadows.
+*/
+class Renderer : public ISampleController
+{
+ friend class Renderable;
+
+ public:
+ //////// ctor ////////
+
+ Renderer();
+ ~Renderer();
+
+
+ //////// public API ////////
+
+ void reloadShaders();
+
+ bool getWireframeMode()
+ {
+ return m_wireframeMode;
+ }
+
+ void setWireframeMode(bool enabled)
+ {
+ if(m_wireframeMode != enabled)
+ {
+ m_wireframeMode = enabled;
+ initializeDefaultRSState();
+ }
+ }
+
+ IRenderMesh* getPrimitiveRenderMesh(PrimitiveRenderMeshType::Enum type);
+
+ Renderable* createRenderable(IRenderMesh& mesh, RenderMaterial& material);
+ void removeRenderable(Renderable* r);
+
+ void drawUI();
+
+
+ //////// public getters ////////
+
+ float getScreenWidth() const
+ {
+ return m_screenWidth;
+ }
+
+ float getScreenHeight() const
+ {
+ return m_screenHeight;
+ }
+
+ void queueRenderBuffer(const PxRenderBuffer* buffer)
+ {
+ m_queuedRenderBuffers.push_back(buffer);
+ }
+
+ ResourceManager& getResourceManager()
+ {
+ return m_resourceManager;
+ }
+
+ uint32_t getVisibleOpaqueRenderablesCount()
+ {
+ return m_visibleOpaqueRenderablesCount;
+ }
+
+ uint32_t getVisibleTransparentRenderablesCount()
+ {
+ return m_visibleTransparentRenderablesCount;
+ }
+
+ CFirstPersonCamera& getCamera()
+ {
+ return m_camera;
+ }
+
+
+ //////// public 'internal' methods ////////
+
+ // for internal usage (used by RenderShadows)
+ void renderDepthOnly(DirectX::XMMATRIX* viewProjectionSubstitute);
+
+ protected:
+
+ //////// controller callbacks ////////
+
+ virtual HRESULT DeviceCreated(ID3D11Device* pDevice);
+ virtual void DeviceDestroyed();
+ virtual LRESULT MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ virtual void Animate(double fElapsedTimeSeconds);
+ virtual void onInitialize();
+ virtual void onTerminate();
+ virtual void BackBufferResized(ID3D11Device* pDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc);
+ virtual void Render(ID3D11Device* /*device*/, ID3D11DeviceContext* ctx, ID3D11RenderTargetView* pRTV,
+ ID3D11DepthStencilView* pDSV);
+
+ private:
+
+ //////// internal methods ////////
+
+ struct RenderDebugVertex
+ {
+ PxVec3 mPos;
+ uint32_t mColor;
+ };
+
+ void render(const PxRenderBuffer* renderBuffer);
+ void render(Renderable* renderable);
+ void renderDebugPrimitive(const RenderDebugVertex *vertices, uint32_t verticesCount, D3D11_PRIMITIVE_TOPOLOGY topology);
+ void initializeDefaultRSState();
+ void setAllConstantBuffers(ID3D11DeviceContext* ctx);
+ void toggleCameraSpeed(bool overspeed);
+
+
+ //////// constant buffers ////////
+
+ struct CBCamera
+ {
+ DirectX::XMMATRIX viewProjection;
+ DirectX::XMMATRIX projectionInv;
+ DirectX::XMFLOAT3 viewPos;
+ float unusedPad;
+ };
+ struct CBWorld
+ {
+ DirectX::XMFLOAT3 ambientColor;
+ float unusedPad1;
+ DirectX::XMFLOAT3 pointLightPos;
+ float unusedPad2;
+ DirectX::XMFLOAT3 pointLightColor;
+ float unusedPad3;
+ DirectX::XMFLOAT3 dirLightDir;
+ float specularPower;
+ DirectX::XMFLOAT3 dirLightColor;
+ float specularIntensity; // TODO: actually it's per object property
+ };
+ struct CBObject
+ {
+ DirectX::XMMATRIX world;
+ DirectX::XMFLOAT4 color;
+ };
+
+
+ //////// internal data ////////
+
+ // camera
+ CFirstPersonCamera m_camera;
+ float m_screenWidth;
+ float m_screenHeight;
+
+ // resources
+ ResourceManager m_resourceManager;
+
+ // additional render modules(libs)
+ RendererShadow m_shadow;
+ bool m_shadowEnabled;
+ RendererHBAO m_HBAO;
+ bool m_HBAOEnabled;
+
+ // DX11 common
+ ID3D11Device* m_device;
+ ID3D11DeviceContext* m_context;
+ D3D11_VIEWPORT m_viewport;
+
+ // DX11 states
+ ID3D11RasterizerState* m_RSState;
+ ID3D11DepthStencilState* m_opaqueRenderDSState;
+ ID3D11DepthStencilState* m_transparencyRenderDSState;
+
+ // DX11 samplers
+ ID3D11SamplerState* m_pointSampler;
+ ID3D11SamplerState* m_linearSampler;
+
+ // Depth Buffer
+ ID3D11Texture2D* m_DSTexture;
+ ID3D11DepthStencilView* m_DSView;
+ ID3D11ShaderResourceView* m_DSTextureSRV;
+
+ // Constant Buffers
+ ID3D11Buffer* m_cameraCB;
+ ID3D11Buffer* m_worldCB;
+ CBWorld m_worldCBData;
+ ID3D11Buffer* m_objectCB;
+
+ // toggles (options)
+ bool m_wireframeMode;
+
+ // renderables
+ std::unordered_set<Renderable*> m_renderables;
+
+ // primitive meshes cache
+ IRenderMesh* m_primitiveRenderMeshes[PrimitiveRenderMeshType::Count];
+
+ // stats
+ uint32_t m_visibleOpaqueRenderablesCount;
+ uint32_t m_visibleTransparentRenderablesCount;
+
+ // Debug Render
+ RenderMaterial* m_debugPrimitiveRenderMaterial;
+ RenderMaterial::InstancePtr m_debugPrimitiveRenderMaterialInstance;
+ ID3D11Buffer* m_debugPrimitiveVB;
+ uint32_t m_debugPrimitiveVBVerticesCount;
+ std::vector<const PxRenderBuffer*> m_queuedRenderBuffers;
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/RendererHBAO.cpp b/NvCloth/samples/SampleBase/renderer/RendererHBAO.cpp
new file mode 100644
index 0000000..9f0f6de
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RendererHBAO.cpp
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "RendererHBAO.h"
+#include "Renderer.h"
+#include "imgui.h"
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Renderer HBAO (wrapper for hbao+)
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+RendererHBAO::RendererHBAO()
+{
+ m_SSAOContext = NULL;
+
+ // default parameters
+ m_SSAOParameters.Radius = 2.0f;
+}
+
+
+RendererHBAO::~RendererHBAO()
+{
+ releaseResources();
+}
+
+
+void RendererHBAO::createResources(ID3D11Device *pd3dDevice)
+{
+ GFSDK_SSAO_Status status;
+ status = GFSDK_SSAO_CreateContext_D3D11(pd3dDevice, &m_SSAOContext, nullptr);
+ assert(status == GFSDK_SSAO_OK);
+}
+
+
+void RendererHBAO::releaseResources()
+{
+ if (m_SSAOContext != NULL)
+ {
+ m_SSAOContext->Release();
+ }
+}
+
+
+void RendererHBAO::renderAO(ID3D11DeviceContext *pd3dDeviceContext, ID3D11RenderTargetView* pRTV, ID3D11ShaderResourceView* pDepthSRV, DirectX::XMMATRIX& projMatrix)
+{
+ GFSDK_SSAO_InputData_D3D11 InputData;
+ InputData.DepthData.pFullResDepthTextureSRV = pDepthSRV;
+ InputData.DepthData.DepthTextureType = GFSDK_SSAO_HARDWARE_DEPTHS;
+ InputData.DepthData.MetersToViewSpaceUnits = 1.0f;
+ InputData.DepthData.ProjectionMatrix.Data = GFSDK_SSAO_Float4x4(reinterpret_cast<const GFSDK_SSAO_FLOAT*>(&(projMatrix.r[0])));
+ InputData.DepthData.ProjectionMatrix.Layout = GFSDK_SSAO_ROW_MAJOR_ORDER;
+
+ GFSDK_SSAO_Output_D3D11 Output;
+ Output.pRenderTargetView = pRTV;// m_pSceneRTs->ColorRTV;
+ Output.Blend.Mode = GFSDK_SSAO_MULTIPLY_RGB;
+
+ m_SSAOContext->RenderAO(pd3dDeviceContext, InputData, m_SSAOParameters, Output);
+}
+
+
+void RendererHBAO::drawUI()
+{
+ ImGui::DragFloat("Radius", &(m_SSAOParameters.Radius), 0.05f, 0.0f, 100.0f);
+ ImGui::DragFloat("Bias", &(m_SSAOParameters.Bias), 0.01f, 0.0f, 0.5f);
+ ImGui::DragFloat("NearAO", &(m_SSAOParameters.NearAO), 0.01f, 1.0f, 4.0f);
+ ImGui::DragFloat("FarAO", &(m_SSAOParameters.FarAO), 0.01, 1.0f, 4.0f);
+ ImGui::DragFloat("PowerExponent", &(m_SSAOParameters.PowerExponent), 0.01f, 1.0f, 8.0f);
+ ImGui::Checkbox("ForegroundAO Enabled", (bool*)&(m_SSAOParameters.ForegroundAO.Enable));
+ ImGui::DragFloat("ForegroundAO ViewDepth", &(m_SSAOParameters.ForegroundAO.ForegroundViewDepth), 0.01f, 0.0f, 100.0f);
+ ImGui::Checkbox("BackgroundAO Enabled", (bool*)&(m_SSAOParameters.BackgroundAO.Enable));
+ ImGui::DragFloat("BackgroundAO ViewDepth", &(m_SSAOParameters.BackgroundAO.BackgroundViewDepth), 0.01f, 0.0f, 100.0f);
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/RendererHBAO.h b/NvCloth/samples/SampleBase/renderer/RendererHBAO.h
new file mode 100644
index 0000000..c900b74
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RendererHBAO.h
@@ -0,0 +1,40 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RENDERER_HBAO_H
+#define RENDERER_HBAO_H
+
+#include <DirectXMath.h>
+#include "GFSDK_SSAO.h"
+
+
+class Renderer;
+
+class RendererHBAO
+{
+public:
+ RendererHBAO();
+ ~RendererHBAO();
+
+ void createResources(ID3D11Device *pd3dDevice);
+ void renderAO(ID3D11DeviceContext *pd3dDeviceContext, ID3D11RenderTargetView* pRTV, ID3D11ShaderResourceView* pDepthSRV, DirectX::XMMATRIX& projMatrix);
+
+ void drawUI();
+
+private:
+ void releaseResources();
+
+ GFSDK_SSAO_Parameters m_SSAOParameters;
+
+ GFSDK_SSAO_Context_D3D11* m_SSAOContext;
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/RendererShadow.cpp b/NvCloth/samples/SampleBase/renderer/RendererShadow.cpp
new file mode 100644
index 0000000..024a44b
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RendererShadow.cpp
@@ -0,0 +1,417 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "RendererShadow.h"
+
+#include "XInput.h"
+#include "DXUTMisc.h"
+#include "DXUTCamera.h"
+#include "Renderer.h"
+#include "UIHelpers.h"
+
+#define CASCADES 1
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Renderer Shadows (wrapper for shadow_lib)
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+const float DEFAULT_LIGHT_SIZE = 3.0f;
+const DirectX::XMFLOAT3 DEFAULT_LIGHT_POS(-25, 25, 25);
+const DirectX::XMFLOAT3 DEFAULT_LIGHT_LOOK_AT(0, 0, 0);
+const DirectX::XMFLOAT3 DEFAULT_SHADOW_COLOR(0.25f, 0.25f, 0.25f);
+
+RendererShadow::RendererShadow()
+{
+ m_shadowLibContext = NULL;
+
+ m_PCSSEnabled = false;
+ m_lightSize = DEFAULT_LIGHT_SIZE;
+ m_lightPos = DEFAULT_LIGHT_POS;
+ m_lightLookAt = DEFAULT_LIGHT_LOOK_AT;
+ m_shadowColor = DEFAULT_SHADOW_COLOR;
+
+ m_worldSpaceBBox0.x = m_worldSpaceBBox0.y = m_worldSpaceBBox0.z = -100;
+ m_worldSpaceBBox1.x = m_worldSpaceBBox1.y = m_worldSpaceBBox1.z = 100;
+
+ // Penumbra params
+ m_PCSSParams.fMaxThreshold = 80.0f;
+ m_PCSSParams.fMaxClamp = 40.0f;
+ m_PCSSParams.fMinSizePercent = 3.0f;
+ m_PCSSParams.fMinWeightExponent = 5.0f;
+ m_PCSSParams.fMinWeightThresholdPercent = 20.0f;
+
+ m_softShadowTestScale = 0.002f;
+
+ memset(&m_shadowBufferSRV, 0, sizeof(m_shadowBufferSRV));
+
+ m_shadowMapHandle = NULL;
+ m_shadowBufferHandle = NULL;
+}
+
+
+RendererShadow::~RendererShadow()
+{
+ ReleaseResources();
+}
+
+
+void RendererShadow::createResources(ID3D11Device *pd3dDevice, ID3D11DeviceContext* context, CFirstPersonCamera* camera)
+{
+ m_camera = camera;
+
+#if !CASCADES
+ uint32_t shadowMapScale = 5;
+ uint32_t shadowMapWidth = 1024;
+ uint32_t shadowMapHeight = 1024;
+
+ // SM Desc
+ m_SMDesc.eViewType = GFSDK_ShadowLib_ViewType_Single;
+ m_SMDesc.eMapType = GFSDK_ShadowLib_MapType_Texture;
+#else
+
+ uint32_t shadowMapScale = 5;
+ uint32_t shadowMapWidth = 1024;
+ uint32_t shadowMapHeight = 1024;
+
+ // SM Desc
+ m_SMDesc.eViewType = GFSDK_ShadowLib_ViewType_Cascades_2;
+ m_SMDesc.eMapType = GFSDK_ShadowLib_MapType_TextureArray;
+#endif
+
+ m_SMDesc.uResolutionWidth = shadowMapWidth * shadowMapScale;
+ m_SMDesc.uResolutionHeight = shadowMapHeight * shadowMapScale;
+ m_SMDesc.uArraySize = m_SMDesc.eViewType;
+
+ for (int j = 0; j < GFSDK_ShadowLib_ViewType_Cascades_4; j++)
+ {
+ m_SMDesc.ViewLocation[j].uMapID = j;
+ m_SMDesc.ViewLocation[j].v2Origin.x = 0;
+ m_SMDesc.ViewLocation[j].v2Origin.y = 0;
+ m_SMDesc.ViewLocation[j].v2Dimension.x = shadowMapWidth * shadowMapScale;
+ m_SMDesc.ViewLocation[j].v2Dimension.y = shadowMapHeight * shadowMapScale;
+ }
+
+
+ // SM Render Params
+ m_SMRenderParams.iDepthBias = 1000;
+ m_SMRenderParams.fSlopeScaledDepthBias = 8;
+
+ // SB Render Params
+ m_SBRenderParams.eTechniqueType = GFSDK_ShadowLib_TechniqueType_PCSS;
+ m_SBRenderParams.eQualityType = GFSDK_ShadowLib_QualityType_High;
+
+ // DLL version
+ GFSDK_ShadowLib_Version DLLVersion;
+ GFSDK_ShadowLib_Status retCode = GFSDK_ShadowLib_GetDLLVersion(&DLLVersion);
+
+ // Header version
+ GFSDK_ShadowLib_Version headerVersion;
+ headerVersion.uMajor = GFSDK_SHADOWLIB_MAJOR_VERSION;
+ headerVersion.uMinor = GFSDK_SHADOWLIB_MINOR_VERSION;
+
+ // Do they match?
+ if (DLLVersion.uMajor == headerVersion.uMajor && DLLVersion.uMinor == headerVersion.uMinor)
+ {
+ GFSDK_ShadowLib_DeviceContext deviceAndContext;
+ deviceAndContext.pD3DDevice = pd3dDevice;
+ deviceAndContext.pDeviceContext = context;
+
+ retCode = GFSDK_ShadowLib_Create(&headerVersion, &m_shadowLibContext, &deviceAndContext, NULL);
+
+ if (retCode != GFSDK_ShadowLib_Status_Ok) assert(false);
+ }
+ else
+ {
+ assert(false);
+ }
+}
+
+
+void RendererShadow::ReleaseResources()
+{
+ SAFE_RELEASE(m_downsampledShadowMap.pTexture);
+ SAFE_RELEASE(m_downsampledShadowMap.pSRV);
+ SAFE_RELEASE(m_downsampledShadowMap.pRTV);
+
+ if (m_shadowLibContext != NULL)
+ {
+ m_shadowLibContext->Destroy();
+ m_shadowLibContext = NULL;
+ }
+}
+
+
+void RendererShadow::setScreenResolution(float FovyRad, UINT Width, UINT Height, UINT uSampleCount, ID3D11DepthStencilView* pReadOnlyDSV)
+{
+ changeShadowSettings(Width, Height, uSampleCount, pReadOnlyDSV);
+}
+
+
+void RendererShadow::changeShadowSettings(UINT Width, UINT Height, UINT uSampleCount, ID3D11DepthStencilView* pReadOnlyDSV)
+{
+ m_SBDesc.uResolutionWidth = Width;
+ m_SBDesc.uResolutionHeight = Height;
+ m_SBDesc.uSampleCount = uSampleCount;
+ m_SBDesc.ReadOnlyDSV.pDSV = pReadOnlyDSV;
+
+ reloadBuffers();
+}
+
+void RendererShadow::reloadBuffers()
+{
+ {
+ m_shadowLibContext->RemoveMap(&m_shadowMapHandle);
+
+ if (m_SMDesc.eMapType == GFSDK_ShadowLib_MapType_Texture &&
+ m_SMDesc.eViewType == GFSDK_ShadowLib_ViewType_Single &&
+ m_SBRenderParams.eTechniqueType == GFSDK_ShadowLib_TechniqueType_PCSS)
+ {
+ m_SMDesc.bDownsample = true;
+ }
+
+ m_shadowLibContext->AddMap(&m_SMDesc, &m_shadowMapHandle);
+ }
+
+ if (m_SMDesc.eMapType == GFSDK_ShadowLib_MapType_Texture && m_SMDesc.eViewType == GFSDK_ShadowLib_ViewType_Single)
+ {
+ m_downsampledShadowMap.uWidth = m_SMDesc.uResolutionWidth >> 1;
+ m_downsampledShadowMap.uHeight = m_SMDesc.uResolutionHeight >> 1;
+ m_downsampledShadowMap.uSampleCount = 1;
+ m_downsampledShadowMap.Format = DXGI_FORMAT_R32_FLOAT;
+ SAFE_RELEASE(m_downsampledShadowMap.pTexture);
+ SAFE_RELEASE(m_downsampledShadowMap.pSRV);
+ SAFE_RELEASE(m_downsampledShadowMap.pRTV);
+ m_shadowLibContext->DevModeCreateTexture2D(&m_downsampledShadowMap);
+ }
+
+ m_shadowLibContext->RemoveBuffer(&m_shadowBufferHandle);
+ m_shadowLibContext->AddBuffer(&m_SBDesc, &m_shadowBufferHandle);
+}
+
+
+
+//--------------------------------------------------------------------------------------
+// Data passed to the shadow map render function
+//--------------------------------------------------------------------------------------
+struct ShadowMapRenderFunctionParams
+{
+ Renderer* renderer;
+};
+static ShadowMapRenderFunctionParams s_RenderParams;
+
+//--------------------------------------------------------------------------------------
+// Shadow map render function
+//--------------------------------------------------------------------------------------
+static void ShadowMapRenderFunction(void* pParams, gfsdk_float4x4* pViewProj)
+{
+ ShadowMapRenderFunctionParams* pRP = (ShadowMapRenderFunctionParams*)pParams;
+
+ DirectX::XMMATRIX viewProjection;
+ memcpy(&viewProjection, &pViewProj->_11, sizeof(gfsdk_float4x4));
+
+ pRP->renderer->renderDepthOnly(&viewProjection);
+}
+
+void RendererShadow::renderShadowMaps(Renderer* renderer)
+{
+ // select technique
+ GFSDK_ShadowLib_TechniqueType technique = m_SBRenderParams.eTechniqueType;
+ m_SBRenderParams.eTechniqueType = m_PCSSEnabled ? GFSDK_ShadowLib_TechniqueType_PCSS : GFSDK_ShadowLib_TechniqueType_PCF;
+ if (technique != m_SBRenderParams.eTechniqueType)
+ reloadBuffers();
+
+
+ DirectX::XMMATRIX viewMatrix = m_camera->GetViewMatrix();
+ DirectX::XMMATRIX projMatrix = m_camera->GetProjMatrix();
+
+ memcpy(&m_SMRenderParams.m4x4EyeViewMatrix, &viewMatrix.r[0], sizeof(gfsdk_float4x4));
+ memcpy(&m_SMRenderParams.m4x4EyeProjectionMatrix, &projMatrix.r[0], sizeof(gfsdk_float4x4));
+
+ // TODO: (better world space bbox needed)
+ m_SMRenderParams.v3WorldSpaceBBox[0] = m_worldSpaceBBox0;
+ m_SMRenderParams.v3WorldSpaceBBox[1] = m_worldSpaceBBox1;
+
+ m_SMRenderParams.LightDesc.eLightType = GFSDK_ShadowLib_LightType_Directional;
+ memcpy(&m_SMRenderParams.LightDesc.v3LightPos, &m_lightPos.x, sizeof(gfsdk_float3));
+ memcpy(&m_SMRenderParams.LightDesc.v3LightLookAt, &m_lightLookAt.x, sizeof(gfsdk_float3));
+ m_SMRenderParams.LightDesc.fLightSize = m_lightSize;
+ m_SMRenderParams.LightDesc.bLightFalloff = false;
+
+ // Scene specific setup for the shadow map phase that follows
+ s_RenderParams.renderer = renderer;
+ m_SMRenderParams.fnpDrawFunction = GFSDK_ShadowLib_FunctionPointer(ShadowMapRenderFunction);
+ m_SMRenderParams.pDrawFunctionParams = &s_RenderParams;
+
+ // render shadow map
+ m_shadowLibContext->RenderMap(m_shadowMapHandle, &m_SMRenderParams);
+}
+
+
+void RendererShadow::renderShadowBuffer(ID3D11ShaderResourceView* pDepthStencilSRV, ID3D11ShaderResourceView* pResolvedDepthStencilSRV)
+{
+ if (m_SBRenderParams.eTechniqueType == GFSDK_ShadowLib_TechniqueType_PCSS &&
+ m_SMDesc.eMapType == GFSDK_ShadowLib_MapType_Texture &&
+ m_SMDesc.eViewType == GFSDK_ShadowLib_ViewType_Single)
+ {
+ m_tempResources.pDownsampledShadowMap = &m_downsampledShadowMap;
+ m_shadowLibContext->SetTempResources(&m_tempResources);
+ }
+
+ m_SBRenderParams.PCSSPenumbraParams = m_PCSSParams;
+ m_SBRenderParams.fSoftShadowTestScale = m_softShadowTestScale;
+
+ m_shadowLibContext->ClearBuffer(m_shadowBufferHandle);
+
+ m_SBRenderParams.DepthBufferDesc.DepthStencilSRV.pSRV = pDepthStencilSRV;
+
+ m_shadowLibContext->RenderBuffer(m_shadowMapHandle, m_shadowBufferHandle, &m_SBRenderParams);
+
+ m_shadowLibContext->FinalizeBuffer(m_shadowBufferHandle, &m_shadowBufferSRV);
+}
+
+
+void RendererShadow::modulateShadowBuffer(ID3D11RenderTargetView* pOutputRTV)
+{
+ GFSDK_ShadowLib_RenderTargetView ColorRTV;
+ ColorRTV.pRTV = pOutputRTV;
+
+ gfsdk_float3 v3ShadowColor = { m_shadowColor.x, m_shadowColor.y, m_shadowColor.z };
+ m_shadowLibContext->ModulateBuffer(m_shadowBufferHandle, &ColorRTV, v3ShadowColor, GFSDK_ShadowLib_ModulateBufferMask_RGB);
+}
+
+
+void RendererShadow::displayShadowMaps(ID3D11RenderTargetView* pOutputRTV, UINT Width, UINT Height)
+{
+ GFSDK_ShadowLib_RenderTargetView ColorRTV;
+ ColorRTV.pRTV = pOutputRTV;
+
+ float fMapResW = (float)m_SMDesc.uResolutionWidth;
+ float fMapResH = (float)m_SMDesc.uResolutionHeight;
+
+ float fWidthScale = Width / ((float)m_SMDesc.uArraySize * fMapResW);
+ fWidthScale = (fWidthScale > 1.0f) ? (1.0f) : (fWidthScale);
+
+ float fOneFifth = (float)Height / (5.0f);
+ float fHeightScale = fOneFifth / fMapResH;
+ fHeightScale = (fHeightScale > 1.0f) ? (1.0f) : (fHeightScale);
+
+ float fScale = (fHeightScale < fWidthScale) ? (fHeightScale) : (fWidthScale);
+
+ fMapResW = floorf(fMapResW * fScale);
+ fMapResH = floorf(fMapResH * fScale);
+
+ for (unsigned int j = 0; j < (unsigned int)m_SMDesc.uArraySize; j++)
+ {
+ m_shadowLibContext->DevModeDisplayMap(m_shadowBufferHandle,
+ &ColorRTV,
+ m_shadowMapHandle,
+ j,
+ j * (unsigned int)fMapResW + j,
+ Height - (unsigned int)fMapResH,
+ fScale);
+ }
+}
+
+
+void RendererShadow::displayMapFrustums(ID3D11RenderTargetView* pOutputRTV, ID3D11DepthStencilView* pDSV)
+{
+ gfsdk_float3 v3Color;
+ v3Color.x = 1.0f;
+ v3Color.y = 0.0f;
+ v3Color.z = 0.0f;
+
+ GFSDK_ShadowLib_RenderTargetView ColorRTV;
+ ColorRTV.pRTV = pOutputRTV;
+
+ GFSDK_ShadowLib_DepthStencilView DSV;
+ DSV.pDSV = pDSV;
+
+ unsigned int NumViews;
+ NumViews = m_SMDesc.eViewType;
+
+ for (unsigned int j = 0; j < NumViews; j++)
+ {
+ switch (j)
+ {
+ case 0:
+ v3Color.x = 1.0f;
+ v3Color.y = 0.0f;
+ v3Color.z = 0.0f;
+ break;
+ case 1:
+ v3Color.x = 0.0f;
+ v3Color.y = 1.0f;
+ v3Color.z = 0.0f;
+ break;
+ case 2:
+ v3Color.x = 0.0f;
+ v3Color.y = 0.0f;
+ v3Color.z = 1.0f;
+ break;
+ case 3:
+ v3Color.x = 1.0f;
+ v3Color.y = 1.0f;
+ v3Color.z = 0.0f;
+ break;
+ }
+
+ m_shadowLibContext->DevModeDisplayMapFrustum(m_shadowBufferHandle,
+ &ColorRTV,
+ &DSV,
+ m_shadowMapHandle,
+ j,
+ v3Color);
+ }
+}
+
+
+void RendererShadow::displayShadowBuffer(ID3D11RenderTargetView* pOutputRTV)
+{
+ gfsdk_float2 v2Scale;
+ v2Scale.x = 1.0f;
+ v2Scale.y = 1.0f;
+
+ GFSDK_ShadowLib_RenderTargetView ColorRTV;
+ ColorRTV.pRTV = pOutputRTV;
+
+ m_shadowLibContext->DevModeDisplayBuffer(m_shadowBufferHandle,
+ &ColorRTV,
+ v2Scale,
+ NULL);
+}
+
+
+void RendererShadow::toggleDisplayCascades(bool bToggle)
+{
+ m_shadowLibContext->DevModeToggleDebugCascadeShader(m_shadowBufferHandle,
+ bToggle);
+}
+
+
+void RendererShadow::drawUI()
+{
+ ImGui::Checkbox("PCSS", &m_PCSSEnabled);
+ ImGui::ColorEdit3("Shadow Color", &(m_shadowColor.x));
+ ImGui::DragFloat("Light Size", &m_lightSize, 0.05f, 0.0f, 100.0f);
+ ImGui::DragFloat3("Light Position", &(m_lightPos.x));
+ ImGui_DragFloat3Dir("Light LookAt", &(m_lightLookAt.x));
+ ImGui::DragFloat("SoftShadowTestScale", &(m_softShadowTestScale), 0.0001f, 0.0f, 10.0f);
+ if (m_PCSSEnabled)
+ {
+ ImGui::DragFloat("PCSS: fMaxClamp", &(m_PCSSParams.fMaxClamp), 0.001f, 0.0f, 100.0f);
+ ImGui::DragFloat("PCSS: fMaxThreshold", &(m_PCSSParams.fMaxThreshold), 0.001f, 0.0f, 100.0f);
+ ImGui::DragFloat("PCSS: fMinSizePercent", &(m_PCSSParams.fMinSizePercent), 0.001f, 0.0f, 100.0f);
+ ImGui::DragFloat("PCSS: fMinWeightExponent", &(m_PCSSParams.fMinWeightExponent), 0.001f, 0.0f, 100.0f);
+ ImGui::DragFloat("PCSS: fMinWeightThresholdPercent", &(m_PCSSParams.fMinWeightThresholdPercent), 0.001f, 0.0f, 100.0f);
+ ImGui::DragFloat("PCSS: fBlockerSearchDitherPercent", &(m_PCSSParams.fBlockerSearchDitherPercent), 0.001f, 0.0f, 100.0f);
+ ImGui::DragFloat("PCSS: fFilterDitherPercent", &(m_PCSSParams.fFilterDitherPercent), 0.001f, 0.0f, 100.0f);
+ }
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/RendererShadow.h b/NvCloth/samples/SampleBase/renderer/RendererShadow.h
new file mode 100644
index 0000000..d8d027b
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/RendererShadow.h
@@ -0,0 +1,82 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RENDERER_SHADOW_H
+#define RENDERER_SHADOW_H
+
+#include <DirectXMath.h>
+#include "Utils.h"
+#include "gfsdk_shadowlib.h"
+
+#include <string>
+
+
+class CFirstPersonCamera;
+class Renderer;
+
+class RendererShadow
+{
+public:
+ RendererShadow();
+ ~RendererShadow();
+
+ void createResources(ID3D11Device *pd3dDevice, ID3D11DeviceContext* context, CFirstPersonCamera* camera);
+
+ void setScreenResolution(float FovyRad, UINT Width, UINT Height, UINT uSampleCount, ID3D11DepthStencilView* pReadOnlyDSV);
+ void changeShadowSettings(UINT Width, UINT Height, UINT uSampleCount, ID3D11DepthStencilView* pReadOnlyDSV);
+ void renderShadowMaps(Renderer* renderer);
+ void renderShadowBuffer(ID3D11ShaderResourceView* pDepthStencilSRV, ID3D11ShaderResourceView* pResolvedDepthStencilSRV);
+ void modulateShadowBuffer(ID3D11RenderTargetView* pOutputRTV);
+ void displayShadowMaps(ID3D11RenderTargetView* pOutputRTV, UINT Width, UINT Height);
+ void displayMapFrustums(ID3D11RenderTargetView* pOutputRTV, ID3D11DepthStencilView* pDSV);
+ void displayShadowBuffer(ID3D11RenderTargetView* pOutputRTV);
+ void toggleDisplayCascades(bool bToggle);
+
+
+ void drawUI();
+
+private:
+ void reloadBuffers();
+ void ReleaseResources();
+
+
+ GFSDK_ShadowLib_Context* m_shadowLibContext;
+
+ GFSDK_ShadowLib_ShaderResourceView m_shadowBufferSRV;
+
+ GFSDK_ShadowLib_Map* m_shadowMapHandle;
+ GFSDK_ShadowLib_MapDesc m_SMDesc;
+ GFSDK_ShadowLib_BufferDesc m_SBDesc;
+ GFSDK_ShadowLib_MapRenderParams m_SMRenderParams;
+
+ GFSDK_ShadowLib_Buffer* m_shadowBufferHandle;
+ GFSDK_ShadowLib_BufferRenderParams m_SBRenderParams;
+
+ GFSDK_ShadowLib_TempResources m_tempResources;
+ GFSDK_ShadowLib_Texture2D m_downsampledShadowMap;
+
+ CFirstPersonCamera* m_camera;
+
+ // params
+ bool m_PCSSEnabled;
+ float m_lightSize;
+ DirectX::XMFLOAT3 m_lightPos;
+ DirectX::XMFLOAT3 m_lightLookAt;
+ DirectX::XMFLOAT3 m_shadowColor;
+ GFSDK_ShadowLib_PCSSPenumbraParams m_PCSSParams;
+ float m_softShadowTestScale;
+
+ gfsdk_float3 m_worldSpaceBBox0;
+ gfsdk_float3 m_worldSpaceBBox1;
+
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/ResourceManager.cpp b/NvCloth/samples/SampleBase/renderer/ResourceManager.cpp
new file mode 100644
index 0000000..fc76e1c
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ResourceManager.cpp
@@ -0,0 +1,210 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "ResourceManager.h"
+#include "PxAssert.h"
+#include "Utils.h"
+
+#include <windows.h>
+#include <string.h>
+
+
+#define PATH_MAX_LEN 512
+
+
+ResourceManager::ResourceManager()
+{
+ // search for root folder by default
+ addSearchDir(".");
+}
+
+const ShaderFileResource* ResourceManager::requestShaderFile(const char* name)
+{
+ const Resource* resource = requestResource(eSHADER_FILE, name);
+ return resource != nullptr ? static_cast<const ShaderFileResource*>(resource) : nullptr;
+}
+
+const TextureResource* ResourceManager::requestTexture(const char* name)
+{
+ const Resource* resource = requestResource(eTEXTURE, name);
+ return resource != nullptr ? static_cast<const TextureResource*>(resource) : nullptr;
+}
+
+const Resource* ResourceManager::requestResource(ResourceType type, const char* name)
+{
+ // search in loaded
+ std::pair<ResourceType, std::string> key(type, name);
+ auto val = m_loadedResources.find(key);
+ if (val != m_loadedResources.end())
+ {
+ return val->second.get();
+ }
+
+ std::shared_ptr<Resource> resource;
+ if (type == eSHADER_FILE)
+ {
+ char path[PATH_MAX_LEN];
+ const char* exts[] = { "hlsl" };
+ if (findFile(name, std::vector<const char*>(exts, exts + sizeof(exts) / sizeof(exts[0])), path))
+ {
+ resource = std::shared_ptr<Resource>(new ShaderFileResource(path));
+ }
+ else
+ {
+ PX_ALWAYS_ASSERT_MESSAGE(name);
+ }
+ }
+ else if (type == eTEXTURE)
+ {
+ char path[PATH_MAX_LEN];
+ const char* exts[] = { "dds", "tga" };
+ if (findFile(name, std::vector<const char*>(exts, exts + sizeof(exts) / sizeof(exts[0])), path))
+ {
+ std::shared_ptr<TextureResource> textureResource(new TextureResource());
+ WCHAR wPath[MAX_PATH];
+ MultiByteToWideChar(CP_ACP, 0, path, -1, wPath, MAX_PATH);
+ wPath[MAX_PATH - 1] = 0;
+
+ const char* ext = strext(path);
+ if (::strcmp(ext, "dds") == 0)
+ {
+ V(DirectX::LoadFromDDSFile(wPath, DirectX::DDS_FLAGS_NONE, &textureResource->metaData,
+ textureResource->image));
+ }
+ else if (::strcmp(ext, "tga") == 0)
+ {
+ V(DirectX::LoadFromTGAFile(wPath, &textureResource->metaData,
+ textureResource->image));
+ }
+ else
+ {
+ PX_ALWAYS_ASSERT_MESSAGE("Unsupported texture extension");
+ }
+ resource = textureResource;
+ }
+ }
+
+ if (resource.get())
+ {
+ m_loadedResources.emplace(key, resource);
+ return resource.get();
+ }
+ else
+ {
+ PX_ALWAYS_ASSERT_MESSAGE(name);
+ return nullptr;
+ }
+}
+
+bool dirExists(const char* dir)
+{
+ DWORD ftyp = GetFileAttributesA(dir);
+ if (ftyp == INVALID_FILE_ATTRIBUTES)
+ return false; // something is wrong with path!
+
+ if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
+ return true; // this is a directory!
+
+ return false; // this is not a directory!
+}
+
+bool ResourceManager::addSearchDir(const char* dir, bool recursive)
+{
+ if (dirExists(dir))
+ {
+ m_searchDirs.push_back(SearchDir(dir, recursive));
+ return true;
+ }
+ return false;
+}
+
+
+ResourceManager::~ResourceManager()
+{
+}
+
+
+bool ResourceManager::findFileInDir(std::string fileNameFull, const char* path, bool recursive, char* foundPath)
+{
+ WIN32_FIND_DATAA ffd;
+ char tmp[PATH_MAX_LEN];
+ ::snprintf(tmp, sizeof(tmp), "%s\\*", path);
+ HANDLE hFind = FindFirstFileA(tmp, &ffd);
+
+ if(INVALID_HANDLE_VALUE == hFind)
+ {
+ return NULL;
+ }
+
+ do
+ {
+ if (0 == ::strcmp(".", ffd.cFileName) || 0 == ::strcmp("..", ffd.cFileName))
+ continue;
+
+ if(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+ {
+ ::snprintf(tmp, sizeof(tmp), "%s\\%s", path, ffd.cFileName);
+ if(findFileInDir(fileNameFull, tmp, recursive, foundPath))
+ return true;
+ }
+ else if (::stricmp(ffd.cFileName, fileNameFull.c_str()) == 0)
+ {
+ ::snprintf(foundPath, PATH_MAX_LEN, "%s\\%s", path, ffd.cFileName);
+ return true;
+ }
+ } while(FindNextFileA(hFind, &ffd) != 0);
+ // release handle
+ FindClose(hFind);
+ return false;
+}
+
+bool ResourceManager::findFile(std::string fileName, const std::vector<const char*>& exts, char* foundPath)
+{
+ std::string fileNameOnly = fileName;
+ size_t ind = fileNameOnly.find_last_of('/');
+ if (ind > 0)
+ fileNameOnly = fileNameOnly.substr(ind + 1);
+
+ for(size_t i = 0; i < m_searchDirs.size(); i++)
+ {
+ const SearchDir& searchDir = m_searchDirs[i];
+
+ for(size_t j = 0; j < exts.size(); j++)
+ {
+ const char* ext = exts[j];
+ const uint32_t fileMaxLen = 128;
+ char fileNameFull[fileMaxLen] = { 0 };
+
+ ::snprintf(fileNameFull, fileMaxLen, "%s.%s", fileNameOnly.c_str(), ext);
+ if(findFileInDir(fileNameFull, searchDir.path.c_str(), searchDir.recursive, foundPath))
+ return true;
+ }
+
+ if (findFileInDir(fileNameOnly.c_str(), searchDir.path.c_str(), searchDir.recursive, foundPath))
+ return true;
+ }
+ return false;
+}
+
+bool ResourceManager::findFile(std::string fileName, std::string& foundPath)
+{
+ std::vector<const char*> exts;
+ char path[PATH_MAX_LEN];
+ if (findFile(fileName, exts, path))
+ {
+ foundPath = path;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+}
+
diff --git a/NvCloth/samples/SampleBase/renderer/ResourceManager.h b/NvCloth/samples/SampleBase/renderer/ResourceManager.h
new file mode 100644
index 0000000..bc06c92
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ResourceManager.h
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef RESOURCE_MANAGER_H
+#define RESOURCE_MANAGER_H
+
+#include <vector>
+#include <string>
+#include <map>
+#include <memory>
+#include "DirectXTex.h"
+
+
+struct Resource
+{
+private:
+ Resource& operator = (const Resource&);
+};
+
+
+struct ShaderFileResource : public Resource
+{
+ ShaderFileResource(const std::string& p) : path(p) {}
+ std::string path;
+};
+
+
+struct TextureResource : public Resource
+{
+ DirectX::TexMetadata metaData;
+ DirectX::ScratchImage image;
+};
+
+
+/**
+ResourceManager used to look for files in provided dirs (see addSearchDir). Also it loads resources and caches them.
+*/
+class ResourceManager
+{
+public:
+ //////// ctor ////////
+
+ ResourceManager();
+ ~ResourceManager();
+
+ //////// public API ////////
+
+ bool addSearchDir(const char* dir, bool recursive = true);
+
+ const ShaderFileResource* requestShaderFile(const char* name);
+
+ const TextureResource* requestTexture(const char* name);
+
+ bool findFile(std::string fileName, std::string& foundPath);
+
+ bool findFile(std::string fileName, const std::vector<const char*>& exts, char* foundPath);
+
+
+private:
+ //////// internal methods ////////
+
+ enum ResourceType
+ {
+ eSHADER_FILE,
+ eTEXTURE
+ };
+
+ const Resource* requestResource(ResourceType type, const char* name);
+
+ bool findFileInDir(std::string fileNameFull, const char* path, bool recursive, char* foundPath);
+
+ struct SearchDir
+ {
+ SearchDir(std::string path_, bool recursive_) : path(path_), recursive(recursive_) {}
+
+ std::string path;
+ bool recursive;
+ };
+
+
+ //////// internal data ////////
+
+ std::vector<SearchDir> m_searchDirs;
+ std::map<std::pair<ResourceType, std::string>, std::shared_ptr<Resource>> m_loadedResources;
+};
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/ShaderUtils.h b/NvCloth/samples/SampleBase/renderer/ShaderUtils.h
new file mode 100644
index 0000000..b43e0f2
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/ShaderUtils.h
@@ -0,0 +1,98 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SHADER_UTILS_H
+#define SHADER_UTILS_H
+
+#include "Utils.h"
+#include <d3dcompiler.h>
+
+
+static HRESULT CompileShaderFromFile(const char* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel,
+ ID3DBlob** ppBlobOut)
+{
+ HRESULT hr = S_OK;
+ ID3DBlob* pErrorBlob = NULL;
+
+ WCHAR wFileName[MAX_PATH];
+ MultiByteToWideChar(CP_ACP, 0, szFileName, -1, wFileName, MAX_PATH);
+ wFileName[MAX_PATH - 1] = 0;
+ hr = D3DCompileFromFile(wFileName, NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, szEntryPoint, szShaderModel, D3D10_SHADER_ENABLE_STRICTNESS, 0,
+ ppBlobOut, &pErrorBlob);
+ if(FAILED(hr))
+ {
+ OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
+ SAFE_RELEASE(pErrorBlob);
+ return hr;
+ }
+ SAFE_RELEASE(pErrorBlob);
+
+ return S_OK;
+}
+
+static HRESULT createShader(ID3D11Device* pDev, const void* pData, size_t len, ID3D11VertexShader** ppShd, bool)
+{
+ return pDev->CreateVertexShader(pData, len, nullptr, ppShd);
+}
+
+static HRESULT createShader(ID3D11Device* pDev, const void* pData, size_t len, ID3D11GeometryShader** ppShd,
+ bool forceFast)
+{
+ return pDev->CreateGeometryShader(pData, len, nullptr, ppShd);
+}
+
+static HRESULT createShader(ID3D11Device* pDev, const void* pData, size_t len, ID3D11PixelShader** ppShd, bool)
+{
+ return pDev->CreatePixelShader(pData, len, nullptr, ppShd);
+}
+
+static const char* shaderModel(ID3D11VertexShader**)
+{
+ return "vs_5_0";
+}
+
+static const char* shaderModel(ID3D11GeometryShader**)
+{
+ return "gs_5_0";
+}
+
+static const char* shaderModel(ID3D11PixelShader**)
+{
+ return "ps_5_0";
+}
+
+// Give back the shader buffer blob for use in CreateVertexLayout. Caller must release the blob.
+template <class S>
+static HRESULT createShaderFromFile(ID3D11Device* pDev, const char* szFileName, LPCSTR szEntryPoint, S** ppShd,
+ ID3DBlob*& pShaderBuffer, bool forceFast = false)
+{
+ HRESULT hr = CompileShaderFromFile(szFileName, szEntryPoint, shaderModel(ppShd), &pShaderBuffer);
+ if(SUCCEEDED(hr) && pShaderBuffer)
+ {
+ const void* shaderBufferData = pShaderBuffer->GetBufferPointer();
+ const UINT shaderBufferSize = pShaderBuffer->GetBufferSize();
+ createShader(pDev, shaderBufferData, shaderBufferSize, ppShd, forceFast);
+ }
+ return hr;
+}
+
+// Overloaded, same as above but don't give back the shader buffer blob.
+template <class S>
+static HRESULT createShaderFromFile(ID3D11Device* pDev, const char* szFileName, LPCSTR szEntryPoint, S** ppShd,
+ bool forceFast = false)
+{
+ ID3DBlob* pShaderBuffer = NULL;
+ HRESULT hr = createShaderFromFile(pDev, szFileName, szEntryPoint, ppShd, pShaderBuffer, forceFast);
+ SAFE_RELEASE(pShaderBuffer);
+ return hr;
+}
+
+
+#endif //SHADER_UTILS_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.cpp b/NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.cpp
new file mode 100644
index 0000000..9f0b022
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.cpp
@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "SkinnedRenderMesh.h"
+#include "Renderer.h"
+
+SkinnedRenderMesh::SkinnedRenderMesh(const std::vector<const SimpleMesh*>& meshes)
+{
+ PX_ASSERT_WITH_MESSAGE(meshes.size() <= MeshesCountMax, "meshes.size() have to be <= SkinnedRenderMesh::MeshesCountMax");
+
+ m_device = GetDeviceManager()->GetDevice();
+
+ // input element desc setup
+ m_inputDesc.push_back({ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ m_inputDesc.push_back({ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ m_inputDesc.push_back({ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+ m_inputDesc.push_back({ "TEXCOORD", 1, DXGI_FORMAT_R32_UINT, 1, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 });
+
+ // reserve VB
+ uint32_t verticesTotal = 0;
+ std::for_each(meshes.begin(), meshes.end(), [&](const SimpleMesh* c) { verticesTotal += (uint32_t)c->vertices.size(); });
+ std::vector<SimpleMesh::Vertex> vertexBuffer;
+ vertexBuffer.reserve(verticesTotal);
+
+ // reserve IB
+ uint32_t indicesTotal = 0;
+ std::for_each(meshes.begin(), meshes.end(), [&](const SimpleMesh* c) { indicesTotal += (uint32_t)c->indices.size(); });
+ m_indices.reserve(indicesTotal);
+
+ // fill VB, IB, MeshInfo
+ m_meshesInfo.resize(meshes.size());
+ for (uint32_t meshIndex = 0; meshIndex < meshes.size(); ++meshIndex)
+ {
+ const SimpleMesh* mesh = meshes[meshIndex];
+ MeshInfo& meshInfo = m_meshesInfo[meshIndex];
+
+ meshInfo.firstVertex = (uint32_t)vertexBuffer.size();
+ vertexBuffer.insert(vertexBuffer.end(), mesh->vertices.begin(), mesh->vertices.end());
+ meshInfo.verticesCount = (uint32_t)mesh->vertices.size();
+
+ meshInfo.firstIndex = (uint32_t)m_indices.size();
+ uint32_t indexOffset = meshInfo.firstVertex;
+ for (uint32_t index : mesh->indices)
+ {
+ m_indices.push_back((uint32_t)index + indexOffset);
+ }
+ meshInfo.indicesCount = (uint32_t)mesh->indices.size();
+ }
+
+ // vertex buffer
+ {
+ D3D11_SUBRESOURCE_DATA vertexBufferData;
+
+ ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
+ vertexBufferData.pSysMem = vertexBuffer.data();
+
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ bufferDesc.ByteWidth = (uint32_t)(sizeof(SimpleMesh::Vertex) * vertexBuffer.size());
+ bufferDesc.CPUAccessFlags = 0;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
+
+ V(m_device->CreateBuffer(&bufferDesc, &vertexBufferData, &m_vertexBuffer));
+ }
+
+ // bone index buffer
+ {
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ bufferDesc.ByteWidth = (uint32_t)(sizeof(uint32_t) * vertexBuffer.size());
+ bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
+
+ V(m_device->CreateBuffer(&bufferDesc, nullptr, &m_boneIndexBuffer));
+ }
+
+ // index buffer
+ {
+ D3D11_BUFFER_DESC bufferDesc;
+
+ memset(&bufferDesc, 0, sizeof(D3D11_BUFFER_DESC));
+ bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
+ bufferDesc.ByteWidth = (uint32_t)(sizeof(uint32_t) * m_indices.size());
+ bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ bufferDesc.MiscFlags = 0;
+ bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
+
+ V(m_device->CreateBuffer(&bufferDesc, nullptr, &m_indexBuffer));
+ }
+
+ // bone texture
+ {
+ D3D11_TEXTURE2D_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Width = 4;
+ desc.Height = (uint32_t)meshes.size();
+ desc.MipLevels = 1;
+ desc.ArraySize = 1;
+ desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
+ desc.SampleDesc.Count = 1;
+ desc.SampleDesc.Quality = 0;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+
+ V(m_device->CreateTexture2D(&desc, nullptr, &m_boneTexture));
+ }
+
+ // bone texture SRV
+ {
+ D3D11_SHADER_RESOURCE_VIEW_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
+ desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
+ desc.Texture2D.MipLevels = 1;
+ desc.Texture2D.MostDetailedMip = 0;
+ V(m_device->CreateShaderResourceView(m_boneTexture, &desc, &m_boneTextureSRV));
+ }
+}
+
+SkinnedRenderMesh::~SkinnedRenderMesh()
+{
+ SAFE_RELEASE(m_vertexBuffer);
+ SAFE_RELEASE(m_boneIndexBuffer);
+ SAFE_RELEASE(m_indexBuffer);
+ SAFE_RELEASE(m_boneTexture);
+ SAFE_RELEASE(m_boneTextureSRV);
+}
+
+void SkinnedRenderMesh::updateVisibleMeshes(const std::vector<uint32_t>& visibleMeshes)
+{
+ ID3D11DeviceContext* context;
+ m_device->GetImmediateContext(&context);
+
+ // update bone index buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedRead;
+ V(context->Map(m_boneIndexBuffer, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mappedRead));
+
+ uint32_t* boneIndexBuffer = (uint32_t*)mappedRead.pData;
+ for (uint32_t i = 0; i < visibleMeshes.size(); ++i)
+ {
+ const MeshInfo& info = m_meshesInfo[visibleMeshes[i]];
+ for (uint32_t v = info.firstVertex; v < info.firstVertex + info.verticesCount; ++v)
+ {
+ boneIndexBuffer[v] = i;
+ }
+ }
+
+ context->Unmap(m_boneIndexBuffer, 0);
+ }
+
+ // update index buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedRead;
+ V(context->Map(m_indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mappedRead));
+
+ uint32_t* indexBuffer = (uint32_t*)mappedRead.pData;
+ uint32_t indexCount = 0;
+ for (uint32_t meshIndex : visibleMeshes)
+ {
+ const MeshInfo& info = m_meshesInfo[meshIndex];
+ memcpy(indexBuffer + indexCount, &m_indices[info.firstIndex], info.indicesCount * sizeof(uint32_t));
+ indexCount += info.indicesCount;
+ }
+ context->Unmap(m_indexBuffer, 0);
+ m_indexCount = indexCount;
+ PX_ASSERT(m_indexCount % 3 == 0);
+ }
+}
+
+void SkinnedRenderMesh::updateVisibleMeshTransforms(std::vector<PxMat44>& transforms)
+{
+ ID3D11DeviceContext* context;
+ m_device->GetImmediateContext(&context);
+
+ // update bone transform texture
+ {
+ D3D11_MAPPED_SUBRESOURCE mappedRead;
+ V(context->Map(m_boneTexture, 0, D3D11_MAP_WRITE_DISCARD, NULL, &mappedRead));
+ for (uint32_t i = 0; i < transforms.size(); ++i)
+ {
+ std::memcpy((uint8_t*)mappedRead.pData + i * mappedRead.RowPitch, &transforms[i], sizeof(PxMat44));
+ }
+ context->Unmap(m_boneTexture, 0);
+ }
+}
+
+void SkinnedRenderMesh::render(ID3D11DeviceContext& context) const
+{
+ context.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+
+ UINT strides[2] = { sizeof(SimpleMesh::Vertex), sizeof(uint32_t) };
+ UINT offsets[2] = { 0 };
+ ID3D11Buffer* buffers[2] = { m_vertexBuffer, m_boneIndexBuffer };
+ context.IASetVertexBuffers(0, 2, buffers, strides, offsets);
+
+ context.IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
+
+ context.VSSetShaderResources(1, 1, &m_boneTextureSRV);
+
+ context.DrawIndexed(m_indexCount, 0, 0);
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.h b/NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.h
new file mode 100644
index 0000000..cc30e89
--- /dev/null
+++ b/NvCloth/samples/SampleBase/renderer/SkinnedRenderMesh.h
@@ -0,0 +1,82 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SKINNED_RENDER_MESH_H
+#define SKINNED_RENDER_MESH_H
+
+#include "Utils.h"
+#include <DirectXMath.h>
+
+#include <vector>
+#include "Renderable.h"
+#include "Mesh.h"
+
+/**
+SkinnedRenderMesh:
+ bonde indices are passed as vertex input,
+ bone transforms are stored in texture
+ max bone meshes count: SkinnedRenderMesh::MeshesCountMax
+*/
+class SkinnedRenderMesh : public IRenderMesh
+{
+public:
+ //////// ctor ////////
+
+ SkinnedRenderMesh(const std::vector<const SimpleMesh*>& meshes);
+ ~SkinnedRenderMesh();
+
+
+ //////// const ////////
+
+ static const uint32_t MeshesCountMax = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
+
+
+ //////// public API ////////
+
+ void updateVisibleMeshes(const std::vector<uint32_t>& visibleMeshes);
+ void updateVisibleMeshTransforms(std::vector<PxMat44>& transforms);
+
+
+ //////// IRenderMesh implementation ////////
+
+ virtual const std::vector<D3D11_INPUT_ELEMENT_DESC>& getInputElementDesc() const { return m_inputDesc; }
+ virtual void render(ID3D11DeviceContext& context) const;
+
+private:
+ //////// internal data ////////
+
+ struct MeshInfo
+ {
+ uint32_t firstIndex;
+ uint32_t indicesCount;
+
+ uint32_t firstVertex;
+ uint32_t verticesCount;
+ };
+
+ std::vector<D3D11_INPUT_ELEMENT_DESC> m_inputDesc;
+
+ ID3D11Device* m_device;
+
+ ID3D11Buffer* m_vertexBuffer;
+ ID3D11Buffer* m_boneIndexBuffer;
+ ID3D11Buffer* m_indexBuffer;
+ ID3D11Texture2D* m_boneTexture;
+ ID3D11ShaderResourceView* m_boneTextureSRV;
+
+ uint32_t m_indexCount;
+
+ std::vector<MeshInfo> m_meshesInfo;
+ std::vector<uint32_t> m_indices;
+};
+
+
+
+#endif //SKINNED_RENDER_MESH_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/Scene.cpp b/NvCloth/samples/SampleBase/scene/Scene.cpp
new file mode 100644
index 0000000..130dad3
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/Scene.cpp
@@ -0,0 +1,162 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "Scene.h"
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Solver.h>
+#include <NvCloth/Fabric.h>
+#include "Renderer.h"
+
+std::vector<SceneFactory> Scene::sSceneFactories;
+
+Scene::~Scene()
+{
+
+}
+
+namespace
+{
+template <typename T> void trackT(std::vector<T>& list, T object)
+{
+ list.push_back(object);
+}
+
+template <typename T> void untrackT(std::vector<T>& list, T object)
+{
+ for(auto it = list.begin(); it != list.end(); ++it)
+ {
+ if(*it == object)
+ {
+ list.erase(it);
+ break;
+ }
+ }
+}
+}
+void Scene::trackClothActor(ClothActor* clothActor)
+{
+ trackT(mClothList, clothActor);
+}
+void Scene::untrackClothActor(ClothActor* clothActor)
+{
+ untrackT(mClothList, clothActor);
+}
+void Scene::trackSolver(nv::cloth::Solver* solver)
+{
+ trackT(mSolverList, solver);
+ mSolverHelpers[solver].Initialize(solver, mSceneController->getJobManager());
+}
+void Scene::untrackSolver(nv::cloth::Solver* solver)
+{
+ untrackT(mSolverList, solver);
+ mSolverHelpers.erase(solver);
+}
+void Scene::trackFabric(nv::cloth::Fabric* fabric)
+{
+ trackT(mFabricList, fabric);
+}
+void Scene::untrackFabric(nv::cloth::Fabric* fabric)
+{
+ untrackT(mFabricList, fabric);
+}
+
+void Scene::addClothToSolver(ClothActor* clothActor, nv::cloth::Solver* solver)
+{
+ solver->addCloth(clothActor->mCloth);
+ assert(mClothSolverMap.find(clothActor) == mClothSolverMap.end());
+ mClothSolverMap[clothActor] = solver;
+}
+
+void Scene::trackRenderable(Renderable* renderable)
+{
+ trackT(mRenderableList, renderable);
+}
+void Scene::untrackRenderable(Renderable* renderable)
+{
+ untrackT(mRenderableList, renderable);
+}
+
+void Scene::autoDeinitialize()
+{
+ //Remove all cloths from solvers
+ for (auto it : mClothSolverMap)
+ {
+ it.second->removeCloth(it.first->mCloth);
+ }
+ mClothSolverMap.clear();
+
+ //Destroy all solvers
+ for (auto it : mSolverList)
+ {
+ delete it;
+ }
+ mSolverList.clear();
+ mSolverHelpers.clear();
+
+ //Destroy all cloths
+ for (auto it : mClothList)
+ {
+ delete it->mCloth;
+ mSceneController->getRenderer().removeRenderable(it->mClothRenderable);
+ delete it->mClothRenderMesh;
+ delete it;
+ }
+ mClothList.clear();
+
+ //Destroy all fabrics
+ for (auto it : mFabricList)
+ {
+ it->decRefCount();
+ }
+ mFabricList.clear();
+
+ //Destroy all renderables
+ for(auto it : mRenderableList)
+ {
+ mSceneController->getRenderer().removeRenderable(it);
+ }
+ mRenderableList.clear();
+}
+
+void Scene::doSimulationStep(float dt)
+{
+ startSimulationStep(dt);
+ waitForSimulationStep();
+ updateSimulationGraphics();
+}
+
+void Scene::startSimulationStep(float dt)
+{
+ for(auto it = mSolverHelpers.begin(); it != mSolverHelpers.end(); ++it)
+ {
+ it->second.StartSimulation(dt);
+ }
+}
+void Scene::waitForSimulationStep()
+{
+ for(auto it = mSolverHelpers.begin(); it != mSolverHelpers.end(); ++it)
+ {
+ it->second.WaitForSimulation();
+ }
+}
+
+void Scene::updateSimulationGraphics()
+{
+ for each (auto actor in mClothList)
+ {
+ nv::cloth::MappedRange<physx::PxVec4> particles = actor->mCloth->getCurrentParticles();
+ std::vector<PxVec3> particles3(particles.size());
+ for(uint32_t i = 0; i < particles.size(); ++i)
+ particles3[i] = particles[i].getXYZ();
+
+ actor->mClothRenderMesh->update(particles3.data(), particles.size());
+ }
+}
+
diff --git a/NvCloth/samples/SampleBase/scene/Scene.h b/NvCloth/samples/SampleBase/scene/Scene.h
new file mode 100644
index 0000000..3a11ec7
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/Scene.h
@@ -0,0 +1,104 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SCENE_H
+#define SCENE_H
+
+#include <vector>
+#include <map>
+#include "scene/SceneController.h"
+namespace nv
+{
+ namespace cloth
+ {
+ class Factory;
+ class Solver;
+ class Cloth;
+ class Fabric;
+ }
+}
+
+class Scene;
+struct SceneFactory
+{
+ SceneFactory(Scene* (*create)(SceneController*), const char* name):Create(create), mName(name) {}
+ Scene* (*Create)(SceneController*);
+ const char* mName;
+};
+
+#define DECLARE_SCENE_NAME(classname, name) static int classname##id = Scene::AddSceneFactory([](SceneController* c) {return (Scene*)new classname(c); }, name);
+#define DECLARE_SCENE(classname) DECLARE_SCENE_NAME(classname,#classname)
+
+class Scene
+{
+public:
+
+ Scene(SceneController* sceneController):mSceneController(sceneController) {}
+ virtual ~Scene();
+
+ virtual void Animate(double dt) { doSimulationStep(dt); }
+ virtual void drawUI() {}
+ virtual void drawStatsUI() {}
+
+ virtual void onInitialize() = 0;
+ virtual void onTerminate() { autoDeinitialize(); }
+
+ SceneController* getSceneController() { return mSceneController; }
+
+ static int AddSceneFactory(Scene* (*create)(SceneController*), const char* name) { sSceneFactories.push_back(SceneFactory(create, name)); return (int)sSceneFactories.size(); }
+ static Scene* CreateScene(int index, SceneController* controller) { return sSceneFactories[index].Create(controller); }
+ static const char* GetSceneName(int index) { return sSceneFactories[index].mName; }
+ static int GetSceneCount() { return (int)sSceneFactories.size(); }
+
+protected:
+ //Helper functions to enable automatic deinitialize
+ //Tracking an object will delete it when autoDeinitialize is called
+ //Untracking can be used if you delete it sooner than autoDeinitialize
+ void trackClothActor(ClothActor* clothActor);
+ void untrackClothActor(ClothActor* clothActor);
+
+ void trackSolver(nv::cloth::Solver* solver);
+ void untrackSolver(nv::cloth::Solver* solver);
+
+ void trackFabric(nv::cloth::Fabric* fabric);
+ void untrackFabric(nv::cloth::Fabric* fabric);
+
+ void addClothToSolver(ClothActor* clothActor, nv::cloth::Solver* solver); //Helps to detach cloths from solver at AutoDeinit.
+
+ void trackRenderable(Renderable* renderMesh);
+ void untrackRenderable(Renderable* renderMesh);
+
+ void autoDeinitialize();
+
+
+ void doSimulationStep(float dt);
+ void startSimulationStep(float dt);
+ void waitForSimulationStep();
+ void updateSimulationGraphics();
+
+private:
+ Scene& operator= (Scene&); // not implemented
+
+private:
+ SceneController* mSceneController;
+
+ std::vector<ClothActor*> mClothList;
+ std::vector<nv::cloth::Solver*> mSolverList;
+ std::map<nv::cloth::Solver*, MultithreadedSolverHelper> mSolverHelpers;
+ std::vector<nv::cloth::Fabric*> mFabricList;
+ std::map<ClothActor*, nv::cloth::Solver*> mClothSolverMap;
+ std::vector<Renderable*> mRenderableList;
+
+ static std::vector<SceneFactory> sSceneFactories;
+
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/SceneController.cpp b/NvCloth/samples/SampleBase/scene/SceneController.cpp
new file mode 100644
index 0000000..90b499c
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/SceneController.cpp
@@ -0,0 +1,250 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "SceneController.h"
+#include "RenderUtils.h"
+#include "Utils.h"
+
+#include "Renderer.h"
+
+#include "CommonUIController.h"
+
+// initialization of NvCloth dll
+#include <NvCloth/Callbacks.h>
+
+// example allocator callbacks
+#include "CallbackImplementations.h"
+
+// low level cloth
+//#include <NvCloth/Factory.h>
+#include <NvCloth/Fabric.h>
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Solver.h>
+
+#include <NvClothExt/ClothFabricCooker.h>
+#include "ClothMeshGenerator.h"
+
+#include <algorithm>
+#include <imgui.h>
+#include <sstream>
+#include <tuple>
+
+#include "scene/Scene.h"
+#include "scene/scenes/SimpleScene.h"
+#include "scene/scenes/WindScene.h"
+
+JobManager SceneController::sJobManager;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// Controller
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+SceneController::SceneController() : mTimeScale(1.0f), mStartDelay(0.f)
+{
+ mActivePlatform = (int)nv::cloth::Platform::CPU;
+ mCUDAInitialized = false;
+ mDXInitialized = false;
+}
+
+SceneController::~SceneController()
+{
+}
+
+void SceneController::onSampleStart()
+{
+ // setup camera
+ CFirstPersonCamera* camera = &getRenderer().getCamera();
+ DirectX::XMVECTORF32 lookAtPt = { 0, 10, 0, 0 };
+ DirectX::XMVECTORF32 eyePt = { 0, 15, 25, 0 };
+ camera->SetViewParams(eyePt, lookAtPt);
+ camera->SetRotateButtons(false, false, true, false);
+ camera->SetEnablePositionMovement(true);
+
+ mStartDelay = 3.f;
+
+ mPhysXPrimitiveRenderMaterial = new RenderMaterial(getRenderer().getResourceManager(), "physx_primitive", "");
+ mPhysXPlaneRenderMaterial = new RenderMaterial(getRenderer().getResourceManager(), "physx_primitive_plane", "");
+
+ /*{
+ IRenderMesh* mesh = getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Plane);
+ mPlane = getRenderer().createRenderable(*mesh, *mPhysXPlaneRenderMaterial);
+ mPlane->setTransform(PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPiDivTwo, PxVec3(0.f, 0.f, 1.f))));
+ mPlane->setScale(PxVec3(1000.f));
+ }*/
+
+ for (uint32_t i = 0; i < 0; ++i)
+ {
+ IRenderMesh* mesh = getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Box);
+ auto box = getRenderer().createRenderable(*mesh, *mPhysXPrimitiveRenderMaterial);
+ box->setColor(getRandomPastelColor());
+ box->setScale(PxVec3(0.2f));
+ mBoxes.push_back(box);
+ }
+
+
+ ///
+
+ mActiveScene = new SimpleScene(this);
+ mActiveScene->onInitialize();
+ mActiveSceneIndex = 0;
+}
+
+void SceneController::onInitialize()
+{
+ NvClothEnvironment::AllocateEnv();
+
+ mFactories[(int)nv::cloth::Platform::CPU] = NvClothCreateFactoryCPU();
+ mFactories[(int)nv::cloth::Platform::CUDA] = nullptr;
+ mFactories[(int)nv::cloth::Platform::DX11] = nullptr;
+
+ //CUDA
+ do
+ {
+ assert(mCUDAInitialized == false);
+ cuInit(0);
+ int deviceCount = 0;
+ mCUDAInitialized = true;
+ mCUDAInitialized = (cuDeviceGetCount(&deviceCount) == CUDA_SUCCESS);
+ mCUDAInitialized &= deviceCount >= 1;
+ if(!mCUDAInitialized)
+ break;
+ mCUDAInitialized = cuCtxCreate(&mCUDAContext, 0, 0) == CUDA_SUCCESS;
+ if(!mCUDAInitialized)
+ break;
+
+ mFactories[(int)nv::cloth::Platform::CUDA] = NvClothCreateFactoryCUDA(mCUDAContext);
+ } while(false);
+
+ //DX11
+ do
+ {
+ assert(mDXInitialized == false);
+ mDXInitialized = true;
+ mDXDevice = GetDeviceManager()->GetDevice();
+
+ mGraphicsContextManager = new DxContextManagerCallbackImpl(mDXDevice);
+ mDXInitialized &= mGraphicsContextManager != nullptr;
+ if(!mDXInitialized)
+ break;
+
+ mFactories[(int)nv::cloth::Platform::DX11] = NvClothCreateFactoryDX11(mGraphicsContextManager);
+ mDXInitialized &= mFactories[(int)nv::cloth::Platform::DX11] != nullptr;
+ } while(false);
+}
+
+void SceneController::onSampleStop()
+{
+ mActiveScene->onTerminate();
+ delete mActiveScene;
+
+ for (auto b : mBoxes)
+ SAFE_DELETE(b);
+
+ mBoxes.clear();
+
+ NvClothDestroyFactory(mFactories[(int)nv::cloth::Platform::CPU]);
+ NvClothDestroyFactory(mFactories[(int)nv::cloth::Platform::CUDA]);
+ NvClothDestroyFactory(mFactories[(int)nv::cloth::Platform::DX11]);
+
+ //SAFE_DELETE(mPlane);
+ SAFE_DELETE(mPhysXPlaneRenderMaterial);
+ SAFE_DELETE(mPhysXPrimitiveRenderMaterial);
+}
+
+void SceneController::onTerminate()
+{
+}
+
+void SceneController::changeScene(int index)
+{
+ mActiveScene->onTerminate();
+ delete mActiveScene;
+
+ mActiveSceneIndex = index;
+
+ if(index < Scene::GetSceneCount())
+ mActiveScene = Scene::CreateScene(index, this);
+ else
+ {
+ mActiveSceneIndex = 0;
+ mActiveScene = Scene::CreateScene(0, this);
+ }
+ mActiveScene->onInitialize();
+}
+
+void SceneController::Animate(double dt)
+{
+ double simulationStep = dt * mTimeScale;
+ if(simulationStep > 1.0 / 60.0)
+ simulationStep = 1.0 / 60.0;
+
+ mActiveScene->Animate(simulationStep);
+
+}
+
+LRESULT SceneController::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ if (uMsg == WM_KEYDOWN)
+ {
+ int iKeyPressed = static_cast<int>(wParam);
+
+ if(iKeyPressed >= '1' && iKeyPressed <= '9')
+ {
+ changeScene(iKeyPressed - '1');
+ }
+
+ switch (iKeyPressed)
+ {
+ case 'R':
+ return 0;
+ case 'F':
+ return 0;
+ default:
+ break;
+ }
+ }
+
+ return 1;
+}
+
+void SceneController::drawUI()
+{
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Cube
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ {
+ ImGui::Text("Time Scale");
+ ImGui::DragFloat("Scale", &mTimeScale, 0.1f, 0.0f, 100.0f);
+ }
+
+ bool pressed = false;
+
+ pressed = pressed | ImGui::RadioButton("CPU", &mActivePlatform, (int)nv::cloth::Platform::CPU); ImGui::SameLine();
+ pressed = pressed | ImGui::RadioButton("DX11", &mActivePlatform, (int)nv::cloth::Platform::DX11); ImGui::SameLine();
+ pressed = pressed | ImGui::RadioButton("CUDA", &mActivePlatform, (int)nv::cloth::Platform::CUDA);
+
+ if(!getFactory())
+ mActivePlatform = (int)nv::cloth::Platform::CPU;
+
+ for(int i = 0; i < Scene::GetSceneCount(); i++)
+ {
+ pressed = pressed | ImGui::RadioButton(Scene::GetSceneName(i), &mActiveSceneIndex, i);
+ }
+ if(pressed)
+ changeScene(mActiveSceneIndex);
+
+ mActiveScene->drawUI();
+}
+
+void SceneController::drawStatsUI()
+{
+ mActiveScene->drawStatsUI();
+}
+
diff --git a/NvCloth/samples/SampleBase/scene/SceneController.h b/NvCloth/samples/SampleBase/scene/SceneController.h
new file mode 100644
index 0000000..d527597
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/SceneController.h
@@ -0,0 +1,128 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SCENE_CONTROLLER_H
+#define SCENE_CONTROLLER_H
+
+
+#include "SampleManager.h"
+#include <map>
+#include <vector>
+
+#include <NvCloth/Factory.h>
+#include "JobManager.h"
+
+#include "ClothRenderMesh.h"
+#include <cuda.h>
+#include "CallbackImplementations.h"
+
+namespace nv
+{
+ namespace cloth
+ {
+ class Factory;
+ class Solver;
+ class Cloth;
+ class Fabric;
+ class DxContextManagerCallback;
+ }
+}
+
+class RenderMaterial;
+class Renderable;
+
+struct ClothActor
+{
+ Renderable* mClothRenderable;
+ ClothRenderMesh* mClothRenderMesh;
+ nv::cloth::Cloth* mCloth;
+};
+
+class Scene;
+
+class SceneController : public ISampleController
+{
+public:
+
+ SceneController();
+ virtual ~SceneController();
+
+ virtual LRESULT MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ virtual void Animate(double dt);
+ void drawUI();
+ void drawStatsUI();
+
+ virtual void onInitialize();
+ virtual void onSampleStart();
+ virtual void onSampleStop();
+ virtual void onTerminate();
+
+ JobManager* getJobManager() { return &sJobManager; }
+ nv::cloth::Factory* getFactory() { return mFactories[mActivePlatform]; }
+
+ static JobManager sJobManager;
+
+ //////// used controllers ////////
+
+ Renderer& getRenderer() const
+ {
+ return getManager()->getRenderer();
+ }
+
+ CommonUIController& getCommonUIController() const
+ {
+ return getManager()->getCommonUIController();
+ }
+
+ RenderMaterial* getDefaultMaterial()
+ {
+ return mPhysXPrimitiveRenderMaterial;
+ }
+
+ RenderMaterial* getDefaultPlaneMaterial()
+ {
+ return mPhysXPlaneRenderMaterial;
+ }
+
+
+private:
+ SceneController& operator= (SceneController&); // not implemented
+
+ void changeScene(int index);
+
+ //////// internal data ////////
+
+ RenderMaterial* mPhysXPrimitiveRenderMaterial;
+ RenderMaterial* mPhysXPlaneRenderMaterial;
+
+ Renderable* mPlane;
+ std::vector<Renderable*> mBoxes;
+
+ float mTimeScale;
+ float mStartDelay;
+
+ // NvCloth
+ CpuDispatcher mDispatcher;
+ physx::PxTaskManager* mTaskManager;
+
+ nv::cloth::Factory* mFactories[3];
+ int mActivePlatform;
+ bool mCUDAInitialized;
+ CUcontext mCUDAContext;
+ bool mDXInitialized;
+ ID3D11Device* mDXDevice;
+ ID3D11DeviceContext* mDXDeviceContext;
+ nv::cloth::DxContextManagerCallback* mGraphicsContextManager;
+
+ Scene* mActiveScene;
+ int mActiveSceneIndex;
+};
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.cpp b/NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.cpp
new file mode 100644
index 0000000..c1f6a00
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.cpp
@@ -0,0 +1,116 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "FreeFallScene.h"
+#include "Scene/SceneController.h"
+#include <NvClothExt/ClothFabricCooker.h>
+#include "ClothMeshGenerator.h"
+#include <NvCloth/Fabric.h>
+#include <NvCloth/Solver.h>
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Factory.h>
+#include "Renderer.h"
+#include "renderer/RenderUtils.h"
+
+DECLARE_SCENE_NAME(FreeFallScene, "Free Fall Scene")
+
+void FreeFallScene::initializeCloth(int index, physx::PxVec3 offset)
+{
+ ///////////////////////////////////////////////////////////////////////
+ ClothMeshData clothMesh;
+
+ physx::PxMat44 transform = PxTransform(PxVec3(0.f, 13.f, 0.f)+ offset, PxQuat(PxPi, PxVec3(1.f, 0.f, 0.f)));
+ clothMesh.GeneratePlaneCloth(1.f * (1 << index), 1.f * (1 << index), int(2.0f*(1 << index)), int(2.0f*(1 << index)), false, transform);
+
+ mClothActor[index] = new ClothActor;
+ nv::cloth::ClothMeshDesc meshDesc = clothMesh.GetClothMeshDesc();
+ {
+ mClothActor[index]->mClothRenderMesh = new ClothRenderMesh(meshDesc);
+ mClothActor[index]->mClothRenderable = getSceneController()->getRenderer().createRenderable(*(static_cast<IRenderMesh*>(mClothActor[index]->mClothRenderMesh)), *getSceneController()->getDefaultMaterial());
+ mClothActor[index]->mClothRenderable->setColor(getRandomPastelColor());
+ }
+
+ nv::cloth::Vector<int32_t>::Type phaseTypeInfo;
+ mFabric[index] = NvClothCookFabricFromMesh(getSceneController()->getFactory(), meshDesc, physx::PxVec3(0.0f, 0.0f, 1.0f), &phaseTypeInfo, false);
+ trackFabric(mFabric[index]);
+
+ // Initialize start positions and masses for the actual cloth instance
+ // (note: the particle/vertex positions do not have to match the mesh description here. Set the positions to the initial shape of this cloth instance)
+ std::vector<physx::PxVec4> particlesCopy;
+ particlesCopy.resize(clothMesh.mVertices.size());
+
+ physx::PxVec3 clothOffset = transform.getPosition();
+ for(int i = 0; i < (int)clothMesh.mVertices.size(); i++)
+ {
+ // To put attachment point closer to each other
+ if(clothMesh.mInvMasses[i] < 1e-6)
+ clothMesh.mVertices[i] = (clothMesh.mVertices[i] - clothOffset)*0.9f + clothOffset;
+
+ particlesCopy[i] = physx::PxVec4(clothMesh.mVertices[i], clothMesh.mInvMasses[i]); // w component is 1/mass, or 0.0f for anchored/fixed particles
+ }
+
+ // Create the cloth from the initial positions/masses and the fabric
+ mClothActor[index]->mCloth = getSceneController()->getFactory()->createCloth(nv::cloth::Range<physx::PxVec4>(&particlesCopy[0], &particlesCopy[0] + particlesCopy.size()), *mFabric[index]);
+ particlesCopy.clear(); particlesCopy.shrink_to_fit();
+
+ std::vector<physx::PxVec4> planes;
+ planes.push_back(physx::PxVec4(physx::PxVec3(0.0f, 1.f, 0.0f), -0.01f));
+
+ nv::cloth::Range<const physx::PxVec4> planesR(&planes[0], &planes[0] + planes.size());
+ mClothActor[index]->mCloth->setPlanes(planesR, 0, mClothActor[index]->mCloth->getNumPlanes());
+ std::vector<uint32_t> indices;
+ indices.resize(planes.size());
+ for(int i = 0; i < (int)indices.size(); i++)
+ indices[i] = 1 << i;
+ nv::cloth::Range<uint32_t> cind(&indices[0], &indices[0] + indices.size());
+ mClothActor[index]->mCloth->setConvexes(cind, 0, mClothActor[index]->mCloth->getNumConvexes());
+
+ mClothActor[index]->mCloth->setGravity(physx::PxVec3(0.0f, -1.0f, 0.0f));
+ mClothActor[index]->mCloth->setFriction(0.1);
+ mClothActor[index]->mCloth->setDragCoefficient(0.5);
+ mClothActor[index]->mCloth->setLiftCoefficient(0.0);
+
+ // Setup phase configs
+ std::vector<nv::cloth::PhaseConfig> phases(mFabric[index]->getNumPhases());
+ for(int i = 0; i < (int)phases.size(); i++)
+ {
+ phases[i].mPhaseIndex = i;
+ phases[i].mStiffness = 1.0f;
+ phases[i].mStiffnessMultiplier = 1.0f;
+ phases[i].mCompressionLimit = 1.0f;
+ phases[i].mStretchLimit = 1.0f;
+ }
+ mClothActor[index]->mCloth->setPhaseConfig(nv::cloth::Range<nv::cloth::PhaseConfig>(&phases.front(), &phases.back()));
+
+ mSolver = getSceneController()->getFactory()->createSolver();
+ trackSolver(mSolver);
+ trackClothActor(mClothActor[index]);
+
+ // Add the cloth to the solver for simulation
+ addClothToSolver(mClothActor[index], mSolver);
+}
+
+void FreeFallScene::onInitialize()
+{
+ float spaceX = -1.5f;
+
+ for(int i = 0; i < 4; ++i)
+ {
+ initializeCloth(i, physx::PxVec3(16.f + float((i+1)*(i+1)) * spaceX, 2.f, -7.f));
+ }
+
+ {
+ IRenderMesh* mesh = getSceneController()->getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Plane);
+ Renderable* plane = getSceneController()->getRenderer().createRenderable(*mesh, *getSceneController()->getDefaultPlaneMaterial());
+ plane->setTransform(PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPiDivTwo, PxVec3(0.f, 0.f, 1.f))));
+ plane->setScale(PxVec3(1000.f));
+ trackRenderable(plane);
+ }
+}
diff --git a/NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.h b/NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.h
new file mode 100644
index 0000000..3cab456
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/FreeFallScene.h
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef FREE_FALL_SCENE_H
+#define FREE_FALL_SCENE_H
+
+#include "scene/Scene.h"
+#include <foundation/PxVec3.h>
+
+class FreeFallScene : public Scene
+{
+public:
+
+ FreeFallScene(SceneController* sceneController): Scene(sceneController) {}
+
+ void initializeCloth(int index, physx::PxVec3 offset);
+ virtual void onInitialize() override;
+
+private:
+ nv::cloth::Fabric* mFabric[4];
+ nv::cloth::Solver* mSolver;
+ ClothActor* mClothActor[4];
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/scenes/FrictionScene.cpp b/NvCloth/samples/SampleBase/scene/scenes/FrictionScene.cpp
new file mode 100644
index 0000000..3c181ea
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/FrictionScene.cpp
@@ -0,0 +1,119 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "FrictionScene.h"
+#include "Scene/SceneController.h"
+#include <NvClothExt/ClothFabricCooker.h>
+#include "ClothMeshGenerator.h"
+#include <NvCloth/Fabric.h>
+#include <NvCloth/Solver.h>
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Factory.h>
+#include "Renderer.h"
+#include "renderer/RenderUtils.h"
+
+DECLARE_SCENE_NAME(FrictionScene, "Friction Scene")
+
+void FrictionScene::initializeCloth(int index, physx::PxVec3 offset, float frictionCoef)
+{
+ ///////////////////////////////////////////////////////////////////////
+ ClothMeshData clothMesh;
+
+ physx::PxMat44 transform = PxTransform(PxVec3(0.f, 13.f, 0.f)+ offset, PxQuat(PxPi / 6.f, PxVec3(1.f, 0.f, 0.f)));
+ clothMesh.GeneratePlaneCloth(3.f, 3.f, 29, 29, false, transform);
+
+ mClothActor[index] = new ClothActor;
+ nv::cloth::ClothMeshDesc meshDesc = clothMesh.GetClothMeshDesc();
+ {
+ mClothActor[index]->mClothRenderMesh = new ClothRenderMesh(meshDesc);
+ mClothActor[index]->mClothRenderable = getSceneController()->getRenderer().createRenderable(*(static_cast<IRenderMesh*>(mClothActor[index]->mClothRenderMesh)), *getSceneController()->getDefaultMaterial());
+ mClothActor[index]->mClothRenderable->setColor(getRandomPastelColor());
+ }
+
+ nv::cloth::Vector<int32_t>::Type phaseTypeInfo;
+ mFabric[index] = NvClothCookFabricFromMesh(getSceneController()->getFactory(), meshDesc, physx::PxVec3(0.0f, 0.0f, 1.0f), &phaseTypeInfo, false);
+ trackFabric(mFabric[index]);
+
+ // Initialize start positions and masses for the actual cloth instance
+ // (note: the particle/vertex positions do not have to match the mesh description here. Set the positions to the initial shape of this cloth instance)
+ std::vector<physx::PxVec4> particlesCopy;
+ particlesCopy.resize(clothMesh.mVertices.size());
+
+ physx::PxVec3 clothOffset = transform.getPosition();
+ for(int i = 0; i < (int)clothMesh.mVertices.size(); i++)
+ {
+ // To put attachment point closer to each other
+ if(clothMesh.mInvMasses[i] < 1e-6)
+ clothMesh.mVertices[i] = (clothMesh.mVertices[i] - clothOffset)*0.9f + clothOffset;
+
+ particlesCopy[i] = physx::PxVec4(clothMesh.mVertices[i], clothMesh.mInvMasses[i]); // w component is 1/mass, or 0.0f for anchored/fixed particles
+ }
+
+ // Create the cloth from the initial positions/masses and the fabric
+ mClothActor[index]->mCloth = getSceneController()->getFactory()->createCloth(nv::cloth::Range<physx::PxVec4>(&particlesCopy[0], &particlesCopy[0] + particlesCopy.size()), *mFabric[index]);
+ particlesCopy.clear(); particlesCopy.shrink_to_fit();
+
+ std::vector<physx::PxVec4> planes;
+ planes.push_back(physx::PxVec4(PxQuat(PxPiDivFour*0.5f, PxVec3(1.f, 0.f, 0.f)).rotate(physx::PxVec3(0.0f, 1.f, 0.0f)), -0.01f));
+
+ nv::cloth::Range<const physx::PxVec4> planesR(&planes[0], &planes[0] + planes.size());
+ mClothActor[index]->mCloth->setPlanes(planesR, 0, mClothActor[index]->mCloth->getNumPlanes());
+ std::vector<uint32_t> indices;
+ indices.resize(planes.size());
+ for(int i = 0; i < (int)indices.size(); i++)
+ indices[i] = 1 << i;
+ nv::cloth::Range<uint32_t> cind(&indices[0], &indices[0] + indices.size());
+ mClothActor[index]->mCloth->setConvexes(cind, 0, mClothActor[index]->mCloth->getNumConvexes());
+
+ mClothActor[index]->mCloth->setGravity(physx::PxVec3(0.0f, -9.8f, 0.0f));
+
+ // Setup phase configs
+ std::vector<nv::cloth::PhaseConfig> phases(mFabric[index]->getNumPhases());
+ for(int i = 0; i < (int)phases.size(); i++)
+ {
+ phases[i].mPhaseIndex = i;
+ phases[i].mStiffness = 1.0f;
+ phases[i].mStiffnessMultiplier = 1.0f;
+ phases[i].mCompressionLimit = 1.0f;
+ phases[i].mStretchLimit = 1.0f;
+ }
+ mClothActor[index]->mCloth->setPhaseConfig(nv::cloth::Range<nv::cloth::PhaseConfig>(&phases.front(), &phases.back()));
+ mClothActor[index]->mCloth->setFriction(frictionCoef);
+
+ mSolver = getSceneController()->getFactory()->createSolver();
+ trackSolver(mSolver);
+ trackClothActor(mClothActor[index]);
+
+ // Add the cloth to the solver for simulation
+ addClothToSolver(mClothActor[index], mSolver);
+}
+
+void FrictionScene::onInitialize()
+{
+
+
+ float spaceX = -4.f;
+ float frictionDelta = 0.2f;
+
+ for(int i = 0; i < 4; ++i)
+ {
+ float friction = i > 0 ? float(i) * frictionDelta : 0.f; // 0.0, 0.2, 0.4, 0.6
+
+ initializeCloth(i, physx::PxVec3(4.f + float(i) * spaceX, 4.f, -18.f), friction);
+ }
+
+ {
+ IRenderMesh* mesh = getSceneController()->getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Plane);
+ Renderable* plane = getSceneController()->getRenderer().createRenderable(*mesh, *getSceneController()->getDefaultPlaneMaterial());
+ plane->setTransform(PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPiDivFour*0.5f, PxVec3(1.f, 0.f, 0.f))*PxQuat(PxPiDivTwo, PxVec3(0.f, 0.f, 1.f))));
+ plane->setScale(PxVec3(1000.f));
+ trackRenderable(plane);
+ }
+}
diff --git a/NvCloth/samples/SampleBase/scene/scenes/FrictionScene.h b/NvCloth/samples/SampleBase/scene/scenes/FrictionScene.h
new file mode 100644
index 0000000..4173e09
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/FrictionScene.h
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef FRICTION_SCENE_H
+#define FRICTION_SCENE_H
+
+#include "scene/Scene.h"
+#include <foundation/PxVec3.h>
+
+class FrictionScene : public Scene
+{
+public:
+
+ FrictionScene(SceneController* sceneController): Scene(sceneController) {}
+
+ void initializeCloth(int index, physx::PxVec3 offset, float frictionCoef);
+ virtual void onInitialize() override;
+
+private:
+ nv::cloth::Fabric* mFabric[4];
+ nv::cloth::Solver* mSolver;
+ ClothActor* mClothActor[4];
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/scenes/SimpleScene.cpp b/NvCloth/samples/SampleBase/scene/scenes/SimpleScene.cpp
new file mode 100644
index 0000000..68bb96b
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/SimpleScene.cpp
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "SimpleScene.h"
+#include "Scene/SceneController.h"
+#include <NvClothExt/ClothFabricCooker.h>
+#include "ClothMeshGenerator.h"
+#include <NvCloth/Fabric.h>
+#include <NvCloth/Solver.h>
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Factory.h>
+#include "Renderer.h"
+#include "renderer/RenderUtils.h"
+
+DECLARE_SCENE_NAME(SimpleScene,"Simple Scene")
+
+void SimpleScene::onInitialize()
+{
+ ///////////////////////////////////////////////////////////////////////
+ ClothMeshData clothMesh;
+
+ physx::PxMat44 transform = PxTransform(PxVec3(0.f, 13.f, 0.f), PxQuat(PxPi / 6.f, PxVec3(1.f, 0.f, 0.f)));
+ clothMesh.GeneratePlaneCloth(6.f, 7.f, 59, 69, false, transform);
+ clothMesh.AttachClothPlaneByAngles(59, 69);
+
+ mClothActor = new ClothActor;
+ nv::cloth::ClothMeshDesc meshDesc = clothMesh.GetClothMeshDesc();
+ {
+ mClothActor->mClothRenderMesh = new ClothRenderMesh(meshDesc);
+ mClothActor->mClothRenderable = getSceneController()->getRenderer().createRenderable(*(static_cast<IRenderMesh*>(mClothActor->mClothRenderMesh)), *getSceneController()->getDefaultMaterial());
+ mClothActor->mClothRenderable->setColor(getRandomPastelColor());
+ }
+
+ nv::cloth::Vector<int32_t>::Type phaseTypeInfo;
+ mFabric = NvClothCookFabricFromMesh(getSceneController()->getFactory(), meshDesc, physx::PxVec3(0.0f, -9.8f, 0.0f), &phaseTypeInfo, false);
+ trackFabric(mFabric);
+
+ // Initialize start positions and masses for the actual cloth instance
+ // (note: the particle/vertex positions do not have to match the mesh description here. Set the positions to the initial shape of this cloth instance)
+ std::vector<physx::PxVec4> particlesCopy;
+ particlesCopy.resize(clothMesh.mVertices.size());
+
+ physx::PxVec3 center = transform.transform(physx::PxVec3(0.0f, 0.0f, 0.0f));
+ for(int i = 0; i < (int)clothMesh.mVertices.size(); i++)
+ {
+ // To put attachment point closer to each other
+ if(clothMesh.mInvMasses[i] < 1e-6)
+ clothMesh.mVertices[i] = (clothMesh.mVertices[i] - center)*0.85f + center;
+
+ particlesCopy[i] = physx::PxVec4(clothMesh.mVertices[i], clothMesh.mInvMasses[i]); // w component is 1/mass, or 0.0f for anchored/fixed particles
+ }
+
+ // Create the cloth from the initial positions/masses and the fabric
+ mClothActor->mCloth = getSceneController()->getFactory()->createCloth(nv::cloth::Range<physx::PxVec4>(&particlesCopy[0], &particlesCopy[0] + particlesCopy.size()), *mFabric);
+ particlesCopy.clear(); particlesCopy.shrink_to_fit();
+
+ mClothActor->mCloth->setGravity(physx::PxVec3(0.0f, -9.8f, 0.0f));
+
+ // Setup phase configs
+ std::vector<nv::cloth::PhaseConfig> phases(mFabric->getNumPhases());
+ for(int i = 0; i < (int)phases.size(); i++)
+ {
+ phases[i].mPhaseIndex = i;
+ phases[i].mStiffness = 1.0f;
+ phases[i].mStiffnessMultiplier = 1.0f;
+ phases[i].mCompressionLimit = 1.0f;
+ phases[i].mStretchLimit = 1.0f;
+ }
+ mClothActor->mCloth->setPhaseConfig(nv::cloth::Range<nv::cloth::PhaseConfig>(&phases.front(), &phases.back()));
+ mClothActor->mCloth->setDragCoefficient(0.5f);
+ mClothActor->mCloth->setDragCoefficient(0.5f);
+
+ mSolver = getSceneController()->getFactory()->createSolver();
+ trackSolver(mSolver);
+ trackClothActor(mClothActor);
+
+ // Add the cloth to the solver for simulation
+ addClothToSolver(mClothActor, mSolver);
+
+ {
+ IRenderMesh* mesh = getSceneController()->getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Plane);
+ Renderable* plane = getSceneController()->getRenderer().createRenderable(*mesh, *getSceneController()->getDefaultPlaneMaterial());
+ plane->setTransform(PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPiDivTwo, PxVec3(0.f, 0.f, 1.f))));
+ plane->setScale(PxVec3(1000.f));
+ trackRenderable(plane);
+ }
+}
diff --git a/NvCloth/samples/SampleBase/scene/scenes/SimpleScene.h b/NvCloth/samples/SampleBase/scene/scenes/SimpleScene.h
new file mode 100644
index 0000000..2ee17c1
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/SimpleScene.h
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SIMPLE_SCENE_H
+#define SIMPLE_SCENE_H
+
+#include "scene/Scene.h"
+
+class SimpleScene : public Scene
+{
+public:
+
+ SimpleScene(SceneController* sceneController):Scene(sceneController) {}
+
+ virtual void onInitialize() override;
+
+private:
+ nv::cloth::Fabric* mFabric;
+ nv::cloth::Solver* mSolver;
+ ClothActor* mClothActor;
+
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/scenes/TetherScene.cpp b/NvCloth/samples/SampleBase/scene/scenes/TetherScene.cpp
new file mode 100644
index 0000000..b818d9d
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/TetherScene.cpp
@@ -0,0 +1,103 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "TetherScene.h"
+#include "Scene/SceneController.h"
+#include <NvClothExt/ClothFabricCooker.h>
+#include "ClothMeshGenerator.h"
+#include <NvCloth/Fabric.h>
+#include <NvCloth/Solver.h>
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Factory.h>
+#include "Renderer.h"
+#include "renderer/RenderUtils.h"
+
+DECLARE_SCENE_NAME(TetherScene, "Tether Scene")
+
+void TetherScene::initializeCloth(int index, physx::PxVec3 offset, float tetherStiffness)
+{
+ ///////////////////////////////////////////////////////////////////////
+ ClothMeshData clothMesh;
+
+ physx::PxMat44 transform = PxTransform(PxVec3(0.f, 13.f, 0.f)+ offset, PxQuat(PxPi / 6.f, PxVec3(1.f, 0.f, 0.f)));
+ clothMesh.GeneratePlaneCloth(6.f, 7.5f, 39, 59, false, transform);
+ clothMesh.AttachClothPlaneByAngles(39, 59);
+
+ mClothActor[index] = new ClothActor;
+ nv::cloth::ClothMeshDesc meshDesc = clothMesh.GetClothMeshDesc();
+ {
+ mClothActor[index]->mClothRenderMesh = new ClothRenderMesh(meshDesc);
+ mClothActor[index]->mClothRenderable = getSceneController()->getRenderer().createRenderable(*(static_cast<IRenderMesh*>(mClothActor[index]->mClothRenderMesh)), *getSceneController()->getDefaultMaterial());
+ mClothActor[index]->mClothRenderable->setColor(getRandomPastelColor());
+ }
+
+ nv::cloth::Vector<int32_t>::Type phaseTypeInfo;
+ mFabric[index] = NvClothCookFabricFromMesh(getSceneController()->getFactory(), meshDesc, physx::PxVec3(0.0f, 0.0f, 1.0f), &phaseTypeInfo, false);
+ trackFabric(mFabric[index]);
+
+ // Initialize start positions and masses for the actual cloth instance
+ // (note: the particle/vertex positions do not have to match the mesh description here. Set the positions to the initial shape of this cloth instance)
+ std::vector<physx::PxVec4> particlesCopy;
+ particlesCopy.resize(clothMesh.mVertices.size());
+
+ physx::PxVec3 clothOffset = transform.getPosition();
+ for(int i = 0; i < (int)clothMesh.mVertices.size(); i++)
+ {
+ // To put attachment point closer to each other
+ if(clothMesh.mInvMasses[i] < 1e-6)
+ clothMesh.mVertices[i] = (clothMesh.mVertices[i] - clothOffset)*0.8f + clothOffset;
+
+ particlesCopy[i] = physx::PxVec4(clothMesh.mVertices[i], clothMesh.mInvMasses[i]); // w component is 1/mass, or 0.0f for anchored/fixed particles
+ }
+
+ // Create the cloth from the initial positions/masses and the fabric
+ mClothActor[index]->mCloth = getSceneController()->getFactory()->createCloth(nv::cloth::Range<physx::PxVec4>(&particlesCopy[0], &particlesCopy[0] + particlesCopy.size()), *mFabric[index]);
+ particlesCopy.clear(); particlesCopy.shrink_to_fit();
+
+ mClothActor[index]->mCloth->setGravity(physx::PxVec3(0.0f, -9.8f, 0.0f));
+ mClothActor[index]->mCloth->setTetherConstraintStiffness(tetherStiffness);
+
+ // Setup phase configs
+ std::vector<nv::cloth::PhaseConfig> phases(mFabric[index]->getNumPhases());
+ for(int i = 0; i < (int)phases.size(); i++)
+ {
+ phases[i].mPhaseIndex = i;
+ phases[i].mStiffness = 1.0f;
+ phases[i].mStiffnessMultiplier = 1.0f;
+ phases[i].mCompressionLimit = 1.0f;
+ phases[i].mStretchLimit = 1.0f;
+ }
+ mClothActor[index]->mCloth->setPhaseConfig(nv::cloth::Range<nv::cloth::PhaseConfig>(&phases.front(), &phases.back()));
+
+
+ mSolver = getSceneController()->getFactory()->createSolver();
+ trackSolver(mSolver);
+ trackClothActor(mClothActor[index]);
+
+ // Add the cloth to the solver for simulation
+ addClothToSolver(mClothActor[index], mSolver);
+}
+
+void TetherScene::onInitialize()
+{
+
+ initializeCloth(0,physx::PxVec3(-5.0f,0.0f,0.0f),0);
+ initializeCloth(1, physx::PxVec3(4.0f, 0.0f, 0.0f),1);
+
+ mTime = 0.0f;
+
+ {
+ IRenderMesh* mesh = getSceneController()->getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Plane);
+ Renderable* plane = getSceneController()->getRenderer().createRenderable(*mesh, *getSceneController()->getDefaultPlaneMaterial());
+ plane->setTransform(PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPiDivTwo, PxVec3(0.f, 0.f, 1.f))));
+ plane->setScale(PxVec3(1000.f));
+ trackRenderable(plane);
+ }
+}
diff --git a/NvCloth/samples/SampleBase/scene/scenes/TetherScene.h b/NvCloth/samples/SampleBase/scene/scenes/TetherScene.h
new file mode 100644
index 0000000..728286b
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/TetherScene.h
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef TETHER_SCENE_H
+#define TETHER_SCENE_H
+
+#include "scene/Scene.h"
+#include <foundation/PxVec3.h>
+
+class TetherScene : public Scene
+{
+public:
+
+ TetherScene(SceneController* sceneController): Scene(sceneController) {}
+
+ void initializeCloth(int index, physx::PxVec3 offset, float tetherStiffness);
+ virtual void onInitialize() override;
+
+private:
+ nv::cloth::Fabric* mFabric[2];
+ nv::cloth::Solver* mSolver;
+ ClothActor* mClothActor[2];
+
+ float mTime;
+
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/scene/scenes/WindScene.cpp b/NvCloth/samples/SampleBase/scene/scenes/WindScene.cpp
new file mode 100644
index 0000000..51cec1d
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/WindScene.cpp
@@ -0,0 +1,124 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "WindScene.h"
+#include "Scene/SceneController.h"
+#include <NvClothExt/ClothFabricCooker.h>
+#include "ClothMeshGenerator.h"
+#include <NvCloth/Fabric.h>
+#include <NvCloth/Solver.h>
+#include <NvCloth/Cloth.h>
+#include <NvCloth/Factory.h>
+#include "Renderer.h"
+#include "renderer/RenderUtils.h"
+
+DECLARE_SCENE_NAME(WindScene, "Wind Scene")
+
+void WindScene::Animate(double dt)
+{
+ mTime += dt;
+
+ if(mTime > 3.7f)
+ {
+ float dvx = 3.f * cos(25.f * mTime);
+ float vy = max(0.f, 0.9f * cos(11.f * mTime));
+ float dvz = 1.5f * sin(19.f * mTime);
+ for(int i = 0; i < 3; i++)
+ {
+ physx::PxVec3 wind = physx::PxVec3(2.5f + dvx, vy, 15.f + dvz);
+ mClothActor[i]->mCloth->setWindVelocity(wind);
+ }
+ }
+
+ doSimulationStep(dt);
+}
+
+void WindScene::initializeCloth(int index, physx::PxVec3 offset)
+{
+ ///////////////////////////////////////////////////////////////////////
+ ClothMeshData clothMesh;
+
+ physx::PxMat44 transform = PxTransform(PxVec3(0.f, 13.f, 0.f)+ offset, PxQuat(PxPi / 6.f, PxVec3(1.f, 0.f, 0.f)));
+ clothMesh.GeneratePlaneCloth(5.f, 6.f, 49, 59, false, transform);
+ clothMesh.AttachClothPlaneByAngles(49, 59);
+ clothMesh.SetInvMasses(0.2f + (float)index * 1.4f);
+
+ mClothActor[index] = new ClothActor;
+ nv::cloth::ClothMeshDesc meshDesc = clothMesh.GetClothMeshDesc();
+ {
+ mClothActor[index]->mClothRenderMesh = new ClothRenderMesh(meshDesc);
+ mClothActor[index]->mClothRenderable = getSceneController()->getRenderer().createRenderable(*(static_cast<IRenderMesh*>(mClothActor[index]->mClothRenderMesh)), *getSceneController()->getDefaultMaterial());
+ mClothActor[index]->mClothRenderable->setColor(getRandomPastelColor());
+ }
+
+ nv::cloth::Vector<int32_t>::Type phaseTypeInfo;
+ mFabric[index] = NvClothCookFabricFromMesh(getSceneController()->getFactory(), meshDesc, physx::PxVec3(0.0f, 0.0f, 1.0f), &phaseTypeInfo, false);
+ trackFabric(mFabric[index]);
+
+ // Initialize start positions and masses for the actual cloth instance
+ // (note: the particle/vertex positions do not have to match the mesh description here. Set the positions to the initial shape of this cloth instance)
+ std::vector<physx::PxVec4> particlesCopy;
+ particlesCopy.resize(clothMesh.mVertices.size());
+
+ physx::PxVec3 clothOffset = transform.getPosition();
+ for(int i = 0; i < (int)clothMesh.mVertices.size(); i++)
+ {
+ // To put attachment point closer to each other
+ if(clothMesh.mInvMasses[i] < 1e-6)
+ clothMesh.mVertices[i] = (clothMesh.mVertices[i] - clothOffset)*0.9f + clothOffset;
+
+ particlesCopy[i] = physx::PxVec4(clothMesh.mVertices[i], clothMesh.mInvMasses[i]); // w component is 1/mass, or 0.0f for anchored/fixed particles
+ }
+
+ // Create the cloth from the initial positions/masses and the fabric
+ mClothActor[index]->mCloth = getSceneController()->getFactory()->createCloth(nv::cloth::Range<physx::PxVec4>(&particlesCopy[0], &particlesCopy[0] + particlesCopy.size()), *mFabric[index]);
+ particlesCopy.clear(); particlesCopy.shrink_to_fit();
+
+ mClothActor[index]->mCloth->setGravity(physx::PxVec3(0.0f, -9.8f, 0.0f));
+
+ // Setup phase configs
+ std::vector<nv::cloth::PhaseConfig> phases(mFabric[index]->getNumPhases());
+ for(int i = 0; i < (int)phases.size(); i++)
+ {
+ phases[i].mPhaseIndex = i;
+ phases[i].mStiffness = 1.0f;
+ phases[i].mStiffnessMultiplier = 1.0f;
+ phases[i].mCompressionLimit = 1.0f;
+ phases[i].mStretchLimit = 1.0f;
+ }
+ mClothActor[index]->mCloth->setPhaseConfig(nv::cloth::Range<nv::cloth::PhaseConfig>(&phases.front(), &phases.back()));
+ mClothActor[index]->mCloth->setDragCoefficient(0.5f);
+ mClothActor[index]->mCloth->setLiftCoefficient(0.6f);
+
+ mSolver = getSceneController()->getFactory()->createSolver();
+ trackSolver(mSolver);
+ trackClothActor(mClothActor[index]);
+
+ // Add the cloth to the solver for simulation
+ addClothToSolver(mClothActor[index], mSolver);
+}
+
+void WindScene::onInitialize()
+{
+
+ initializeCloth(2,physx::PxVec3(-9.0f,0.0f,0.0f));
+ initializeCloth(1, physx::PxVec3(-2.0f, 0.0f, 0.0f));
+ initializeCloth(0, physx::PxVec3(5.0f, 0.0f, 0.0f));
+
+ mTime = 0.0f;
+
+ {
+ IRenderMesh* mesh = getSceneController()->getRenderer().getPrimitiveRenderMesh(PrimitiveRenderMeshType::Plane);
+ Renderable* plane = getSceneController()->getRenderer().createRenderable(*mesh, *getSceneController()->getDefaultPlaneMaterial());
+ plane->setTransform(PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxPiDivTwo, PxVec3(0.f, 0.f, 1.f))));
+ plane->setScale(PxVec3(1000.f));
+ trackRenderable(plane);
+ }
+}
diff --git a/NvCloth/samples/SampleBase/scene/scenes/WindScene.h b/NvCloth/samples/SampleBase/scene/scenes/WindScene.h
new file mode 100644
index 0000000..d637bed
--- /dev/null
+++ b/NvCloth/samples/SampleBase/scene/scenes/WindScene.h
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef WIND_SCENE_H
+#define WIND_SCENE_H
+
+#include "scene/Scene.h"
+#include <foundation/PxVec3.h>
+
+class WindScene : public Scene
+{
+public:
+
+ WindScene(SceneController* sceneController): Scene(sceneController) {}
+
+ virtual void Animate(double dt) override;
+ void initializeCloth(int index, physx::PxVec3 offset);
+ virtual void onInitialize() override;
+
+private:
+ nv::cloth::Fabric* mFabric[3];
+ nv::cloth::Solver* mSolver;
+ ClothActor* mClothActor[3];
+
+ float mTime;
+
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/ui/CommonUIController.cpp b/NvCloth/samples/SampleBase/ui/CommonUIController.cpp
new file mode 100644
index 0000000..0c0cac8
--- /dev/null
+++ b/NvCloth/samples/SampleBase/ui/CommonUIController.cpp
@@ -0,0 +1,467 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "CommonUIController.h"
+
+#include "Renderer.h"
+#include "SceneController.h"
+#include "SampleController.h"
+#include "SampleProfiler.h"
+
+#include <imgui.h>
+#include "imgui_impl_dx11.h"
+#include "UIHelpers.h"
+
+#include <cstdio>
+#include <inttypes.h>
+
+
+inline float memorySizeOutput(const char*& prefix, float value)
+{
+ for (prefix = "\0\0k\0M\0G\0T\0P\0E"; value >= 1024 && *prefix != 'E'; value /= 1024, prefix += 2);
+ return value;
+}
+
+CommonUIController::CommonUIController()
+{
+}
+
+HRESULT CommonUIController::DeviceCreated(ID3D11Device* pDevice)
+{
+ DeviceManager* manager = GetDeviceManager();
+ ID3D11DeviceContext* pd3dDeviceContext;
+ pDevice->GetImmediateContext(&pd3dDeviceContext);
+ ImGui_ImplDX11_Init(manager->GetHWND(), pDevice, pd3dDeviceContext);
+
+ ImGuiStyle& style = ImGui::GetStyle();
+ style.WindowRounding = 8.0f;
+ style.ScrollbarRounding = 8.0f;
+ style.FrameRounding = 8.0f;
+ //style.IndentSpacing = 20;
+ int mainColor[3] = { 110, 110, 110 }; // previous green one { 50, 110, 30 }
+ style.Colors[ImGuiCol_TitleBg] = ImColor(mainColor[0], mainColor[1], mainColor[2], 62);
+ style.Colors[ImGuiCol_TitleBgCollapsed] = ImColor(mainColor[0], mainColor[1], mainColor[2], 52);
+ style.Colors[ImGuiCol_TitleBgActive] = ImColor(mainColor[0], mainColor[1], mainColor[2], 87);
+ style.Colors[ImGuiCol_Header] = ImColor(mainColor[0], mainColor[1], mainColor[2], 52);
+ style.Colors[ImGuiCol_HeaderHovered] = ImColor(mainColor[0], mainColor[1], mainColor[2], 92);
+ style.Colors[ImGuiCol_HeaderActive] = ImColor(mainColor[0], mainColor[1], mainColor[2], 72);
+ style.Colors[ImGuiCol_ScrollbarBg] = ImColor(mainColor[0], mainColor[1], mainColor[2], 12);
+ style.Colors[ImGuiCol_ScrollbarGrab] = ImColor(mainColor[0], mainColor[1], mainColor[2], 52);
+ style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImColor(mainColor[0], mainColor[1], mainColor[2], 92);
+ style.Colors[ImGuiCol_ScrollbarGrabActive] = ImColor(mainColor[0], mainColor[1], mainColor[2], 72);
+ style.Colors[ImGuiCol_Button] = ImColor(40, 100, 80, 30);
+ style.Colors[ImGuiCol_ButtonHovered] = ImColor(40, 100, 80, 100);
+ style.Colors[ImGuiCol_ButtonActive] = ImColor(40, 100, 80, 70);
+ style.Colors[ImGuiCol_PopupBg] = ImColor(10, 23, 18, 230);
+ style.Colors[ImGuiCol_TextSelectedBg] = ImColor(10, 23, 18, 180);
+ style.Colors[ImGuiCol_FrameBg] = ImColor(70, 70, 70, 30);
+ style.Colors[ImGuiCol_FrameBgHovered] = ImColor(70, 70, 70, 70);
+ style.Colors[ImGuiCol_FrameBgActive] = ImColor(70, 70, 70, 50);
+ style.Colors[ImGuiCol_ComboBg] = ImColor(20, 20, 20, 252);
+
+ return S_OK;
+}
+
+void CommonUIController::DeviceDestroyed()
+{
+ ImGui_ImplDX11_Shutdown();
+}
+
+extern LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+
+LRESULT CommonUIController::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ PX_UNUSED(hWnd);
+ PX_UNUSED(wParam);
+ PX_UNUSED(lParam);
+
+ ImGui_ImplDX11_WndProcHandler(hWnd, uMsg, wParam, lParam);
+
+ if (uMsg == WM_KEYDOWN && !ImGui::GetIO().WantCaptureKeyboard)
+ {
+ int iKeyPressed = static_cast<int>(wParam);
+ switch (iKeyPressed)
+ {
+ case 'P':
+ {
+ //getPhysXController().setPaused(!getPhysXController().isPaused());
+ break;
+ }
+ case 'O':
+ {
+ getRenderer().setWireframeMode(!getRenderer().getWireframeMode());
+ break;
+ }
+ case 'I':
+ {
+ //getBlastController().debugRenderMode = (BlastFamily::DebugRenderMode)(((int)getBlastController().debugRenderMode + 1) % BlastFamily::DebugRenderMode::DEBUG_RENDER_MODES_COUNT);
+ break;
+ }
+ case VK_F5:
+ {
+ getRenderer().reloadShaders();
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ if (ImGui::GetIO().WantCaptureMouse)
+ return 0;
+
+ return 1;
+}
+
+void CommonUIController::Animate(double fElapsedTimeSeconds)
+{
+ m_dt = (float)fElapsedTimeSeconds;
+}
+
+void CommonUIController::Render(ID3D11Device*, ID3D11DeviceContext*, ID3D11RenderTargetView*, ID3D11DepthStencilView*)
+{
+ ImGui_ImplDX11_NewFrame();
+ drawUI();
+ ImGui::Render();
+}
+
+void CommonUIController::addDelayedCall(const char* title, const char* message, std::function<void()> func, float delay)
+{
+ DelayedCall call = { func, title, message, delay, delay };
+ m_delayedCalls.emplace(call);
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// IMGUI UI
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+void CommonUIController::drawUI()
+{
+ const float padding = 8.0f;
+ ImGui::SetNextWindowPos(ImVec2(padding, padding), ImGuiSetCond_Once/*ImGuiSetCond_FirstUseEver*/);
+ ImGui::SetNextWindowSize(ImVec2(420, getRenderer().getScreenHeight() - 2 * padding), ImGuiSetCond_Once/*ImGuiSetCond_FirstUseEver*/);
+ ImGui::SetNextWindowCollapsed(false, ImGuiSetCond_Once);
+ ImGui::Begin("New Shiny UI", 0, ImGuiWindowFlags_NoTitleBar);
+ {
+ ImGui::PushItemWidth(ImGui::GetWindowSize().x * 0.5f);
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Scene
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (ImGui::CollapsingHeader("Scene"))
+ {
+ getSceneController().drawUI();
+ }
+
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Stats
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (ImGui::CollapsingHeader("Stats"))
+ {
+ // FPS
+ double averageTime = GetDeviceManager()->GetAverageFrameTime();
+ float fps = (averageTime > 0) ? 1.0 / averageTime : 0.0;
+ float frameMs = 1000.0f / fps;
+ ImGui::Text("Frame Time %.3f ms (%.1f FPS)", frameMs, fps);
+
+ static PlotLinesInstance<> fpsPlot;
+ fpsPlot.plot("FPS", frameMs, "ms/frame", 0.0f, 100.0f);
+
+ // Render stats
+ ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0xFF, 0x3B, 0xD8, 0xFF));
+ ImGui::Text("Draw Calls (Opaque/Transparent): %d/%d", getRenderer().getVisibleOpaqueRenderablesCount(), getRenderer().getVisibleTransparentRenderablesCount());
+ ImGui::PopStyleColor();
+
+#if NV_PROFILE
+ // Sample Profiler
+ static bool s_showProfilerWindow = false;
+ if (ImGui::Button("Code Profiler"))
+ {
+ s_showProfilerWindow = !s_showProfilerWindow;
+ }
+ if (s_showProfilerWindow)
+ {
+ drawCodeProfiler(&s_showProfilerWindow);
+ }
+#endif
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Application
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (ImGui::CollapsingHeader("Application"))
+ {
+ // Reload Shaders
+ if (ImGui::Button("Reload Shaders (F5)"))
+ {
+ getRenderer().reloadShaders();
+ }
+
+ /*// ImGui Test Window (just in case)
+ static bool s_showTestWindow = false;
+ if (ImGui::Button("ImGui Test Window"))
+ {
+ s_showTestWindow = !s_showTestWindow;
+ }
+ if (s_showTestWindow)
+ {
+ ImGui::ShowTestWindow();
+ }*/
+ }
+
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Debug Render
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (ImGui::CollapsingHeader("Debug Render"))
+ {
+ // WireFrame
+ bool wireFrameEnabled = getRenderer().getWireframeMode();
+ if (ImGui::Checkbox("WireFrame (O)", &wireFrameEnabled))
+ {
+ getRenderer().setWireframeMode(wireFrameEnabled);
+ }
+
+ // - - - - - - - -
+ ImGui::Spacing();
+ }
+
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Renderer
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (ImGui::CollapsingHeader("Renderer"))
+ {
+ getRenderer().drawUI();
+ }
+
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Hints
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (ImGui::CollapsingHeader("Hints / Help"))
+ {
+ ImGui::BulletText("Rotate camera - RMB");
+ ImGui::BulletText("Move camera - WASDQE(SHIFT)");
+ //ImGui::BulletText("Play/Pause - P");
+ ImGui::BulletText("Reload shaders - F5");
+ ImGui::BulletText("Wireframe - O");
+ //ImGui::BulletText("Restart - R");
+ }
+
+ ImGui::PopItemWidth();
+ }
+ ImGui::End();
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Mode Text
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ /*{
+ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4());
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0,0));
+
+ const char* text = "CENTERED TEXT, REMOVE ME";
+ ImVec2 size = ImGui::CalcTextSize(text);
+ ImGui::SetNextWindowPos(ImVec2((getRenderer().getScreenWidth() - size.x) / 2, 0));
+ ImGui::Begin("Mode Text", 0, ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar);
+ ImGui::Text(text);
+ ImGui::End();
+
+ ImGui::PopStyleVar();
+ ImGui::PopStyleColor();
+ }*/
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // FPS
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ {
+ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4());
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
+
+ double averageTime = GetDeviceManager()->GetAverageFrameTime();
+ float fps = (averageTime > 0) ? 1.0 / averageTime : 0.0;
+ static char buf[32];
+ std::sprintf(buf, "%.1f FPS", fps);
+ ImVec2 size = ImGui::CalcTextSize(buf);
+
+ size.x += 20.0;
+ ImGui::SetNextWindowSize(size);
+ ImGui::SetNextWindowPos(ImVec2(getRenderer().getScreenWidth() - size.x, 0));
+ ImGui::Begin("FPS", 0, ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar);
+ ImGui::Text(buf);
+ ImGui::End();
+
+ ImGui::PopStyleVar();
+ ImGui::PopStyleColor();
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Loading overlay
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ if (!m_delayedCalls.empty())
+ {
+ DelayedCall& call = m_delayedCalls.front();
+ if (call.delay > 0)
+ {
+ const int height = 50;
+ const char* message = call.message;
+ const float alpha = PxClamp(lerp(0.0f, 1.0f, (call.delayTotal - call.delay) * 10.0f), 0.0f, 1.0f);
+
+ ImGui::PushStyleColor(ImGuiCol_WindowBg, ImColor(0, 0, 0, 200));
+ ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
+ ImGui::SetNextWindowPosCenter();
+ ImVec2 size = ImGui::CalcTextSize(message);
+ int width = std::max<float>(200, size.x) + 50;
+ ImGui::SetNextWindowSize(ImVec2(width, height));
+ ImGui::Begin(call.title, 0, ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar);
+ ImGui::SetCursorPos(ImVec2((width - size.x) * 0.5f, (height - size.y) * 0.5f));
+ ImGui::Text(message);
+ ImGui::End();
+ ImGui::PopStyleVar();
+ ImGui::PopStyleColor();
+
+ call.delay -= PxClamp(m_dt, 0.0f, 0.1f);
+ }
+ else
+ {
+ call.func();
+ m_delayedCalls.pop();
+ }
+ }
+}
+
+
+void CommonUIController::drawCodeProfiler(bool* open)
+{
+ ImGuiWindowFlags window_flags = 0;
+ const float padding = 8.0f;
+ const float width = 550;
+ const float height = 580;
+ ImGui::SetNextWindowPos(ImVec2(getRenderer().getScreenWidth() - width - padding, padding), ImGuiSetCond_Once/*ImGuiSetCond_FirstUseEver*/);
+ ImGui::SetNextWindowSize(ImVec2(width, height), ImGuiSetCond_Once);
+ if (!ImGui::Begin("Code Profiler", open, window_flags))
+ {
+ // Early out if the window is collapsed, as an optimization.
+ ImGui::End();
+ return;
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Control/Main Bar
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ {
+ if (ImGui::Button("Reset"))
+ {
+ PROFILER_INIT();
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Dump To File (profile.txt)"))
+ {
+ SampleProfilerDumpToFile("profile.txt");
+ }
+ ImGui::SameLine();
+ ImGui::Text("Profiler overhead: %2.3f ms", SampleProfilerGetOverhead().count() * 0.001f);
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Legend
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ {
+ ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
+ ImGui::Text("Legend: name | calls | time | max time");
+ ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Stats Tree
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ ImGui::SetNextTreeNodeOpen(true, ImGuiSetCond_Once);
+ float plotMS = 0.0f;
+ float plotMaxMS = 0.0f;
+ const char* plotName = nullptr;
+ if (ImGui::TreeNode("Root"))
+ {
+ auto treeIt = SampleProfilerCreateTreeIterator();
+ if (treeIt)
+ {
+ uint32_t depth = 1;
+ uint32_t openeDepth = 1;
+ while (!treeIt->isDone())
+ {
+ const auto data = treeIt->data();
+
+ while (data->depth < depth)
+ {
+ ImGui::TreePop();
+ depth--;
+ }
+
+ const uint32_t maxLen = 30;
+ auto hash = data->hash;
+ static uint64_t selectedNodeHash = 0;
+ if (selectedNodeHash == hash)
+ {
+ plotMS = data->time.count() * 0.001f;
+ plotMaxMS = data->maxTime.count() * 0.001f;
+ plotName = data->name;
+ }
+ if (ImGui::TreeNodeEx(data->name, data->hasChilds ? 0 : ImGuiTreeNodeFlags_Leaf, "%-*.*s | %d | %2.3f ms | %2.3f ms",
+ maxLen, maxLen, data->name, data->calls, data->time.count() * 0.001f, data->maxTime.count() * 0.001f))
+ {
+ depth++;
+ treeIt->next();
+ }
+ else
+ {
+ treeIt->next();
+ while (!treeIt->isDone() && treeIt->data()->depth > depth)
+ treeIt->next();
+ }
+
+ if (ImGui::IsItemClicked())
+ {
+ selectedNodeHash = hash;
+ }
+ }
+
+ while (depth > 0)
+ {
+ ImGui::TreePop();
+ depth--;
+ }
+
+ treeIt->release();
+ }
+ else
+ {
+ ImGui::Text("Profiler Is Broken. Begin/End Mismatch.");
+ }
+ }
+
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ // Selected Item Plot
+ ///////////////////////////////////////////////////////////////////////////////////////////
+ {
+ ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
+ if (plotName)
+ {
+ static PlotLinesInstance<> selectedNodePlot;
+ selectedNodePlot.plot("", plotMS, plotName, 0.0f, plotMaxMS);
+ }
+ else
+ {
+ ImGui::Text("Select item to plot.");
+ }
+ }
+
+ ImGui::End();
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/ui/CommonUIController.h b/NvCloth/samples/SampleBase/ui/CommonUIController.h
new file mode 100644
index 0000000..47953b7
--- /dev/null
+++ b/NvCloth/samples/SampleBase/ui/CommonUIController.h
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef COMMON_UI_CONTROLLER_H
+#define COMMON_UI_CONTROLLER_H
+
+#include "SampleManager.h"
+#include <DirectXMath.h>
+#include <string>
+#include <list>
+#include <queue>
+#include <functional>
+
+
+class Renderer;
+class PhysXController;
+class BlastController;
+
+
+class CommonUIController : public ISampleController
+{
+ public:
+ CommonUIController();
+ virtual ~CommonUIController() {};
+
+ virtual HRESULT DeviceCreated(ID3D11Device* pDevice);
+ virtual void DeviceDestroyed();
+ virtual LRESULT MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ virtual void Animate(double fElapsedTimeSeconds);
+ virtual void Render(ID3D11Device*, ID3D11DeviceContext*, ID3D11RenderTargetView*, ID3D11DepthStencilView*);
+
+ void addDelayedCall(std::function<void()> func, const char* message)
+ {
+ addDelayedCall("PLEASE WAIT...", message, func);
+ }
+
+ void addPopupMessage(const char* title, const char* message, float duration = 2.f)
+ {
+ addDelayedCall(title, message, [] {}, duration);
+ }
+
+ private:
+ void addDelayedCall(const char* title, const char* message, std::function<void()> func, float delay = 0.1f);
+
+ void drawUI();
+ void drawCodeProfiler(bool*);
+
+
+ //////// used controllers ////////
+
+ Renderer& getRenderer() const
+ {
+ return getManager()->getRenderer();
+ }
+
+ SceneController& getSceneController() const
+ {
+ return getManager()->getSceneController();
+ }
+
+ SampleController& getSampleController() const
+ {
+ return getManager()->getSampleController();
+ }
+
+
+ //////// internal data ////////
+
+ struct DelayedCall
+ {
+ std::function<void()> func;
+ const char* title;
+ const char* message;
+ float delay;
+ float delayTotal;
+ };
+
+ std::queue<DelayedCall> m_delayedCalls;
+
+ float m_dt;
+
+};
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/ui/imgui_impl_dx11.cpp b/NvCloth/samples/SampleBase/ui/imgui_impl_dx11.cpp
new file mode 100644
index 0000000..11f66f0
--- /dev/null
+++ b/NvCloth/samples/SampleBase/ui/imgui_impl_dx11.cpp
@@ -0,0 +1,583 @@
+// ImGui Win32 + DirectX11 binding
+// In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+
+// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
+// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// https://github.com/ocornut/imgui
+
+#include <imgui.h>
+#include "imgui_impl_dx11.h"
+
+// DirectX
+#include <d3d11.h>
+#include <d3dcompiler.h>
+#define DIRECTINPUT_VERSION 0x0800
+#include <dinput.h>
+
+// Data
+static INT64 g_Time = 0;
+static INT64 g_TicksPerSecond = 0;
+
+static HWND g_hWnd = 0;
+static ID3D11Device* g_pd3dDevice = NULL;
+static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
+static ID3D11Buffer* g_pVB = NULL;
+static ID3D11Buffer* g_pIB = NULL;
+static ID3D10Blob * g_pVertexShaderBlob = NULL;
+static ID3D11VertexShader* g_pVertexShader = NULL;
+static ID3D11InputLayout* g_pInputLayout = NULL;
+static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
+static ID3D10Blob * g_pPixelShaderBlob = NULL;
+static ID3D11PixelShader* g_pPixelShader = NULL;
+static ID3D11SamplerState* g_pFontSampler = NULL;
+static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
+static ID3D11RasterizerState* g_pRasterizerState = NULL;
+static ID3D11BlendState* g_pBlendState = NULL;
+static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
+static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
+
+struct VERTEX_CONSTANT_BUFFER
+{
+ float mvp[4][4];
+};
+
+// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
+// If text or lines are blurry when integrating ImGui in your engine:
+// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
+void ImGui_ImplDX11_RenderDrawLists(ImDrawData* draw_data)
+{
+ ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
+
+ // Create and grow vertex/index buffers if needed
+ if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
+ {
+ if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
+ g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
+ D3D11_BUFFER_DESC desc;
+ memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
+ desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ desc.MiscFlags = 0;
+ if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
+ return;
+ }
+ if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
+ {
+ if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
+ g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
+ D3D11_BUFFER_DESC desc;
+ memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
+ desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
+ return;
+ }
+
+ // Copy and convert all vertices into a single contiguous buffer
+ D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
+ if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
+ return;
+ if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
+ return;
+ ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
+ ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
+ {
+ const ImDrawList* cmd_list = draw_data->CmdLists[n];
+ memcpy(vtx_dst, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
+ memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
+ vtx_dst += cmd_list->VtxBuffer.size();
+ idx_dst += cmd_list->IdxBuffer.size();
+ }
+ ctx->Unmap(g_pVB, 0);
+ ctx->Unmap(g_pIB, 0);
+
+ // Setup orthographic projection matrix into our constant buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mapped_resource;
+ if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
+ return;
+ VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
+ float L = 0.0f;
+ float R = ImGui::GetIO().DisplaySize.x;
+ float B = ImGui::GetIO().DisplaySize.y;
+ float T = 0.0f;
+ float mvp[4][4] =
+ {
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
+ { 0.0f, 0.0f, 0.5f, 0.0f },
+ { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
+ };
+ memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
+ ctx->Unmap(g_pVertexConstantBuffer, 0);
+ }
+
+ // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
+ struct BACKUP_DX11_STATE
+ {
+ UINT ScissorRectsCount, ViewportsCount;
+ D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
+ D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
+ ID3D11RasterizerState* RS;
+ ID3D11BlendState* BlendState;
+ FLOAT BlendFactor[4];
+ UINT SampleMask;
+ UINT StencilRef;
+ ID3D11DepthStencilState* DepthStencilState;
+ ID3D11ShaderResourceView* PSShaderResource;
+ ID3D11SamplerState* PSSampler;
+ ID3D11PixelShader* PS;
+ ID3D11VertexShader* VS;
+ UINT PSInstancesCount, VSInstancesCount;
+ ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
+ D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
+ ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
+ UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
+ DXGI_FORMAT IndexBufferFormat;
+ ID3D11InputLayout* InputLayout;
+ };
+ BACKUP_DX11_STATE old;
+ old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
+ ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
+ ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
+ ctx->RSGetState(&old.RS);
+ ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
+ ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
+ ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
+ ctx->PSGetSamplers(0, 1, &old.PSSampler);
+ old.PSInstancesCount = old.VSInstancesCount = 256;
+ ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
+ ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
+ ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
+ ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
+ ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
+ ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
+ ctx->IAGetInputLayout(&old.InputLayout);
+
+ // Setup viewport
+ D3D11_VIEWPORT vp;
+ memset(&vp, 0, sizeof(D3D11_VIEWPORT));
+ vp.Width = ImGui::GetIO().DisplaySize.x;
+ vp.Height = ImGui::GetIO().DisplaySize.y;
+ vp.MinDepth = 0.0f;
+ vp.MaxDepth = 1.0f;
+ vp.TopLeftX = vp.TopLeftY = 0.0f;
+ ctx->RSSetViewports(1, &vp);
+
+ // Bind shader and vertex buffers
+ unsigned int stride = sizeof(ImDrawVert);
+ unsigned int offset = 0;
+ ctx->IASetInputLayout(g_pInputLayout);
+ ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
+ ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
+ ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ ctx->VSSetShader(g_pVertexShader, NULL, 0);
+ ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
+ ctx->PSSetShader(g_pPixelShader, NULL, 0);
+ ctx->PSSetSamplers(0, 1, &g_pFontSampler);
+
+ // Setup render state
+ const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
+ ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
+ ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
+ ctx->RSSetState(g_pRasterizerState);
+
+ // Render command lists
+ int vtx_offset = 0;
+ int idx_offset = 0;
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
+ {
+ const ImDrawList* cmd_list = draw_data->CmdLists[n];
+ 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
+ {
+ const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
+ ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
+ ctx->RSSetScissorRects(1, &r);
+ ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
+ }
+ idx_offset += pcmd->ElemCount;
+ }
+ vtx_offset += cmd_list->VtxBuffer.size();
+ }
+
+ // Restore modified DX state
+ ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
+ ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
+ ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
+ ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
+ ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
+ ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
+ ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
+ ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
+ for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
+ ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
+ ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
+ for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
+ ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
+ ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
+ ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
+ ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
+}
+
+IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ ImGuiIO& io = ImGui::GetIO();
+ switch (msg)
+ {
+ case WM_LBUTTONDOWN:
+ io.MouseDown[0] = true;
+ return true;
+ case WM_LBUTTONUP:
+ io.MouseDown[0] = false;
+ return true;
+ case WM_RBUTTONDOWN:
+ io.MouseDown[1] = true;
+ return true;
+ case WM_RBUTTONUP:
+ io.MouseDown[1] = false;
+ return true;
+ case WM_MBUTTONDOWN:
+ io.MouseDown[2] = true;
+ return true;
+ case WM_MBUTTONUP:
+ io.MouseDown[2] = false;
+ return true;
+ case WM_MOUSEWHEEL:
+ io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
+ return true;
+ case WM_MOUSEMOVE:
+ io.MousePos.x = (signed short)(lParam);
+ io.MousePos.y = (signed short)(lParam >> 16);
+ return true;
+ case WM_KEYDOWN:
+ if (wParam < 256)
+ io.KeysDown[wParam] = 1;
+ return true;
+ case WM_KEYUP:
+ if (wParam < 256)
+ io.KeysDown[wParam] = 0;
+ return true;
+ case WM_CHAR:
+ // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
+ if (wParam > 0 && wParam < 0x10000)
+ io.AddInputCharacter((unsigned short)wParam);
+ return true;
+ }
+ return 0;
+}
+
+static void ImGui_ImplDX11_CreateFontsTexture()
+{
+ // Build texture atlas
+ ImGuiIO& io = ImGui::GetIO();
+ unsigned char* pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
+
+ // Upload texture to graphics system
+ {
+ D3D11_TEXTURE2D_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Width = width;
+ desc.Height = height;
+ desc.MipLevels = 1;
+ desc.ArraySize = 1;
+ desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ desc.SampleDesc.Count = 1;
+ desc.Usage = D3D11_USAGE_DEFAULT;
+ desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ desc.CPUAccessFlags = 0;
+
+ ID3D11Texture2D *pTexture = NULL;
+ D3D11_SUBRESOURCE_DATA subResource;
+ subResource.pSysMem = pixels;
+ subResource.SysMemPitch = desc.Width * 4;
+ subResource.SysMemSlicePitch = 0;
+ g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
+
+ // Create texture view
+ D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
+ ZeroMemory(&srvDesc, sizeof(srvDesc));
+ srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
+ srvDesc.Texture2D.MipLevels = desc.MipLevels;
+ srvDesc.Texture2D.MostDetailedMip = 0;
+ g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
+ pTexture->Release();
+ }
+
+ // Store our identifier
+ io.Fonts->TexID = (void *)g_pFontTextureView;
+
+ // Create texture sampler
+ {
+ D3D11_SAMPLER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
+ desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.MipLODBias = 0.f;
+ desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
+ desc.MinLOD = 0.f;
+ desc.MaxLOD = 0.f;
+ g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
+ }
+}
+
+bool ImGui_ImplDX11_CreateDeviceObjects()
+{
+ if (!g_pd3dDevice)
+ return false;
+ if (g_pFontSampler)
+ ImGui_ImplDX11_InvalidateDeviceObjects();
+
+ // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
+ // If you would like to use this DX11 sample code but remove this dependency you can:
+ // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [prefered solution]
+ // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
+ // See https://github.com/ocornut/imgui/pull/638 for sources and details.
+
+ // Create the vertex shader
+ {
+ static const char* vertexShader =
+ "cbuffer vertexBuffer : register(b0) \
+ {\
+ float4x4 ProjectionMatrix; \
+ };\
+ struct VS_INPUT\
+ {\
+ float2 pos : POSITION;\
+ float4 col : COLOR0;\
+ float2 uv : TEXCOORD0;\
+ };\
+ \
+ struct PS_INPUT\
+ {\
+ float4 pos : SV_POSITION;\
+ float4 col : COLOR0;\
+ float2 uv : TEXCOORD0;\
+ };\
+ \
+ PS_INPUT main(VS_INPUT input)\
+ {\
+ PS_INPUT output;\
+ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
+ output.col = input.col;\
+ output.uv = input.uv;\
+ return output;\
+ }";
+
+ D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
+ if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
+ return false;
+ if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
+ return false;
+
+ // Create the input layout
+ D3D11_INPUT_ELEMENT_DESC local_layout[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ };
+ if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
+ return false;
+
+ // Create the constant buffer
+ {
+ D3D11_BUFFER_DESC desc;
+ desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ desc.MiscFlags = 0;
+ g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
+ }
+ }
+
+ // Create the pixel shader
+ {
+ static const char* pixelShader =
+ "struct PS_INPUT\
+ {\
+ float4 pos : SV_POSITION;\
+ float4 col : COLOR0;\
+ float2 uv : TEXCOORD0;\
+ };\
+ sampler sampler0;\
+ Texture2D texture0;\
+ \
+ float4 main(PS_INPUT input) : SV_Target\
+ {\
+ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
+ return out_col; \
+ }";
+
+ D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
+ if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
+ return false;
+ if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
+ return false;
+ }
+
+ // Create the blending setup
+ {
+ D3D11_BLEND_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.AlphaToCoverageEnable = false;
+ desc.RenderTarget[0].BlendEnable = true;
+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
+ g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
+ }
+
+ // Create the rasterizer state
+ {
+ D3D11_RASTERIZER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.FillMode = D3D11_FILL_SOLID;
+ desc.CullMode = D3D11_CULL_NONE;
+ desc.ScissorEnable = true;
+ desc.DepthClipEnable = true;
+ g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
+ }
+
+ // Create depth-stencil State
+ {
+ D3D11_DEPTH_STENCIL_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.DepthEnable = false;
+ desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
+ desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
+ desc.StencilEnable = false;
+ desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
+ desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
+ desc.BackFace = desc.FrontFace;
+ g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
+ }
+
+ ImGui_ImplDX11_CreateFontsTexture();
+
+ return true;
+}
+
+void ImGui_ImplDX11_InvalidateDeviceObjects()
+{
+ if (!g_pd3dDevice)
+ return;
+
+ if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
+ if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = 0; }
+ if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
+ if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
+
+ if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
+ if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
+ if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
+ if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
+ if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
+ if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
+ if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
+ if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
+ if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
+}
+
+bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context)
+{
+ g_hWnd = (HWND)hwnd;
+ g_pd3dDevice = device;
+ g_pd3dDeviceContext = device_context;
+
+ if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
+ return false;
+ if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
+ return false;
+
+ ImGuiIO& io = ImGui::GetIO();
+ io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
+ io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
+ io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
+ io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
+ io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
+ io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
+ io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
+ io.KeyMap[ImGuiKey_Home] = VK_HOME;
+ io.KeyMap[ImGuiKey_End] = VK_END;
+ io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
+ io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
+ io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
+ io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
+ io.KeyMap[ImGuiKey_A] = 'A';
+ io.KeyMap[ImGuiKey_C] = 'C';
+ io.KeyMap[ImGuiKey_V] = 'V';
+ io.KeyMap[ImGuiKey_X] = 'X';
+ io.KeyMap[ImGuiKey_Y] = 'Y';
+ io.KeyMap[ImGuiKey_Z] = 'Z';
+
+ io.RenderDrawListsFn = ImGui_ImplDX11_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
+ io.ImeWindowHandle = g_hWnd;
+
+ return true;
+}
+
+void ImGui_ImplDX11_Shutdown()
+{
+ ImGui_ImplDX11_InvalidateDeviceObjects();
+ ImGui::Shutdown();
+ g_pd3dDevice = NULL;
+ g_pd3dDeviceContext = NULL;
+ g_hWnd = (HWND)0;
+}
+
+void ImGui_ImplDX11_NewFrame()
+{
+ if (!g_pFontSampler)
+ ImGui_ImplDX11_CreateDeviceObjects();
+
+ ImGuiIO& io = ImGui::GetIO();
+
+ // Setup display size (every frame to accommodate for window resizing)
+ RECT rect;
+ GetClientRect(g_hWnd, &rect);
+ io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
+
+ // Setup time step
+ INT64 current_time;
+ QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
+ io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
+ g_Time = current_time;
+
+ // Read keyboard modifiers inputs
+ io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
+ io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
+ io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
+ io.KeySuper = false;
+ // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
+ // io.MousePos : filled by WM_MOUSEMOVE events
+ // io.MouseDown : filled by WM_*BUTTON* events
+ // io.MouseWheel : filled by WM_MOUSEWHEEL events
+
+ // Hide OS mouse cursor if ImGui is drawing it
+ SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));
+
+ // Start the frame
+ ImGui::NewFrame();
+}
diff --git a/NvCloth/samples/SampleBase/ui/imgui_impl_dx11.h b/NvCloth/samples/SampleBase/ui/imgui_impl_dx11.h
new file mode 100644
index 0000000..7d6f710
--- /dev/null
+++ b/NvCloth/samples/SampleBase/ui/imgui_impl_dx11.h
@@ -0,0 +1,25 @@
+// ImGui Win32 + DirectX11 binding
+// In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+
+// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
+// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// https://github.com/ocornut/imgui
+
+struct ID3D11Device;
+struct ID3D11DeviceContext;
+
+IMGUI_API bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context);
+IMGUI_API void ImGui_ImplDX11_Shutdown();
+IMGUI_API void ImGui_ImplDX11_NewFrame();
+
+// Use if you want to reset your rendering device without losing ImGui state.
+IMGUI_API void ImGui_ImplDX11_InvalidateDeviceObjects();
+IMGUI_API bool ImGui_ImplDX11_CreateDeviceObjects();
+
+// Handler for Win32 messages, update mouse/keyboard data.
+// You may or not need this for your implementation, but it can serve as reference for handling inputs.
+// Commented out to avoid dragging dependencies on <windows.h> types. You can copy the extern declaration in your code.
+/*
+IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+*/
diff --git a/NvCloth/samples/SampleBase/utils/CallbackImplementations.cpp b/NvCloth/samples/SampleBase/utils/CallbackImplementations.cpp
new file mode 100644
index 0000000..0a257ba
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/CallbackImplementations.cpp
@@ -0,0 +1,110 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "CallbackImplementations.h"
+#include "JobManager.h"
+#include <iostream>
+
+//#if USE_DX11
+#include <d3d11.h>
+//#endif
+
+#include <PsThread.h>
+
+NvClothEnvironment* NvClothEnvironment::sEnv = nullptr;
+
+
+void ErrorCallback::reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line)
+{
+ const char* codeName = "???";
+ switch(code)
+ {
+#define CASE(x) case physx::PxErrorCode::Enum::x : codeName = #x; break;
+ CASE(eNO_ERROR)
+ CASE(eDEBUG_INFO)
+ CASE(eDEBUG_WARNING)
+ CASE(eINVALID_PARAMETER)
+ CASE(eINVALID_OPERATION)
+ CASE(eOUT_OF_MEMORY)
+ CASE(eINTERNAL_ERROR)
+ CASE(eABORT)
+ CASE(ePERF_WARNING)
+ default:
+ ;
+#undef CASE
+ }
+
+ std::cout << "Log " << codeName << " from file:" << file << ":" << line << "\n MSG:" << message << std::endl;
+}
+
+//#if USE_DX11
+DxContextManagerCallbackImpl::DxContextManagerCallbackImpl(ID3D11Device* device, bool synchronizeResources)
+ :
+ mDevice(device),
+ mSynchronizeResources(synchronizeResources)
+{
+ mDevice->AddRef();
+ mDevice->GetImmediateContext(&mContext);
+#ifdef _DEBUG
+ mLockCountTls = physx::shdfnd::TlsAlloc();
+#endif
+}
+DxContextManagerCallbackImpl::~DxContextManagerCallbackImpl()
+{
+ mContext->Release();
+
+#if _DEBUG
+ ID3D11Debug* debugDevice;
+ mDevice->QueryInterface(&debugDevice);
+ if(debugDevice)
+ {
+ debugDevice->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
+ debugDevice->Release();
+ }
+#endif
+
+ mDevice->Release();
+
+#if _DEBUG
+ physx::shdfnd::TlsFree(mLockCountTls);
+#endif
+}
+
+void DxContextManagerCallbackImpl::acquireContext()
+{
+
+ mMutex.lock();
+#if _DEBUG
+ physx::shdfnd::TlsSet(mLockCountTls, reinterpret_cast<void*>(reinterpret_cast<intptr_t>(physx::shdfnd::TlsGet(mLockCountTls)) + 1));
+#endif
+}
+void DxContextManagerCallbackImpl::releaseContext()
+{
+#if _DEBUG
+ physx::shdfnd::TlsSet(mLockCountTls, reinterpret_cast<void*>(reinterpret_cast<intptr_t>(physx::shdfnd::TlsGet(mLockCountTls)) - 1));
+#endif
+ mMutex.unlock();
+}
+ID3D11Device* DxContextManagerCallbackImpl::getDevice() const
+{
+ return mDevice;
+}
+ID3D11DeviceContext* DxContextManagerCallbackImpl::getContext() const
+{
+#if _DEBUG
+ assert(reinterpret_cast<intptr_t>(physx::shdfnd::TlsGet(mLockCountTls)) > 0);
+#endif
+ return mContext;
+}
+bool DxContextManagerCallbackImpl::synchronizeResources() const
+{
+ return mSynchronizeResources;
+}
+//#endif
diff --git a/NvCloth/samples/SampleBase/utils/CallbackImplementations.h b/NvCloth/samples/SampleBase/utils/CallbackImplementations.h
new file mode 100644
index 0000000..38a4b17
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/CallbackImplementations.h
@@ -0,0 +1,230 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#pragma once
+#include <NvCloth/Callbacks.h>
+#include <foundation/PxAllocatorCallback.h>
+#include <foundation/PxErrorCallback.h>
+#include <foundation/PxAssert.h>
+#include <foundation/PxProfiler.h>
+
+#include <vector>
+#include <map>
+
+#if USE_CUDA
+#include <cuda.h>
+#endif
+
+#include <string>
+#include <sstream>
+#include <assert.h>
+#include <mutex>
+
+#include <NvCloth/DxContextManagerCallback.h>
+
+#ifdef _MSC_VER
+#include <Windows.h>
+#endif
+
+class Allocator : public physx::PxAllocatorCallback
+{
+ public:
+ Allocator()
+ {
+ mEnableLeakDetection = false;
+ }
+ virtual void* allocate(size_t size, const char* typeName, const char* filename, int line)
+ {
+ #ifdef _MSC_VER
+ void* ptr = _aligned_malloc(size, 16);
+ #else
+ void* ptr;
+ if(posix_memalign(&ptr, 16, size)) ptr = 0;
+ #endif
+ if (mEnableLeakDetection)
+ {
+ std::lock_guard<std::mutex> lock(mAllocationsMapLock);
+ mAllocations[ptr] = Allocation(size, typeName, filename, line);
+ }
+ return ptr;
+ }
+ virtual void deallocate(void* ptr)
+ {
+ if (mEnableLeakDetection && ptr)
+ {
+ std::lock_guard<std::mutex> lock(mAllocationsMapLock);
+ auto i = mAllocations.find(ptr);
+ if (i == mAllocations.end())
+ {
+ printf("Tried to deallocate %p which was not allocated with this allocator callback.",ptr);
+ }
+ else
+ {
+ mAllocations.erase(i);
+ }
+ }
+ #ifdef _MSC_VER
+ _aligned_free(ptr);
+ #else
+ free(ptr);
+ #endif
+ }
+
+ void StartTrackingLeaks()
+ {
+ std::lock_guard<std::mutex> lock(mAllocationsMapLock);
+ mAllocations.clear();
+ mEnableLeakDetection = true;
+ }
+
+ void StopTrackingLeaksAndReport()
+ {
+ std::lock_guard<std::mutex> lock(mAllocationsMapLock);
+ mEnableLeakDetection = false;
+
+ size_t totalBytes = 0;
+ std::stringstream message;
+ message << "Memory leaks detected:\n";
+ for (auto it = mAllocations.begin(); it != mAllocations.end(); ++it)
+ {
+ const Allocation& alloc = it->second;
+ message << "* Allocated ptr " << it->first << " of " << alloc.mSize << "bytes (type=" << alloc.mTypeName << ") at " << alloc.mFileName << ":" << alloc.mLine<<"\n";
+ totalBytes += alloc.mSize;
+ }
+ if (mAllocations.size()>0)
+ {
+ message << "=====Total of " << totalBytes << " bytes in " << mAllocations.size() << " allocations leaked=====";
+ const std::string& tmp = message.str();
+#ifdef _MSC_VER
+// OutputDebugString(tmp.c_str()); //Write to visual studio output so we can see it after the application closes
+#endif
+ printf("%s\n", tmp.c_str());
+ }
+
+ mAllocations.clear();
+ }
+ private:
+ bool mEnableLeakDetection;
+ struct Allocation
+ {
+ Allocation(){}
+ Allocation(size_t size, const char* typeName, const char* filename, int line)
+ : mSize(size), mTypeName(typeName), mFileName(filename), mLine(line)
+ {
+
+ }
+ size_t mSize;
+ std::string mTypeName;
+ std::string mFileName;
+ int mLine;
+ };
+ std::map<void*,Allocation> mAllocations;
+ std::mutex mAllocationsMapLock;
+};
+
+class ErrorCallback : public physx::PxErrorCallback
+{
+ public:
+ ErrorCallback(){}
+ virtual void reportError(physx::PxErrorCode::Enum code, const char* message, const char* file, int line);
+};
+
+
+class AssertHandler : public physx::PxAssertHandler
+{
+ public:
+ virtual void operator()(const char* exp, const char* file, int line, bool& ignore)
+ {
+ PX_UNUSED(ignore);
+ printf("NV_CLOTH_ASSERT(%s) from file:%s:%d Failed\n", exp, file, line);
+ assert(("Assertion failed, see log/console for more info.",0));
+ }
+};
+
+
+class NvClothEnvironment
+{
+ NvClothEnvironment()
+ {
+ SetUp();
+ }
+ virtual ~NvClothEnvironment()
+ {
+ TearDown();
+ }
+
+ static NvClothEnvironment* sEnv;
+
+ public:
+ static void AllocateEnv()
+ {
+ sEnv = new NvClothEnvironment;
+ }
+ static void FreeEnv(){ delete sEnv; sEnv = nullptr; }
+ static void ReportEnvFreed(){ sEnv = nullptr; } //google test will free it for us, so we just reset the value
+ static NvClothEnvironment* GetEnv(){ return sEnv; }
+
+ virtual void SetUp()
+ {
+ mAllocator = new Allocator;
+ mAllocator->StartTrackingLeaks();
+ mFoundationAllocator = new Allocator;
+ mFoundationAllocator->StartTrackingLeaks();
+ mErrorCallback = new ErrorCallback;
+ mAssertHandler = new AssertHandler;
+ nv::cloth::InitializeNvCloth(mAllocator, mErrorCallback, mAssertHandler, nullptr);
+#if USE_CUDA
+ cuInit(0);
+#endif
+ }
+ virtual void TearDown()
+ {
+ mAllocator->StopTrackingLeaksAndReport();
+ mFoundationAllocator->StopTrackingLeaksAndReport();
+ delete mErrorCallback;
+ delete mFoundationAllocator;
+ delete mAllocator;
+ delete mAssertHandler;
+ }
+
+ Allocator* GetAllocator(){ return mAllocator; }
+ Allocator* GetFoundationAllocator(){ return mFoundationAllocator; }
+ ErrorCallback* GetErrorCallback(){ return mErrorCallback; }
+ AssertHandler* GetAssertHandler(){ return mAssertHandler; }
+
+ private:
+ Allocator* mAllocator;
+ Allocator* mFoundationAllocator;
+ ErrorCallback* mErrorCallback;
+ AssertHandler* mAssertHandler;
+};
+
+//#if USE_DX11
+class DxContextManagerCallbackImpl : public nv::cloth::DxContextManagerCallback
+{
+public:
+ DxContextManagerCallbackImpl(ID3D11Device* device, bool synchronizeResources = false);
+ ~DxContextManagerCallbackImpl();
+ virtual void acquireContext() override;
+ virtual void releaseContext() override;
+ virtual ID3D11Device* getDevice() const override;
+ virtual ID3D11DeviceContext* getContext() const override;
+ virtual bool synchronizeResources() const override;
+
+private:
+ std::recursive_mutex mMutex;
+ ID3D11Device* mDevice;
+ ID3D11DeviceContext* mContext;
+ bool mSynchronizeResources;
+#ifdef _DEBUG
+ uint32_t mLockCountTls;
+#endif
+};
+//#endif
diff --git a/NvCloth/samples/SampleBase/utils/ClothMeshGenerator.cpp b/NvCloth/samples/SampleBase/utils/ClothMeshGenerator.cpp
new file mode 100644
index 0000000..d75bb25
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/ClothMeshGenerator.cpp
@@ -0,0 +1,193 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "ClothMeshGenerator.h"
+
+void ClothMeshData::Clear()
+{
+ mVertices.clear();
+ mTriangles.clear();
+ mQuads.clear();
+}
+
+void ClothMeshData::GeneratePlaneCloth(float width, float height, int segmentsX, int segmentsY, bool createQuads, physx::PxMat44 transform, bool alternatingDiagonals)
+{
+
+/*
+GeneratePlaneCloth(x,y,2,2) generates:
+
+ v0______v1_____v2 v0______v1_____v2
+ | | | |\ |\ |
+ | Q0 | Q1 | | \t0 | \t2 |
+ | | | | t1 \ | t3 \ |
+ v3------v4-----v5 v3-----\v4----\v5
+ | | | | \ | \ |
+ | Q2 | Q3 | | \t4| \t6|
+ |______|______| |_t5_\_|_t7__\|
+ v6 v7 v8 v6 v7 v8
+*/
+
+
+// Submesh submesh;
+
+ Clear();
+ mVertices.resize((segmentsX + 1) * (segmentsY + 1));
+ mInvMasses.resize((segmentsX + 1) * (segmentsY + 1));
+ mTriangles.resize(segmentsX * segmentsY * 2);
+ if (createQuads)
+ mQuads.resize(segmentsX * segmentsY);
+
+ mMesh.vertices.resize(mVertices.size());
+ mMesh.indices.resize(3 * mTriangles.size());
+
+ physx::PxVec3 topLeft(-width * 0.5f, 0.f, -height * 0.5f);
+// vec3 topLeftGLM(-width * 0.5f, translateUp, -height * 0.5f);
+
+ //calculate uv scale and offset to keep texture aspect ratio 1:1
+ float uvSx = width > height ? 1.0f : width / height;
+ float uvSy = width > height ? height / width : 1.0f;
+ float uvOx = 0.5f * (1.0f - uvSx);
+ float uvOy = 0.5f * (1.0f - uvSy);
+
+ // Vertices
+ for (int y = 0; y < segmentsY + 1; y++)
+ {
+ for(int x = 0; x < segmentsX + 1; x++)
+ {
+ mVertices[x + y * (segmentsX + 1)] = transform.transform(topLeft + physx::PxVec3( ((float)x / (float)segmentsX) * width,
+ 0.f,
+ ((float)y / (float)segmentsY) * height));
+ mInvMasses[x + y * (segmentsX + 1)] = 1.0f;
+
+ mMesh.vertices[x + y * (segmentsX + 1)].position = transform.transform(topLeft + physx::PxVec3(((float)x / (float)segmentsX) * width,
+ 0.f,
+ ((float)y / (float)segmentsY) * height));
+ mMesh.vertices[x + y * (segmentsX + 1)].normal = transform.transform(physx::PxVec3(0.f, 1.f, 0.f));
+
+ mMesh.vertices[x + y * (segmentsX + 1)].uv = physx::PxVec2(uvOx + uvSx*(float)x / (float)segmentsX, uvOy + uvSy*(1.0f - (float)y / (float)segmentsY));
+ }
+ }
+
+ if (createQuads)
+ {
+ // Quads
+ for (int y = 0; y < segmentsY; y++)
+ {
+ for (int x = 0; x < segmentsX; x++)
+ {
+ mQuads[(x + y * segmentsX)] = Quad((uint32_t)(x + 0) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 1) * (segmentsX + 1),
+ (uint32_t)(x + 0) + (y + 1) * (segmentsX + 1));
+ }
+ }
+ }
+
+ // Triangles
+ for (int y = 0; y < segmentsY; y++)
+ {
+ for(int x = 0; x < segmentsX; x++)
+ {
+ if(alternatingDiagonals && (x^y)&1)
+ {
+ //Top right to bottom left
+ mTriangles[(x + y * segmentsX) * 2 + 0] = Triangle( (uint32_t)(x + 0) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 0) + (y + 1) * (segmentsX + 1));
+
+ mTriangles[(x + y * segmentsX) * 2 + 1] = Triangle( (uint32_t)(x + 1) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 1) * (segmentsX + 1),
+ (uint32_t)(x + 0) + (y + 1) * (segmentsX + 1));
+ }
+ else
+ {
+ //Top left to bottom right
+ mTriangles[(x + y * segmentsX) * 2 + 0] = Triangle( (uint32_t)(x + 0) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 1) * (segmentsX + 1));
+
+ mTriangles[(x + y * segmentsX) * 2 + 1] = Triangle( (uint32_t)(x + 0) + (y + 0) * (segmentsX + 1),
+ (uint32_t)(x + 1) + (y + 1) * (segmentsX + 1),
+ (uint32_t)(x + 0) + (y + 1) * (segmentsX + 1));
+ }
+ }
+ }
+
+ for (int i = 0; i < (int)mTriangles.size(); i++)
+ {
+ mMesh.indices[3 * i] = mTriangles[i].a;
+ mMesh.indices[3 * i + 1] = mTriangles[i].b;
+ mMesh.indices[3 * i + 2] = mTriangles[i].c;
+ }
+}
+
+void ClothMeshData::AttachClothPlaneByAngles(int segmentsX, int segmentsY, bool attachByWidth)
+{
+ for (int y = 0; y < segmentsY + 1; y++)
+ for (int x = 0; x < segmentsX + 1; x++)
+ if ((attachByWidth && y == 0) || (!attachByWidth && x == 0))
+ if (x == 0 || x == segmentsX)
+ mInvMasses[x + y * (segmentsX + 1)] = 0.0f;
+}
+
+void ClothMeshData::AttachClothPlaneBySide(int segmentsX, int segmentsY, bool attachByWidth)
+{
+ for (int y = 0; y < segmentsY + 1; y++)
+ for (int x = 0; x < segmentsX + 1; x++)
+ if ((attachByWidth && y == 0) || (!attachByWidth && x == 0))
+ mInvMasses[x + y * (segmentsX + 1)] = 0.0f;
+}
+
+void ClothMeshData::SetInvMasses(float invMass)
+{
+ // Doesn't modify attached vertices
+ for (int i = 0; i < (int)mInvMasses.size(); ++i)
+ if (mInvMasses[i] > 1e-6f)
+ mInvMasses[i] = invMass;
+}
+
+void ClothMeshData::SetInvMassesFromDensity(float density)
+{
+ // Tempt code, should take into account triangle's areas
+ // Doesn't modify attached vertices
+ for (int i = 0; i < (int)mInvMasses.size(); ++i)
+ if (mInvMasses[i] > 1e-6f)
+ mInvMasses[i] = 1.f / density;
+}
+
+template <typename T>
+nv::cloth::BoundedData ToBoundedData(T& vector)
+{
+ nv::cloth::BoundedData d;
+ d.data = &vector[0];
+ d.stride = sizeof(vector[0]);
+ d.count = (physx::PxU32)vector.size();
+
+ return d;
+}
+
+nv::cloth::ClothMeshDesc ClothMeshData::GetClothMeshDesc()
+{
+ nv::cloth::ClothMeshDesc d;
+ d.setToDefault();
+ d.points = ToBoundedData(mVertices);
+ if (mQuads.size() != 0)
+ d.quads = ToBoundedData(mQuads);
+ if (mTriangles.size() != 0)
+ d.triangles = ToBoundedData(mTriangles);
+ d.invMasses = ToBoundedData(mInvMasses);
+
+ return d;
+}
+
+SimpleMesh ClothMeshData::GetRenderMesh()
+{
+ return mMesh;
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/utils/ClothMeshGenerator.h b/NvCloth/samples/SampleBase/utils/ClothMeshGenerator.h
new file mode 100644
index 0000000..0f57230
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/ClothMeshGenerator.h
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#pragma once
+#include <vector>
+#include <foundation/PxVec3.h>
+#include <foundation/PxVec2.h>
+#include "NvClothExt/ClothFabricCooker.h"
+#include <foundation/PxMat44.h>
+#include "Mesh.h"
+
+struct ClothMeshData
+{
+ struct Triangle
+ {
+ Triangle(){}
+ Triangle(uint32_t _a, uint32_t _b, uint32_t _c) :
+ a(_a), b(_b), c(_c){}
+ uint32_t a, b, c;
+ };
+ struct Quad
+ {
+ Quad(){}
+ Quad(uint32_t _a, uint32_t _b, uint32_t _c, uint32_t _d) :
+ a(_a), b(_b), c(_c), d(_d){}
+ uint32_t a, b, c, d;
+ };
+ std::vector<physx::PxVec3> mVertices;
+ std::vector<physx::PxVec2> mUvs;
+ std::vector<Triangle> mTriangles;
+ std::vector<Quad> mQuads;
+ std::vector<physx::PxReal> mInvMasses;
+
+ SimpleMesh mMesh;
+
+ void Clear();
+ void GeneratePlaneCloth(float width, float height, int segmentsX, int segmentsY, bool createQuads = false, physx::PxMat44 transform = physx::PxIdentity, bool alternatingDiagonals = true);
+
+ void AttachClothPlaneByAngles(int segmentsX, int segmentsY, bool attachByWidth = true);
+ void AttachClothPlaneBySide(int segmentsX, int segmentsY, bool attachByWidth = true);
+
+ void SetInvMasses(float invMass);
+ void SetInvMassesFromDensity(float density); // Todo
+
+ nv::cloth::ClothMeshDesc GetClothMeshDesc();
+ SimpleMesh GetRenderMesh();
+};
diff --git a/NvCloth/samples/SampleBase/utils/JobManager.cpp b/NvCloth/samples/SampleBase/utils/JobManager.cpp
new file mode 100644
index 0000000..093db60
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/JobManager.cpp
@@ -0,0 +1,136 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#include "JobManager.h"
+#define _USE_MATH_DEFINES
+#include <math.h>
+#include <NvCloth/Solver.h>
+
+void Job::Initialize(JobManager* parent, std::function<void(Job*)> function, int refcount)
+{
+ mFunction = function;
+ mParent = parent;
+ Reset(refcount);
+}
+
+Job::Job(const Job& job)
+{
+ mFunction = job.mFunction;
+ mParent = job.mParent;
+ mRefCount.store(job.mRefCount);
+ mFinished = job.mFinished;
+}
+
+void Job::Reset(int refcount)
+{
+ mRefCount = refcount;
+ mFinished = false;
+}
+
+void Job::Execute()
+{
+ if (mFunction)
+ mFunction(this);
+ else
+ ExecuteInternal();
+
+ mFinishedLock.lock();
+ mFinished = true;
+ mFinishedLock.unlock();
+ mFinishedEvent.notify_one();
+}
+
+void Job::AddReference()
+{
+ mRefCount++;
+}
+void Job::RemoveReference()
+{
+ if (0 == --mRefCount)
+ {
+ mParent->Submit(this);
+ }
+}
+
+void Job::Wait()
+{
+ std::unique_lock<std::mutex> lock(mFinishedLock);
+ mFinishedEvent.wait(lock, [this](){return mFinished;} );
+ return;
+}
+
+void JobManager::WorkerEntryPoint(JobManager* parrent)
+{
+ while (true)
+ {
+ Job* job;
+ {
+ std::unique_lock<std::mutex> lock(parrent->mJobQueueLock);
+ while (parrent->mJobQueue.size() == 0 && !parrent->mQuit)
+ parrent->mJobQueueEvent.wait(lock);
+
+ if (parrent->mQuit)
+ return;
+
+ job = parrent->mJobQueue.front();
+ parrent->mJobQueue.pop();
+ }
+ job->Execute();
+ }
+}
+
+void JobManager::Submit(Job* job)
+{
+ mJobQueueLock.lock();
+ mJobQueue.push(job);
+ mJobQueueLock.unlock();
+ mJobQueueEvent.notify_one();
+}
+
+void MultithreadedSolverHelper::Initialize(nv::cloth::Solver* solver, JobManager* jobManager)
+{
+ mSolver = solver;
+ mJobManager = jobManager;
+ mEndSimulationJob.Initialize(mJobManager, [this](Job*) {
+ mSolver->endSimulation();
+ });
+
+ mStartSimulationJob.Initialize(mJobManager, [this](Job*) {
+ mSolver->beginSimulation(mDt);
+ for(int j = 0; j < mSolver->getSimulationChunkCount(); j++)
+ mSimulationChunkJobs[j].RemoveReference();
+ });
+}
+
+void MultithreadedSolverHelper::StartSimulation(float dt)
+{
+ mDt = dt;
+
+ if (mSolver->getSimulationChunkCount() != mSimulationChunkJobs.size())
+ {
+ mSimulationChunkJobs.resize(mSolver->getSimulationChunkCount(), Job());
+ for (int j = 0; j < mSolver->getSimulationChunkCount(); j++)
+ mSimulationChunkJobs[j].Initialize(mJobManager, [this, j](Job*) {mSolver->simulateChunk(j); mEndSimulationJob.RemoveReference(); });
+ }
+ else
+ {
+ for (int j = 0; j < mSolver->getSimulationChunkCount(); j++)
+ mSimulationChunkJobs[j].Reset();
+ }
+ mStartSimulationJob.Reset();
+ mEndSimulationJob.Reset(mSolver->getSimulationChunkCount());
+ mStartSimulationJob.RemoveReference();
+
+}
+
+void MultithreadedSolverHelper::WaitForSimulation()
+{
+ mEndSimulationJob.Wait();
+} \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/utils/JobManager.h b/NvCloth/samples/SampleBase/utils/JobManager.h
new file mode 100644
index 0000000..648fa33
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/JobManager.h
@@ -0,0 +1,175 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#pragma once
+
+#include <foundation/PxErrorCallback.h>
+#include <regex>
+#include "CallbackImplementations.h"
+#include <mutex>
+#include <thread>
+#include <condition_variable>
+
+#include <foundation/PxVec4.h>
+#include <foundation/PxVec3.h>
+#include <vector>
+#include <queue>
+#include <atomic>
+
+#include <task/PxTaskManager.h>
+#include <task/PxTask.h>
+
+namespace nv
+{
+namespace cloth
+{
+class Solver;
+}
+}
+
+///Dummy task that can be used as end node in a task graph.
+class DummyTask : public physx::PxTask
+{
+public:
+ DummyTask() { mFinished = false; mTm = nullptr; }
+ DummyTask(physx::PxTaskManager* tm) { mFinished = false; mTm = tm; mTm->submitUnnamedTask(*this); }
+ ~DummyTask() { mTm = nullptr; } //Way to catch race conditions. Will usually crash on nullptr if the task gets deleted before the taskmanager is done with it.
+
+ virtual void run() override { }
+ virtual void release() override { physx::PxTask::release(); mFinished = true; mWaitEvent.notify_all(); }
+ virtual const char* getName() const override { return "DummyTask"; }
+
+ void Reset(physx::PxTaskManager* tm) { mFinished = false; mTm = tm; mTm->submitUnnamedTask(*this); }
+
+ ///Use Wait to block the calling thread until this task is finished and save to delete
+ void Wait()
+ {
+ std::mutex eventLock;
+ std::unique_lock<std::mutex> lock(eventLock);
+ while (!mFinished) { mWaitEvent.wait(lock); }
+ }
+
+private:
+ std::condition_variable mWaitEvent;
+ bool mFinished;
+};
+
+class CpuDispatcher : public physx::PxCpuDispatcher
+{
+ virtual void submitTask(physx::PxBaseTask& task)
+ {
+ task.run();
+ task.release();
+ }
+ virtual uint32_t getWorkerCount() const { return 1; }
+};
+
+
+class JobManager;
+class Job
+{
+public:
+ Job() = default;
+ Job(const Job&);
+ void Initialize(JobManager* parent, std::function<void(Job*)> function = std::function<void(Job*)>(), int refcount = 1);
+ void Reset(int refcount = 1); //Call this before reusing a job that doesn't need to be reinitialized
+ void Execute();
+ void AddReference();
+ void RemoveReference();
+ void Wait(); //Block until job is finished
+private:
+ virtual void ExecuteInternal() {}
+
+ std::function<void(Job*)> mFunction;
+ JobManager* mParent;
+ std::atomic_int mRefCount;
+
+ bool mFinished;
+ std::mutex mFinishedLock;
+ std::condition_variable mFinishedEvent;
+};
+
+class JobManager
+{
+public:
+ JobManager()
+ {
+ mWorkerCount = 8;
+ mWorkerThreads = new std::thread[mWorkerCount];
+ mQuit = false;
+
+ for(int i = 0; i < mWorkerCount; i++)
+ mWorkerThreads[i] = std::thread(JobManager::WorkerEntryPoint, this);
+ }
+ ~JobManager()
+ {
+ if(!mQuit)
+ Quit();
+ }
+
+ void Quit()
+ {
+ std::unique_lock<std::mutex> lock(mJobQueueLock);
+ mQuit = true;
+ lock.unlock();
+ mJobQueueEvent.notify_all();
+ for(int i = 0; i < mWorkerCount; i++)
+ {
+ mWorkerThreads[i].join();
+ }
+ delete[] mWorkerThreads;
+ }
+
+ template <int count, typename F>
+ void ParallelLoop(F const& function)
+ {
+ /*for(int i = 0; i < count; i++)
+ function(i);*/
+ Job finalJob;
+ finalJob.Initialize(this, std::function<void(Job*)>(), count);
+ Job jobs[count];
+ for(int j = 0; j < count; j++)
+ {
+ jobs[j].Initialize(this, [j, &finalJob, function](Job*) {function(j); finalJob.RemoveReference(); });
+ jobs[j].RemoveReference();
+ }
+ finalJob.Wait();
+ }
+
+ static void WorkerEntryPoint(JobManager* parrent);
+private:
+ friend class Job;
+ void Submit(Job* job);
+
+ int mWorkerCount;
+ std::thread* mWorkerThreads;
+
+ std::mutex mJobQueueLock;
+ std::queue<Job*> mJobQueue;
+ std::condition_variable mJobQueueEvent;
+ bool mQuit;
+};
+
+class MultithreadedSolverHelper
+{
+public:
+ void Initialize(nv::cloth::Solver* solver, JobManager* jobManager);
+ void StartSimulation(float dt);
+ void WaitForSimulation();
+private:
+ Job mStartSimulationJob;
+ Job mEndSimulationJob;
+ std::vector<Job> mSimulationChunkJobs;
+
+ float mDt;
+
+ nv::cloth::Solver* mSolver;
+ JobManager* mJobManager;
+};
diff --git a/NvCloth/samples/SampleBase/utils/SampleProfiler.cpp b/NvCloth/samples/SampleBase/utils/SampleProfiler.cpp
new file mode 100644
index 0000000..0438b06
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/SampleProfiler.cpp
@@ -0,0 +1,223 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+
+#include "SampleProfiler.h"
+#include <map>
+#include <iostream>
+#include <fstream>
+#include <stack>
+
+using namespace std::chrono;
+
+struct ProfileData
+{
+ steady_clock::time_point start;
+
+ microseconds time;
+ microseconds prevTime;
+ microseconds maxTime;
+ uint32_t calls;
+ uint32_t prevCalls;
+
+ ProfileData() : time(0), prevTime(0), maxTime(0), calls(0), prevCalls(0)
+ {}
+};
+
+struct Node
+{
+ ProfileData data;
+ std::map<const char*, Node> childs;
+ Node* parent;
+};
+
+static std::map<const char*, Node> s_roots;
+static Node* s_currentNode;
+static bool s_beginEndMismatch;
+static microseconds s_overhead;
+static microseconds s_prevOverhead;
+
+void SampleProfilerInit()
+{
+ s_roots.clear();
+ s_currentNode = nullptr;
+ s_beginEndMismatch = false;
+ s_overhead = microseconds();
+}
+
+void SampleProfilerBegin(const char* name)
+{
+ auto start = steady_clock::now();
+ {
+ Node* parent = s_currentNode;
+ if (s_currentNode == nullptr)
+ {
+ s_currentNode = &s_roots[name];
+ }
+ else
+ {
+ s_currentNode = &s_currentNode->childs[name];
+ }
+ s_currentNode->parent = parent;
+ s_currentNode->data.calls++;
+ s_currentNode->data.start = steady_clock::now();
+ }
+ s_overhead += duration_cast<microseconds>(steady_clock::now() - start);
+}
+
+void SampleProfilerEnd()
+{
+ auto start = steady_clock::now();
+ {
+ if (s_currentNode)
+ {
+ auto& data = s_currentNode->data;
+ data.time += duration_cast<microseconds>(steady_clock::now() - data.start);
+ data.maxTime = data.time > data.maxTime ? data.time : data.maxTime;
+ s_currentNode = s_currentNode->parent;
+ }
+ else
+ {
+ s_beginEndMismatch = true;
+ }
+ }
+ s_overhead += duration_cast<microseconds>(steady_clock::now() - start);
+}
+
+struct SampleProfilerTreeIteratorImpl final : public SampleProfilerTreeIterator
+{
+ struct StackNode
+ {
+ Node* node;
+ const char* name;
+ };
+
+ SampleProfilerTreeIteratorImpl(std::map<const char*, Node>& roots)
+ {
+ for (auto& root : roots)
+ {
+ m_stack.emplace(StackNode { &root.second, root.first });
+ }
+
+ next();
+ }
+
+ virtual const Data* data() const override
+ {
+ return m_valid ? &m_data : nullptr;
+ }
+
+ Node* node()
+ {
+ return m_node;
+ }
+
+ virtual bool isDone() const
+ {
+ return !m_valid;
+ }
+
+ virtual void next()
+ {
+ if (!m_stack.empty())
+ {
+ auto& e = m_stack.top();
+ m_stack.pop();
+ m_node = e.node;
+ m_data.depth = 0;
+ m_data.hash = (uint64_t)m_node;
+ for (const Node* p = m_node; p != nullptr; p = p->parent)
+ {
+ m_data.depth++;
+ }
+ m_data.name = e.name;
+ m_data.calls = m_node->data.prevCalls;
+ m_data.time = m_node->data.prevTime;
+ m_data.maxTime = m_node->data.maxTime;
+ m_data.hasChilds = !m_node->childs.empty();
+
+ for (auto it = m_node->childs.rbegin(); it != m_node->childs.rend(); ++it)
+ {
+ m_stack.emplace(StackNode { &(*it).second, (*it).first });
+ }
+ m_valid = true;
+ }
+ else
+ {
+ m_valid = false;
+ }
+ }
+
+ virtual void release()
+ {
+ delete this;
+ }
+
+ bool m_valid;
+ Data m_data;
+ Node* m_node;
+ std::stack<StackNode > m_stack;
+};
+
+void SampleProfilerReset()
+{
+ for (SampleProfilerTreeIteratorImpl it(s_roots); !it.isDone(); it.next())
+ {
+ auto& data = it.node()->data;
+ data.prevTime = data.time;
+ data.prevCalls = data.calls;
+ data.time = microseconds();
+ data.calls = 0;
+ }
+ s_currentNode = nullptr;
+ s_beginEndMismatch = false;
+ s_prevOverhead = s_overhead;
+ s_overhead = microseconds();
+}
+
+bool SampleProfilerIsValid()
+{
+ return !s_beginEndMismatch;
+}
+
+microseconds SampleProfilerGetOverhead()
+{
+ return s_prevOverhead;
+}
+
+SampleProfilerTreeIterator* SampleProfilerCreateTreeIterator()
+{
+ return SampleProfilerIsValid() ? new SampleProfilerTreeIteratorImpl(s_roots) : nullptr;
+}
+
+void SampleProfilerDumpToFile(const char* path)
+{
+ std::ofstream myfile(path, std::ios_base::out);
+ if (myfile.is_open())
+ {
+ if (s_beginEndMismatch)
+ {
+ myfile << "Error: Begin/End Mismatch.\n";
+ }
+ else
+ {
+ myfile << "[Root]\n";
+ for(SampleProfilerTreeIteratorImpl it(s_roots); !it.isDone(); it.next())
+ {
+ auto data = it.data();
+ for (uint32_t i = 0; i < data->depth; ++i)
+ myfile << "\t";
+ myfile << data->name << " --> calls: " << data->calls << ", total: " << data->time.count() * 0.001 << "ms\n";
+ }
+ }
+
+ myfile.close();
+ }
+}
diff --git a/NvCloth/samples/SampleBase/utils/SampleProfiler.h b/NvCloth/samples/SampleBase/utils/SampleProfiler.h
new file mode 100644
index 0000000..af0002c
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/SampleProfiler.h
@@ -0,0 +1,79 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SAMPLEPROFILER_H
+#define SAMPLEPROFILER_H
+
+#include <chrono>
+
+#if NV_PROFILE
+
+void SampleProfilerInit();
+void SampleProfilerBegin(const char* name);
+void SampleProfilerEnd();
+void SampleProfilerReset();
+
+struct SampleProfilerScoped
+{
+ SampleProfilerScoped(const char* name)
+ {
+ SampleProfilerBegin(name);
+ }
+
+ ~SampleProfilerScoped()
+ {
+ SampleProfilerEnd();
+ }
+};
+
+#define PROFILER_INIT() SampleProfilerInit()
+#define PROFILER_BEGIN(x) SampleProfilerBegin(x)
+#define PROFILER_END() SampleProfilerEnd()
+#define PROFILER_SCOPED(x) SampleProfilerScoped __scopedProfiler__(x)
+#define PROFILER_SCOPED_FUNCTION() SampleProfilerScoped __scopedProfiler__(__FUNCTION__)
+#define PROFILER_RESET() SampleProfilerReset()
+
+#else
+
+#define PROFILER_INIT()
+#define PROFILER_BEGIN(x)
+#define PROFILER_END()
+#define PROFILER_SCOPED(x)
+#define PROFILER_SCOPED_FUNCTION()
+#define PROFILER_RESET()
+
+#endif
+
+void SampleProfilerDumpToFile(const char* path);
+bool SampleProfilerIsValid();
+std::chrono::microseconds SampleProfilerGetOverhead();
+
+struct SampleProfilerTreeIterator
+{
+ struct Data
+ {
+ uint64_t hash;
+ const char* name;
+ bool hasChilds;
+ uint32_t depth;
+ std::chrono::microseconds time;
+ std::chrono::microseconds maxTime;
+ uint32_t calls;
+ };
+
+ virtual const Data* data() const = 0;
+ virtual bool isDone() const = 0;
+ virtual void next() = 0;
+ virtual void release() = 0;
+};
+
+SampleProfilerTreeIterator* SampleProfilerCreateTreeIterator();
+
+#endif //SAMPLEPROFILER_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/utils/SampleTime.h b/NvCloth/samples/SampleBase/utils/SampleTime.h
new file mode 100644
index 0000000..eac895d
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/SampleTime.h
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef SAMPLE_TIME_H
+#define SAMPLE_TIME_H
+
+#include <stdint.h>
+
+class Time
+{
+public:
+ Time() : m_lastTickCount(getTimeTicks()) {}
+
+ double Time::getElapsedSeconds()
+ {
+ const int64_t lastTickCount = m_lastTickCount;
+ m_lastTickCount = getTimeTicks();
+ return (m_lastTickCount - lastTickCount) * s_secondsPerTick;
+ }
+
+ double Time::peekElapsedSeconds() const
+ {
+ return (getTimeTicks() - m_lastTickCount) * s_secondsPerTick;
+ }
+
+ double Time::getLastTime() const
+ {
+ return m_lastTickCount * s_secondsPerTick;
+ }
+
+private:
+ static double getTickDuration()
+ {
+ LARGE_INTEGER a;
+ QueryPerformanceFrequency(&a);
+ return 1.0 / (double)a.QuadPart;
+ }
+
+ int64_t getTimeTicks() const
+ {
+ LARGE_INTEGER a;
+ QueryPerformanceCounter(&a);
+ return a.QuadPart;
+ }
+
+ int64_t m_lastTickCount;
+ static const double s_secondsPerTick;
+};
+
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/utils/UIHelpers.h b/NvCloth/samples/SampleBase/utils/UIHelpers.h
new file mode 100644
index 0000000..5c4dfee
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/UIHelpers.h
@@ -0,0 +1,56 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+#ifndef UI_HELPERS_H
+#define UI_HELPERS_H
+
+#include "imgui.h"
+#include "PxVec3.h"
+
+
+static void ImGui_DragFloat3Dir(const char* label, float v[3])
+{
+ if (ImGui::Button("Normalize"))
+ {
+ ((physx::PxVec3*)v)->normalize();
+ }
+ ImGui::SameLine();
+ ImGui::DragFloat3(label, v);
+};
+
+
+#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
+
+template<int valuesCount = 90>
+class PlotLinesInstance
+{
+public:
+ PlotLinesInstance()
+ {
+ memset(m_values, 0, sizeof(float) * valuesCount);
+ }
+
+ void plot(const char* label, float newValue, const char* overlay_text, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 80))
+ {
+ for (; ImGui::GetTime() > m_time + 1.0f / 60.0f; m_time += 1.0f / 60.0f)
+ {
+ m_values[m_offset] = newValue;
+ m_offset = (m_offset + 1) % valuesCount;
+ }
+ ImGui::PlotLines(label, m_values, valuesCount, m_offset, overlay_text, scale_min, scale_max, graph_size);
+ }
+
+private:
+ float m_values[valuesCount];
+ int m_offset;
+ float m_time = ImGui::GetTime();
+};
+
+#endif //UI_HELPERS_H \ No newline at end of file
diff --git a/NvCloth/samples/SampleBase/utils/Utils.cpp b/NvCloth/samples/SampleBase/utils/Utils.cpp
new file mode 100644
index 0000000..a271137
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/Utils.cpp
@@ -0,0 +1,13 @@
+#include "Utils.h"
+
+#include <string>
+#include <cstdarg>
+
+HRESULT messagebox_printf(const char* caption, UINT mb_type, const char* format, ...)
+{
+ va_list args;
+ va_start(args, format);
+ char formatted_text[512];
+ _vsnprintf(formatted_text, 512, format, args);
+ return MessageBoxA(nullptr, formatted_text, caption, mb_type);
+}
diff --git a/NvCloth/samples/SampleBase/utils/Utils.h b/NvCloth/samples/SampleBase/utils/Utils.h
new file mode 100644
index 0000000..5e84e8e
--- /dev/null
+++ b/NvCloth/samples/SampleBase/utils/Utils.h
@@ -0,0 +1,89 @@
+#ifndef UTILS_H
+#define UTILS_H
+
+#include <DeviceManager.h>
+#include <assert.h>
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+// MACROS
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+#ifndef V_RETURN
+#define V_RETURN(x) \
+ { \
+ hr = (x); \
+ if(FAILED(hr)) \
+ { \
+ return hr; \
+ } \
+ }
+#endif
+
+#ifndef V
+#define V(x) \
+ { \
+ HRESULT hr = (x); \
+ _ASSERT(SUCCEEDED(hr)); \
+ }
+#endif
+
+#ifndef SAFE_RELEASE
+#define SAFE_RELEASE(p) \
+ { \
+ if(p) \
+ { \
+ (p)->Release(); \
+ (p) = NULL; \
+ } \
+ }
+#endif
+
+#ifndef SAFE_DELETE
+#define SAFE_DELETE(p) \
+ { \
+ if(p) \
+ { \
+ delete (p); \
+ (p) = NULL; \
+ } \
+ }
+#endif
+
+#define ASSERT_PRINT(cond, format, ...) \
+ if(!(cond)) \
+ { \
+ messagebox_printf("Assertion Failed!", MB_OK | MB_ICONERROR, #cond "\n" format, __VA_ARGS__); \
+ assert(cond); \
+ }
+
+HRESULT messagebox_printf(const char* caption, UINT mb_type, const char* format, ...);
+
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+static const char* strext(const char* str)
+{
+ const char* ext = NULL; // by default no extension found!
+ while (str)
+ {
+ str = strchr(str, '.');
+ if (str)
+ {
+ str++;
+ ext = str;
+ }
+ }
+ return ext;
+}
+
+static inline float lerp(float a, float b, float t) { return a + (b - a) * t; }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/compiler/cmake/SampleBase.cmake b/NvCloth/samples/compiler/cmake/SampleBase.cmake
new file mode 100644
index 0000000..1b00d8d
--- /dev/null
+++ b/NvCloth/samples/compiler/cmake/SampleBase.cmake
@@ -0,0 +1,193 @@
+#
+# Build SampleBase Common
+#
+
+MESSAGE("SampleBase.cmake [begin]")
+
+MESSAGE("CMAKE_MODULE_PATH: " ${CMAKE_MODULE_PATH})
+
+SET(SB_SOURCE_DIR ${PROJECT_SOURCE_DIR}/SampleBase)
+SET(SB_CORE_SOURCE_DIR ${SB_SOURCE_DIR}/core)
+SET(SB_RENDERER_SOURCE_DIR ${SB_SOURCE_DIR}/renderer)
+SET(SB_SCENE_SOURCE_DIR ${SB_SOURCE_DIR}/scene)
+SET(SB_UI_SOURCE_DIR ${SB_SOURCE_DIR}/ui)
+SET(SB_UTILS_SOURCE_DIR ${SB_SOURCE_DIR}/utils)
+
+FIND_PACKAGE(PxShared "1.0.21467209.1" REQUIRED)
+FIND_PACKAGE(DXUT "9.15.2016.1" REQUIRED)
+FIND_PACKAGE(DirectXTex "10.5.2016.2" REQUIRED)
+FIND_PACKAGE(imgui "1.49" REQUIRED)
+#FIND_PACKAGE(tinyObjLoader $ENV{PM_tinyObjLoader_VERSION} REQUIRED)
+#FIND_PACKAGE(tclap $ENV{PM_tclap_VERSION} REQUIRED)
+
+# Include here after the directories are defined so that the platform specific file can use the variables.
+include(${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/SampleBase.cmake)
+
+SET(CORE_FILES
+ ${SB_CORE_SOURCE_DIR}/Application.cpp
+ ${SB_CORE_SOURCE_DIR}/Application.h
+ ${SB_CORE_SOURCE_DIR}/DeviceManager.cpp
+ ${SB_CORE_SOURCE_DIR}/DeviceManager.h
+ ${SB_CORE_SOURCE_DIR}/SampleController.cpp
+ ${SB_CORE_SOURCE_DIR}/SampleController.h
+ ${SB_CORE_SOURCE_DIR}/SampleManager.cpp
+ ${SB_CORE_SOURCE_DIR}/SampleManager.h
+)
+
+SET(RENDERER_FILES
+ ${SB_RENDERER_SOURCE_DIR}/ConvexRenderMesh.cpp
+ ${SB_RENDERER_SOURCE_DIR}/ConvexRenderMesh.h
+ ${SB_RENDERER_SOURCE_DIR}/CustomRenderMesh.cpp
+ ${SB_RENDERER_SOURCE_DIR}/CustomRenderMesh.h
+ ${SB_RENDERER_SOURCE_DIR}/ClothRenderMesh.h
+ ${SB_RENDERER_SOURCE_DIR}/ClothRenderMesh.cpp
+ ${SB_RENDERER_SOURCE_DIR}/DebugRenderBuffer.h
+ ${SB_RENDERER_SOURCE_DIR}/Mesh.cpp
+ ${SB_RENDERER_SOURCE_DIR}/Mesh.h
+ ${SB_RENDERER_SOURCE_DIR}/PrimitiveRenderMesh.cpp
+ ${SB_RENDERER_SOURCE_DIR}/PrimitiveRenderMesh.h
+ ${SB_RENDERER_SOURCE_DIR}/PxPhysXCommonConfig.h
+ ${SB_RENDERER_SOURCE_DIR}/PxRenderBuffer.h
+ ${SB_RENDERER_SOURCE_DIR}/Renderable.cpp
+ ${SB_RENDERER_SOURCE_DIR}/Renderable.h
+ ${SB_RENDERER_SOURCE_DIR}/Renderer.cpp
+ ${SB_RENDERER_SOURCE_DIR}/Renderer.h
+ ${SB_RENDERER_SOURCE_DIR}/RendererHBAO.cpp
+ ${SB_RENDERER_SOURCE_DIR}/RendererHBAO.h
+ ${SB_RENDERER_SOURCE_DIR}/RendererShadow.cpp
+ ${SB_RENDERER_SOURCE_DIR}/RendererShadow.h
+ ${SB_RENDERER_SOURCE_DIR}/RenderMaterial.cpp
+ ${SB_RENDERER_SOURCE_DIR}/RenderMaterial.h
+ ${SB_RENDERER_SOURCE_DIR}/RenderUtils.h
+ ${SB_RENDERER_SOURCE_DIR}/ResourceManager.cpp
+ ${SB_RENDERER_SOURCE_DIR}/ResourceManager.h
+ ${SB_RENDERER_SOURCE_DIR}/ShaderUtils.h
+ ${SB_RENDERER_SOURCE_DIR}/SkinnedRenderMesh.cpp
+ ${SB_RENDERER_SOURCE_DIR}/SkinnedRenderMesh.h
+)
+
+SET(SCENE_FILES
+ ${SB_SCENE_SOURCE_DIR}/SceneController.cpp
+ ${SB_SCENE_SOURCE_DIR}/SceneController.h
+ ${SB_SCENE_SOURCE_DIR}/Scene.cpp
+ ${SB_SCENE_SOURCE_DIR}/Scene.h
+)
+
+SET(SCENES_FILES
+ ${SB_SCENE_SOURCE_DIR}/scenes/SimpleScene.h
+ ${SB_SCENE_SOURCE_DIR}/scenes/SimpleScene.cpp
+ ${SB_SCENE_SOURCE_DIR}/scenes/WindScene.h
+ ${SB_SCENE_SOURCE_DIR}/scenes/WindScene.cpp
+ ${SB_SCENE_SOURCE_DIR}/scenes/TetherScene.h
+ ${SB_SCENE_SOURCE_DIR}/scenes/TetherScene.cpp
+ ${SB_SCENE_SOURCE_DIR}/scenes/FrictionScene.h
+ ${SB_SCENE_SOURCE_DIR}/scenes/FrictionScene.cpp
+ ${SB_SCENE_SOURCE_DIR}/scenes/FreeFallScene.h
+ ${SB_SCENE_SOURCE_DIR}/scenes/FreeFallScene.cpp
+)
+
+SET(UI_FILES
+ ${SB_UI_SOURCE_DIR}/CommonUIController.cpp
+ ${SB_UI_SOURCE_DIR}/CommonUIController.h
+ ${SB_UI_SOURCE_DIR}/imgui_impl_dx11.cpp
+ ${SB_UI_SOURCE_DIR}/imgui_impl_dx11.h
+)
+
+SET(UTIL_FILES
+ ${SB_UTILS_SOURCE_DIR}/SampleProfiler.cpp
+ ${SB_UTILS_SOURCE_DIR}/SampleProfiler.h
+ ${SB_UTILS_SOURCE_DIR}/SampleTime.h
+ ${SB_UTILS_SOURCE_DIR}/UIHelpers.h
+ ${SB_UTILS_SOURCE_DIR}/Utils.cpp
+ ${SB_UTILS_SOURCE_DIR}/Utils.h
+ ${SB_UTILS_SOURCE_DIR}/ClothMeshGenerator.cpp
+ ${SB_UTILS_SOURCE_DIR}/ClothMeshGenerator.h
+ ${SB_UTILS_SOURCE_DIR}/CallbackImplementations.cpp
+ ${SB_UTILS_SOURCE_DIR}/CallbackImplementations.h
+ ${SB_UTILS_SOURCE_DIR}/JobManager.cpp
+ ${SB_UTILS_SOURCE_DIR}/JobManager.h
+)
+
+SET(ROOT_FILES
+ ${SB_SOURCE_DIR}/Main.cpp
+ ${SB_SOURCE_DIR}/Sample.h
+)
+
+ADD_EXECUTABLE(SampleBase
+ ${CORE_FILES}
+ ${RENDERER_FILES}
+ ${SCENE_FILES}
+ ${SCENES_FILES}
+
+ ${UI_FILES}
+ ${UTIL_FILES}
+ ${ROOT_FILES}
+
+
+ ${IMGUI_SOURCE_FILES}
+)
+
+SOURCE_GROUP("Source" FILES ${ROOT_FILES})
+
+SOURCE_GROUP("Source\\core" FILES ${CORE_FILES})
+SOURCE_GROUP("Source\\imgui" FILES ${IMGUI_SOURCE_FILES})
+SOURCE_GROUP("Source\\renderer" FILES ${RENDERER_FILES})
+SOURCE_GROUP("Source\\scene" FILES ${SCENE_FILES})
+SOURCE_GROUP("Source\\scene\\scenes" FILES ${SCENES_FILES})
+SOURCE_GROUP("Source\\ui" FILES ${UI_FILES})
+SOURCE_GROUP("Source\\utils" FILES ${UTIL_FILES})
+
+# Target specific compile options
+
+TARGET_INCLUDE_DIRECTORIES(SampleBase
+ PRIVATE ${SAMPLEBASE_PLATFORM_INCLUDES}
+
+ PRIVATE ${DIRECTXTEX_INCLUDE_DIRS}
+ PRIVATE ${DXUT_INCLUDE_DIRS}
+
+ PRIVATE ${NVCLOTH_ROOT_DIR}/samples/external/shadow_lib
+ PRIVATE ${NVCLOTH_ROOT_DIR}/samples/external/hbao
+
+ PRIVATE ${IMGUI_INCLUDE_DIRS}
+
+ PRIVATE ${SB_SOURCE_DIR}
+ PRIVATE ${SB_SOURCE_DIR}/core
+ PRIVATE ${SB_SOURCE_DIR}/renderer
+ PRIVATE ${SB_SOURCE_DIR}/scene
+ PRIVATE ${SB_SOURCE_DIR}/ui
+ PRIVATE ${SB_SOURCE_DIR}/utils
+
+ PRIVATE ${PXSHARED_ROOT_DIR}/include/foundation
+ PRIVATE ${PXSHARED_ROOT_DIR}/include
+ PRIVATE ${PXSHARED_ROOT_DIR}/src/foundation/include
+
+ PRIVATE ${NVCLOTH_ROOT_DIR}/include
+ PRIVATE ${NVCLOTH_ROOT_DIR}/extensions/include
+)
+
+TARGET_COMPILE_DEFINITIONS(SampleBase
+ PRIVATE ${SAMPLEBASE_COMPILE_DEFS}
+)
+
+SET_TARGET_PROPERTIES(SampleBase PROPERTIES
+ COMPILE_PDB_NAME_DEBUG "SampleBase${CMAKE_DEBUG_POSTFIX}"
+ COMPILE_PDB_NAME_CHECKED "SampleBase${CMAKE_CHECKED_POSTFIX}"
+ COMPILE_PDB_NAME_PROFILE "SampleBase${CMAKE_PROFILE_POSTFIX}"
+ COMPILE_PDB_NAME_RELEASE "SampleBase${CMAKE_RELEASE_POSTFIX}"
+)
+
+TARGET_COMPILE_OPTIONS(SampleBase PRIVATE /wd4005 /wd4244)
+
+# Do final direct sets after the target has been defined
+TARGET_LINK_LIBRARIES(SampleBase
+ PUBLIC d3dcompiler.lib d3d11.lib dxgi.lib comctl32.lib
+ PUBLIC ${HBAO_LIB} ${SHADOW_LIB} ${DXUT_LIBRARIES} ${DIRECTXTEX_LIBRARIES})
+
+TARGET_LINK_LIBRARIES(SampleBase PUBLIC PxFoundation)
+TARGET_LINK_LIBRARIES(SampleBase PUBLIC NvCloth)
+TARGET_LINK_LIBRARIES(SampleBase PUBLIC ${CUDA_CUDA_LIBRARY})
+
+SET_TARGET_PROPERTIES(SampleBase PROPERTIES LINK_FLAGS ${SAMPLEBASE_LINK_FLAGS})
+
+include(${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/SampleBase-AT.cmake OPTIONAL)
+MESSAGE("SampleBase.cmake [end]") \ No newline at end of file
diff --git a/NvCloth/samples/compiler/cmake/windows/CMakeLists.txt b/NvCloth/samples/compiler/cmake/windows/CMakeLists.txt
new file mode 100644
index 0000000..a222309
--- /dev/null
+++ b/NvCloth/samples/compiler/cmake/windows/CMakeLists.txt
@@ -0,0 +1,82 @@
+#Platform specific compile flags and project includes
+
+SET(GW_DEPS_ROOT $ENV{GW_DEPS_ROOT})
+
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}; $ENV{GW_DEPS_ROOT}/sw/physx/tools/CMakeModules)
+
+IF(EXISTS $ENV{GW_DEPS_ROOT}/Externals/CMakeModules)
+ SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}; $ENV{GW_DEPS_ROOT}/Externals/CMakeModules)
+ENDIF()
+
+
+IF(EXISTS $ENV{GW_DEPS_ROOT}/Externals/CMakeModules)
+ SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}; $ENV{GW_DEPS_ROOT}/Externals/CMakeModules)
+ENDIF()
+
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}; "${CMAKE_CURRENT_SOURCE_DIR}/..")
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}; "${CMAKE_CURRENT_SOURCE_DIR}/external/CMakeModules")
+MESSAGE("CMAKE_MODULE_PATH: " ${CMAKE_MODULE_PATH})
+
+#NOTE: Warnings lowered on the sample projects as it's got a lot of warnings. Defines below hide more.
+SET(CMAKE_CXX_FLAGS "/GR- /GF /MP /Gy /EHsc /d2Zi+ /errorReport:prompt /fp:fast /Gd /Gm- /GS- /nologo /W3 /WX /Zc:forScope /Zc:inline /Zc:wchar_t /Zi")
+
+# Are we using the static or dynamic RT library? Whatever we use, it needs to be the same in any dependencies
+# we pull in or we're potentially having mismatch issues.
+IF(STATIC_WINCRT)
+ SET(WINCRT_NDEBUG "/MT")
+ SET(WINCRT_DEBUG "/MTd")
+ELSE()
+ SET(WINCRT_NDEBUG "/MD")
+ SET(WINCRT_DEBUG "/MDd")
+ENDIF()
+
+SET(CMAKE_CXX_FLAGS_DEBUG "/Od /RTCsu ${WINCRT_DEBUG}")
+SET(CMAKE_CXX_FLAGS_CHECKED "/Ox ${WINCRT_NDEBUG}")
+SET(CMAKE_CXX_FLAGS_PROFILE "/Ox ${WINCRT_NDEBUG}")
+SET(CMAKE_CXX_FLAGS_RELEASE "/Ox ${WINCRT_NDEBUG}")
+
+# Build PDBs for all configurations
+SET(CMAKE_SHARED_LINKER_FLAGS "/DEBUG")
+
+IF(CMAKE_CL_64)
+ ADD_DEFINITIONS(-DWIN64)
+ENDIF(CMAKE_CL_64)
+
+SET(SAMPLES_SLN_COMPILE_DEFS _UNICODE;UNICODE;WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH;_ALLOW_RUNTIME_LIBRARY_MISMATCH;__GFSDK_DX11__;)
+#NvBlastExt doesn't have the _CONSOLE flag
+
+SET(SAMPLES_SLN_DEBUG_COMPILE_DEFS _DEBUG;NV_DEBUG=1;)
+SET(SAMPLES_SLN_CHECKED_COMPILE_DEFS NDEBUG;NV_CHECKED=1;)
+SET(SAMPLES_SLN_PROFILE_COMPILE_DEFS NDEBUG;NV_PROFILE=1;)
+SET(SAMPLES_SLN_RELEASE_COMPILE_DEFS NDEBUG;)
+
+IF(CMAKE_CL_64)
+ SET(LIBPATH_SUFFIX "x64")
+ELSE(CMAKE_CL_64)
+ SET(LIBPATH_SUFFIX "x86")
+ENDIF(CMAKE_CL_64)
+
+SET(CMAKE_DEBUG_POSTFIX "${CMAKE_DEBUG_POSTFIX}_${LIBPATH_SUFFIX}")
+SET(CMAKE_PROFILE_POSTFIX "${CMAKE_PROFILE_POSTFIX}_${LIBPATH_SUFFIX}")
+SET(CMAKE_CHECKED_POSTFIX "${CMAKE_CHECKED_POSTFIX}_${LIBPATH_SUFFIX}")
+SET(CMAKE_RELEASE_POSTFIX "${CMAKE_RELEASE_POSTFIX}_${LIBPATH_SUFFIX}")
+
+SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}; "${CMAKE_CURRENT_SOURCE_DIR}/../../../..")
+
+SET(PX_SELECT_COMPONENTS PxFoundation)
+FIND_PACKAGE(PxShared REQUIRED)
+FIND_PACKAGE(NvCloth REQUIRED)
+
+# Include the PxShared-exports.cmake file that PxShared created. There's other ways to do this, but there's a bunch of issues with it in a CI environment
+# such as - we don't want to be installing any built artifacts on this server, etc. So for now we hack it.
+
+# Add PxShared as a dependency so that we can use project references
+#ADD_SUBDIRECTORY(${PXSHARED_ROOT_DIR}/src/compiler/cmake/windows "${CMAKE_CURRENT_BINARY_DIR}/pxshared_bin")
+#MESSAGE("NVCLOTH_ROOT_DIR = ${NVCLOTH_ROOT_DIR}")
+ADD_SUBDIRECTORY(${NVCLOTH_ROOT_DIR}/compiler/cmake/windows "${CMAKE_CURRENT_BINARY_DIR}/NvCloth_bin")
+
+
+# Include all of the projects
+INCLUDE(${PROJECT_CMAKE_FILES_DIR}/SampleBase.cmake)
+
+
diff --git a/NvCloth/samples/compiler/cmake/windows/SampleBase-AT.cmake b/NvCloth/samples/compiler/cmake/windows/SampleBase-AT.cmake
new file mode 100644
index 0000000..1b40447
--- /dev/null
+++ b/NvCloth/samples/compiler/cmake/windows/SampleBase-AT.cmake
@@ -0,0 +1,7 @@
+# Copy the dlls from the deps
+
+ADD_CUSTOM_COMMAND(TARGET SampleBase POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ ${SHADOW_DLLS} ${HBAO_DLLS} ${D3DCOMPILER_DLL}
+ ${BL_EXE_OUTPUT_DIR}
+)
diff --git a/NvCloth/samples/compiler/cmake/windows/SampleBase.cmake b/NvCloth/samples/compiler/cmake/windows/SampleBase.cmake
new file mode 100644
index 0000000..5cabf1e
--- /dev/null
+++ b/NvCloth/samples/compiler/cmake/windows/SampleBase.cmake
@@ -0,0 +1,45 @@
+#
+# Build SampleBase Windows
+#
+
+FIND_PACKAGE(CUDA 8 REQUIRED)
+
+SET(SAMPLEBASE_PLATFORM_COMMON_FILES
+)
+
+SET(SAMPLEBASE_PLATFORM_INCLUDES ${CUDA_INCLUDE_DIRS}
+)
+
+SET(SAMPLEBASE_COMPILE_DEFS
+ # Common to all configurations
+ ${SAMPLES_SLN_COMPILE_DEFS}
+
+ $<$<CONFIG:debug>:${SAMPLES_SLN_DEBUG_COMPILE_DEFS}>
+ $<$<CONFIG:checked>:${SAMPLES_SLN_CHECKED_COMPILE_DEFS}>
+ $<$<CONFIG:profile>:${SAMPLES_SLN_PROFILE_COMPILE_DEFS}>
+ $<$<CONFIG:release>:${SAMPLES_SLN_RELEASE_COMPILE_DEFS}>
+)
+
+SET(SAMPLEBASE_LINK_FLAGS "/SUBSYSTEM:WINDOWS")
+
+SET(SAMPLEBASE_ADDITIONAL_DLLS "")
+
+#TODO: Move this to an external dep
+if (CMAKE_CL_64)
+ SET(SHADOW_LIB ${NVCLOTH_ROOT_DIR}/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.lib)
+ SET(SHADOW_DLLS ${NVCLOTH_ROOT_DIR}/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.dll)
+
+ SET(HBAO_LIB ${NVCLOTH_ROOT_DIR}/samples/external/hbao/GFSDK_SSAO_D3D11.win64.lib)
+ SET(HBAO_DLLS ${NVCLOTH_ROOT_DIR}/samples/external/hbao/GFSDK_SSAO_D3D11.win64.dll)
+
+ SET(D3DCOMPILER_DLL "\"$(VC_ExecutablePath_x64_x64)/d3dcompiler_47.dll\"")
+else()
+ SET(SHADOW_LIB ${NVCLOTH_ROOT_DIR}/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.lib)
+ SET(SHADOW_DLLS ${NVCLOTH_ROOT_DIR}/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.dll)
+
+ SET(HBAO_LIB ${NVCLOTH_ROOT_DIR}/samples/external/hbao/GFSDK_SSAO_D3D11.win32.lib)
+ SET(HBAO_DLLS ${NVCLOTH_ROOT_DIR}/samples/external/hbao/GFSDK_SSAO_D3D11.win32.dll)
+
+ SET(D3DCOMPILER_DLL "\"$(VC_ExecutablePath_x86_x86)/d3dcompiler_47.dll\"")
+endif()
+
diff --git a/NvCloth/samples/external/CMakeModules/FindDXUT.cmake b/NvCloth/samples/external/CMakeModules/FindDXUT.cmake
new file mode 100644
index 0000000..34cd759
--- /dev/null
+++ b/NvCloth/samples/external/CMakeModules/FindDXUT.cmake
@@ -0,0 +1,82 @@
+# - Try to find DXUT SDK
+# - Sets DXUT_LIBRARIES - list of the libraries found
+# - Sets DXUT_INCLUDE_DIRS
+
+include(FindPackageHandleStandardArgs)
+
+# Find the includes
+
+# TODO: Do the version stuff properly!
+find_path(DXUTSDK_PATH Core/DXUT.h
+ PATHS ${GW_DEPS_ROOT}/DXUT/${DXUT_FIND_VERSION}
+ ${NVCLOTH_ROOT_DIR}/samples/external/DXUT/${DXUT_FIND_VERSION}
+)
+
+# If the project pulling in this dependency needs the static crt, then append that to the path.
+
+if (STATIC_WINCRT)
+ SET(DXUTSDK_CRT_FOLDER "staticcrt")
+else()
+ SET(DXUTSDK_CRT_FOLDER "dynamiccrt")
+endif()
+
+if (CMAKE_CL_64)
+ SET(DXUTSDK_ARCH_FOLDER "x64")
+else()
+ SET(DXUTSDK_ARCH_FOLDER "Win32")
+endif()
+
+if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 18.0.0.0 AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.0.0)
+ SET(VS_STR "vs2013")
+elseif(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.0.0.0)
+ SET(VS_STR "vs2015")
+else()
+ MESSAGE(FATAL_ERROR "Failed to find compatible FBXSDK - Only supporting VS2013 and VS2015")
+endif()
+
+
+SET(CORE_LIB_PATH ${DXUTSDK_PATH}/Core/Bin/${DXUTSDK_CRT_FOLDER}/${VS_STR}/${DXUTSDK_ARCH_FOLDER}/)
+SET(OPT_LIB_PATH ${DXUTSDK_PATH}/Optional/Bin/${DXUTSDK_CRT_FOLDER}/${VS_STR}/${DXUTSDK_ARCH_FOLDER}/)
+
+find_library(DXUT_LIB
+ NAMES DXUT
+ PATHS ${CORE_LIB_PATH}/Release
+)
+find_library(DXUT_LIB_DEBUG
+ NAMES DXUT
+ PATHS ${CORE_LIB_PATH}/Debug
+)
+
+find_library(DXUTOPT_LIB
+ NAMES DXUTOpt
+ PATHS ${OPT_LIB_PATH}/Release
+)
+
+find_library(DXUTOPT_LIB_DEBUG
+ NAMES DXUTOpt
+ PATHS ${OPT_LIB_PATH}/Debug
+)
+
+MESSAGE("DXUT: ${DXUT_LIB}")
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(DXUTSDK
+ DEFAULT_MSG
+ DXUTSDK_PATH
+
+ DXUT_LIB
+ DXUTOPT_LIB
+
+ DXUT_LIB_DEBUG
+ DXUTOPT_LIB_DEBUG
+)
+
+if (DXUTSDK_FOUND)
+ # NOTE: This include list is way too long and reaches into too many internals.
+ # Also may not be good enough for all users.
+ SET(DXUT_INCLUDE_DIRS
+ ${DXUTSDK_PATH}/Core
+ ${DXUTSDK_PATH}/Optional
+ )
+
+ SET(DXUT_LIBRARIES optimized ${DXUT_LIB} debug ${DXUT_LIB_DEBUG} optimized ${DXUTOPT_LIB} debug ${DXUTOPT_LIB_DEBUG})
+endif()
diff --git a/NvCloth/samples/external/CMakeModules/FindDirectXTex.cmake b/NvCloth/samples/external/CMakeModules/FindDirectXTex.cmake
new file mode 100644
index 0000000..4332a1d
--- /dev/null
+++ b/NvCloth/samples/external/CMakeModules/FindDirectXTex.cmake
@@ -0,0 +1,66 @@
+# - Try to find DirectXTex SDK
+# - Sets DIRECTXTEX_LIBRARIES - list of the libraries found
+# - Sets DIRECTXTEX_INCLUDE_DIRS
+
+include(FindPackageHandleStandardArgs)
+
+# Find the includes
+
+# TODO: Do the version stuff properly!
+find_path(DIRECTXTEXSDK_PATH include/DirectXTex.h
+ PATHS ${GW_DEPS_ROOT}/DirectXTex/${DirectXTex_FIND_VERSION}
+ ${NVCLOTH_ROOT_DIR}/samples/external/DirectXTex/${DirectXTex_FIND_VERSION}
+)
+
+# If the project pulling in this dependency needs the static crt, then append that to the path.
+
+if (STATIC_WINCRT)
+ SET(DIRECTXTEXSDK_CRT_FOLDER "staticcrt")
+else()
+ SET(DIRECTXTEXSDK_CRT_FOLDER "dynamiccrt")
+endif()
+
+if (CMAKE_CL_64)
+ SET(DIRECTXTEXSDK_ARCH_FOLDER "x64")
+else()
+ SET(DIRECTXTEXSDK_ARCH_FOLDER "Win32")
+endif()
+
+if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 18.0.0.0 AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.0.0)
+ SET(VS_STR "vs2013")
+elseif(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.0.0.0)
+ SET(VS_STR "vs2015")
+else()
+ MESSAGE(FATAL_ERROR "Failed to find compatible FBXSDK - Only supporting VS2013 and VS2015")
+endif()
+
+
+SET(LIB_PATH ${DIRECTXTEXSDK_PATH}/bin/${DIRECTXTEXSDK_CRT_FOLDER}/${VS_STR}/${DIRECTXTEXSDK_ARCH_FOLDER}/)
+
+find_library(DIRECTXTEX_LIB
+ NAMES DirectXTex
+ PATHS ${LIB_PATH}/Release
+)
+find_library(DIRECTXTEX_LIB_DEBUG
+ NAMES DirectXTex
+ PATHS ${LIB_PATH}/Debug
+)
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(DIRECTXTEXSDK
+ DEFAULT_MSG
+ DIRECTXTEXSDK_PATH
+
+ DIRECTXTEX_LIB
+
+ DIRECTXTEX_LIB_DEBUG
+)
+
+if (DIRECTXTEXSDK_FOUND)
+ # NOTE: This include list is way too long and reaches into too many internals.
+ # Also may not be good enough for all users.
+ SET(DIRECTXTEX_INCLUDE_DIRS
+ ${DIRECTXTEXSDK_PATH}/include
+ )
+
+ SET(DIRECTXTEX_LIBRARIES optimized ${DIRECTXTEX_LIB} debug ${DIRECTXTEX_LIB_DEBUG})
+endif()
diff --git a/NvCloth/samples/external/CMakeModules/FindPxShared.cmake b/NvCloth/samples/external/CMakeModules/FindPxShared.cmake
new file mode 100644
index 0000000..c094676
--- /dev/null
+++ b/NvCloth/samples/external/CMakeModules/FindPxShared.cmake
@@ -0,0 +1,20 @@
+# - Try to find PxShared
+# Once done this will define
+# PXSHARED_FOUND - System has PxShared
+# PXSHARED_ROOT_DIR - The root of PxShared
+
+# NOTE: We're including a version in this, but the first hint is without one - we should use that!
+FIND_PATH( PXSHARED_ROOT_DIR include/cudamanager/PxGpuCopyDesc.h
+ HINTS
+ ${GW_DEPS_ROOT}/PxShared/${PxShared_FIND_VERSION}
+ ${GW_DEPS_ROOT}/sw/physx/PxShared/1.0/trunk
+
+ )
+
+
+
+
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(PxShared DEFAULT_MSG PXSHARED_ROOT_DIR)
+
+mark_as_advanced(PXSHARED_ROOT_DIR)
diff --git a/NvCloth/samples/external/CMakeModules/Findimgui.cmake b/NvCloth/samples/external/CMakeModules/Findimgui.cmake
new file mode 100644
index 0000000..f75d8fe
--- /dev/null
+++ b/NvCloth/samples/external/CMakeModules/Findimgui.cmake
@@ -0,0 +1,44 @@
+# - Try to find imgui SDK
+# - Sets IMGUI_LIBRARIES - list of the libraries found
+# - Sets IMGUI_SOURCE_FILES - list of files to include in project
+# - Sets IMGUI_INCLUDE_DIRS
+
+
+include(FindPackageHandleStandardArgs)
+
+# Find the includes
+
+# TODO: Do the version stuff properly!
+find_path(IMGUISDK_PATH imgui.h
+ PATHS ${GW_DEPS_ROOT}/imgui/${imgui_FIND_VERSION}
+ ${NVCLOTH_ROOT_DIR}/samples/external/imgui/${imgui_FIND_VERSION}
+)
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(IMGUISDK
+ DEFAULT_MSG
+ IMGUISDK_PATH
+)
+
+if (IMGUISDK_FOUND)
+ # NOTE: This include list is way too long and reaches into too many internals.
+ # Also may not be good enough for all users.
+ SET(IMGUI_INCLUDE_DIRS
+ ${IMGUISDK_PATH}
+ )
+
+ # imgui is added as source to a project that uses it, so put together a list of files here
+ SET(IMGUI_SOURCE_FILES
+ ${IMGUISDK_PATH}/imconfig.h
+ ${IMGUISDK_PATH}/imgui.cpp
+ ${IMGUISDK_PATH}/imgui.h
+ ${IMGUISDK_PATH}/imgui_demo.cpp
+ ${IMGUISDK_PATH}/imgui_draw.cpp
+ ${IMGUISDK_PATH}/imgui_internal.h
+ ${IMGUISDK_PATH}/stb_rect_pack.h
+ ${IMGUISDK_PATH}/stb_textedit.h
+ ${IMGUISDK_PATH}/stb_truetype.h
+ )
+
+
+ SET(IMGUI_LIBRARIES optimized IMGUI_LIB debug IMGUI_LIB_DEBUG optimized DXUTOPT_LIB debug DXUTOPT_LIB_DEBUG)
+endif()
diff --git a/NvCloth/samples/external/CMakeModules/FindnvToolsExt.cmake b/NvCloth/samples/external/CMakeModules/FindnvToolsExt.cmake
new file mode 100644
index 0000000..2ba7cea
--- /dev/null
+++ b/NvCloth/samples/external/CMakeModules/FindnvToolsExt.cmake
@@ -0,0 +1,65 @@
+# - Try to find nvToolsExt
+# Once done this will define
+# NVTOOLSEXT_FOUND - System has nvToolsExt
+# NVTOOLSEXT_INCLUDE_DIRS - The nvToolsExt include directories
+# NVTOOLSEXT_LIB - The lib needed to use nvToolsExt
+# NVTOOLSEXT_DLL - The dll needed to use nvToolsExt
+# NVTOOLSEXT_DEFINITIONS - Compiler switches required for using nvToolsExt
+
+INCLUDE(FindPackageHandleStandardArgs)
+
+#TODO: Proper version support
+FIND_PATH( NVTOOLSEXTSDK_PATH include/nvToolsExt.h
+ PATHS
+ ${GW_DEPS_ROOT}/nvToolsExt/${nvToolsExt_FIND_VERSION}
+ ${GW_DEPS_ROOT}/Externals/nvToolsExt/1
+ ${GW_DEPS_ROOT}/sw/physx/externals/nvToolsExt/1
+ )
+
+MESSAGE("NvToolsExt: " ${NVTOOLSEXTSDK_PATH})
+
+if (CMAKE_CL_64)
+ SET(NVTOOLSEXT_ARCH_FOLDER "x64")
+ SET(NVTOOLSEXT_ARCH_FILE "64")
+else()
+ SET(NVTOOLSEXT_ARCH_FOLDER "Win32")
+ SET(NVTOOLSEXT_ARCH_FILE "32")
+endif()
+
+IF(TARGET_BUILD_PLATFORM STREQUAL "Windows")
+ # NOTE: Doesn't make sense for all platforms - ARM
+ if (CMAKE_CL_64)
+ SET(NVTOOLSEXT_ARCH_FOLDER "x64")
+ SET(NVTOOLSEXT_ARCH_FILE "64")
+ else()
+ SET(NVTOOLSEXT_ARCH_FOLDER "Win32")
+ SET(NVTOOLSEXT_ARCH_FILE "32")
+ endif()
+
+ SET(CMAKE_FIND_LIBRARY_SUFFIXES ".lib" ".dll")
+
+
+ FIND_LIBRARY( NVTOOLSEXT_LIB
+ NAMES nvToolsExt${NVTOOLSEXT_ARCH_FILE}_1
+ PATHS
+ ${NVTOOLSEXTSDK_PATH}/lib/${NVTOOLSEXT_ARCH_FOLDER}
+ )
+
+ find_library( NVTOOLSEXT_DLL
+ NAMES nvToolsExt${NVTOOLSEXT_ARCH_FILE}_1
+ PATHS
+ ${NVTOOLSEXTSDK_PATH}/bin/${NVTOOLSEXT_ARCH_FOLDER}
+ )
+
+
+ SET(NVTOOLSEXT_INCLUDE_DIRS
+ ${NVTOOLSEXTSDK_PATH}/include
+ )
+
+ FIND_PACKAGE_HANDLE_STANDARD_ARGS(nvToolsExt DEFAULT_MSG NVTOOLSEXT_LIB NVTOOLSEXT_DLL NVTOOLSEXT_INCLUDE_DIRS)
+ELSE()
+ # Exclude the libraries for non-windows platforms
+ FIND_PACKAGE_HANDLE_STANDARD_ARGS(nvToolsExt DEFAULT_MSG NVTOOLSEXT_INCLUDE_DIRS)
+ENDIF()
+
+mark_as_advanced(NVTOOLSEXT_INCLUDE_DIRS NVTOOLSEXT_DLL NVTOOLSEXT_LIB) \ No newline at end of file
diff --git a/NvCloth/samples/external/CMakeModules/SetOutputPaths.cmake b/NvCloth/samples/external/CMakeModules/SetOutputPaths.cmake
new file mode 100644
index 0000000..a1be9f4
--- /dev/null
+++ b/NvCloth/samples/external/CMakeModules/SetOutputPaths.cmake
@@ -0,0 +1,95 @@
+FUNCTION(SetOutputPaths
+ OUTPUT_EXE_DIR
+ OUTPUT_DLL_DIR
+ OUTPUT_LIB_DIR)
+
+ SET(EXE_DIR ${OUTPUT_EXE_DIR})
+ SET(DLL_DIR ${OUTPUT_DLL_DIR})
+ SET(LIB_DIR ${OUTPUT_LIB_DIR})
+
+ # Override the default output directories for all configurations.
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_CHECKED ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_CHECKED ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_CHECKED ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_PROFILE ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_PROFILE ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_PROFILE ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ${LIB_DIR})
+
+ENDFUNCTION(SetOutputPaths)
+
+FUNCTION(SetExeOutputPath OUTPUT_EXE_DIR)
+
+ SET(EXE_DIR ${OUTPUT_EXE_DIR})
+
+ # Override the default output directories for all configurations.
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_CHECKED ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_PROFILE ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${EXE_DIR} PARENT_SCOPE)
+
+ENDFUNCTION(SetExeOutputPath)
+
+FUNCTION(SetDllOutputPath OUTPUT_DLL_DIR)
+
+ SET(DLL_DIR ${OUTPUT_DLL_DIR})
+
+ # Override the default output directories for all configurations.
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG ${DLL_DIR}/${ARGV1} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_PROFILE ${DLL_DIR}/${ARGV2} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_CHECKED ${DLL_DIR}/${ARGV3} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${DLL_DIR}/${ARGV4} PARENT_SCOPE)
+
+ENDFUNCTION(SetDllOutputPath)
+
+FUNCTION(SetLibOutputPath OUTPUT_LIB_DIR)
+
+ SET(LIB_DIR ${OUTPUT_LIB_DIR})
+
+ # Override the default output directories for all configurations.
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${LIB_DIR}/${ARGV1} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_PROFILE ${LIB_DIR}/${ARGV2} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_CHECKED ${LIB_DIR}/${ARGV3} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${LIB_DIR}/${ARGV4} PARENT_SCOPE)
+
+ SET(CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ${LIB_DIR})
+
+ENDFUNCTION(SetLibOutputPath)
+
+FUNCTION(SetSingleOutputPath OUTPUT_ALL_DIR)
+
+ SET(EXE_DIR ${OUTPUT_ALL_DIR})
+ SET(DLL_DIR ${OUTPUT_ALL_DIR})
+ SET(LIB_DIR ${OUTPUT_ALL_DIR})
+
+ # Override the default output directories for all configurations.
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_CHECKED ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_CHECKED ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_CHECKED ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_PROFILE ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_PROFILE ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_PROFILE ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${EXE_DIR} PARENT_SCOPE)
+ SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${DLL_DIR} PARENT_SCOPE)
+ SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${LIB_DIR} PARENT_SCOPE)
+
+ SET(CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ${LIB_DIR})
+
+ENDFUNCTION(SetSingleOutputPath)
+
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/DXUT.lib
new file mode 100644
index 0000000..4b07cc7
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/dxut.pdb
new file mode 100644
index 0000000..3706a90
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Debug/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/DXUT.lib
new file mode 100644
index 0000000..3f08396
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/dxut.pdb
new file mode 100644
index 0000000..d518e74
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/Win32/Release/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/DXUT.lib
new file mode 100644
index 0000000..fa3ac34
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/dxut.pdb
new file mode 100644
index 0000000..1f6d382
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Debug/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/DXUT.lib
new file mode 100644
index 0000000..b256786
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/dxut.pdb
new file mode 100644
index 0000000..cef2b95
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2013/x64/Release/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.lib
new file mode 100644
index 0000000..df8d5de
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.pdb
new file mode 100644
index 0000000..23fc237
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Debug/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.lib
new file mode 100644
index 0000000..8a0fa77
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.pdb
new file mode 100644
index 0000000..a573d76
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/Win32/Release/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.lib
new file mode 100644
index 0000000..61396f7
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.pdb
new file mode 100644
index 0000000..0a3ab9d
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Debug/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.lib
new file mode 100644
index 0000000..ae3bbdc
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.pdb
new file mode 100644
index 0000000..b1fba2f
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/dynamiccrt/vs2015/x64/Release/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/DXUT.lib
new file mode 100644
index 0000000..78ac45e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/dxut.pdb
new file mode 100644
index 0000000..f6ab878
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Debug/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/DXUT.lib
new file mode 100644
index 0000000..c056849
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/dxut.pdb
new file mode 100644
index 0000000..9df7c09
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/Win32/Release/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/DXUT.lib
new file mode 100644
index 0000000..8d6b78e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/dxut.pdb
new file mode 100644
index 0000000..124dca8
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Debug/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/DXUT.lib
new file mode 100644
index 0000000..a6d75b1
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/dxut.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/dxut.pdb
new file mode 100644
index 0000000..64a0479
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2013/x64/Release/dxut.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.lib
new file mode 100644
index 0000000..29d1418
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.pdb
new file mode 100644
index 0000000..ce70c1e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Debug/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.lib
new file mode 100644
index 0000000..6e1b231
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.pdb
new file mode 100644
index 0000000..d273b05
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/Win32/Release/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.lib
new file mode 100644
index 0000000..a02da67
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.pdb
new file mode 100644
index 0000000..0e1b4c5
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Debug/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.lib
new file mode 100644
index 0000000..50bc741
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.pdb
new file mode 100644
index 0000000..5a620f6
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/Bin/staticcrt/vs2015/x64/Release/DXUT.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DDSTextureLoader.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DDSTextureLoader.h
new file mode 100644
index 0000000..122df9f
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DDSTextureLoader.h
@@ -0,0 +1,133 @@
+//--------------------------------------------------------------------------------------
+// File: DDSTextureLoader.h
+//
+// Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
+//
+// Note these functions are useful as a light-weight runtime loader for DDS files. For
+// a full-featured DDS file reader, writer, and texture processing pipeline see
+// the 'Texconv' sample and the 'DirectXTex' library.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+// http://go.microsoft.com/fwlink/?LinkId=248929
+//--------------------------------------------------------------------------------------
+
+#pragma once
+
+#include <d3d11_1.h>
+#include <stdint.h>
+
+
+namespace DirectX
+{
+ enum DDS_ALPHA_MODE
+ {
+ DDS_ALPHA_MODE_UNKNOWN = 0,
+ DDS_ALPHA_MODE_STRAIGHT = 1,
+ DDS_ALPHA_MODE_PREMULTIPLIED = 2,
+ DDS_ALPHA_MODE_OPAQUE = 3,
+ DDS_ALPHA_MODE_CUSTOM = 4,
+ };
+
+ // Standard version
+ HRESULT CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice,
+ _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
+ _In_ size_t ddsDataSize,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ HRESULT CreateDDSTextureFromFile( _In_ ID3D11Device* d3dDevice,
+ _In_z_ const wchar_t* szFileName,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ // Standard version with optional auto-gen mipmap support
+ HRESULT CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
+ _In_ size_t ddsDataSize,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ HRESULT CreateDDSTextureFromFile( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_z_ const wchar_t* szFileName,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ // Extended version
+ HRESULT CreateDDSTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
+ _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
+ _In_ size_t ddsDataSize,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ HRESULT CreateDDSTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
+ _In_z_ const wchar_t* szFileName,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ // Extended version with optional auto-gen mipmap support
+ HRESULT CreateDDSTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
+ _In_ size_t ddsDataSize,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+
+ HRESULT CreateDDSTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_z_ const wchar_t* szFileName,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Outptr_opt_ ID3D11Resource** texture,
+ _Outptr_opt_ ID3D11ShaderResourceView** textureView,
+ _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
+ );
+} \ No newline at end of file
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUT.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUT.h
new file mode 100644
index 0000000..fc6247e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUT.h
@@ -0,0 +1,341 @@
+//--------------------------------------------------------------------------------------
+// File: DXUT.h
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+#ifndef UNICODE
+#error "DXUT requires a Unicode build."
+#endif
+
+#ifndef STRICT
+#define STRICT
+#endif
+
+// If app hasn't choosen, set to work with Windows Vista and beyond
+#ifndef WINVER
+#define WINVER 0x0600
+#endif
+#ifndef _WIN32_WINDOWS
+#define _WIN32_WINDOWS 0x0600
+#endif
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0600
+#endif
+
+#if (_WIN32_WINNT >= 0x0A00) && !defined(USE_DIRECT3D11_3)
+#define USE_DIRECT3D11_3
+#endif
+
+#if (_WIN32_WINNT >= 0x0603) && !defined(USE_DIRECT3D11_2)
+#define USE_DIRECT3D11_2
+#endif
+
+#if defined(USE_DIRECT3D11_3) && !defined(USE_DIRECT3D11_2)
+#define USE_DIRECT3D11_2
+#endif
+
+// #define DXUT_AUTOLIB to automatically include the libs needed for DXUT
+#ifdef DXUT_AUTOLIB
+#pragma comment( lib, "comctl32.lib" )
+#pragma comment( lib, "dxguid.lib" )
+#pragma comment( lib, "d3dcompiler.lib" )
+#pragma comment( lib, "ole32.lib" )
+#pragma comment( lib, "uuid.lib" )
+#endif
+
+#pragma warning( disable : 4481 )
+
+// Standard Windows includes
+#if !defined(NOMINMAX)
+#define NOMINMAX
+#endif
+
+#include <windows.h>
+#include <initguid.h>
+#include <assert.h>
+#include <commctrl.h> // for InitCommonControls()
+#include <shellapi.h> // for ExtractIcon()
+#include <new.h> // for placement new
+#include <shlobj.h>
+#include <math.h>
+#include <limits.h>
+#include <stdio.h>
+
+// CRT's memory leak detection
+#if defined(DEBUG) || defined(_DEBUG)
+#include <crtdbg.h>
+#endif
+
+// Direct3D11 includes
+#include <d3dcommon.h>
+#include <dxgi.h>
+#include <d3d11_1.h>
+#include <d3dcompiler.h>
+
+#ifdef USE_DIRECT3D11_2
+#include <d3d11_2.h>
+#endif
+
+#ifdef USE_DIRECT3D11_3
+#include <d3d11_3.h>
+#endif
+
+// DirectXMath includes
+#include <DirectXMath.h>
+#include <DirectXColors.h>
+
+// WIC includes
+#include <wincodec.h>
+
+// XInput includes
+#include <xinput.h>
+
+// HRESULT translation for Direct3D and other APIs
+#include "dxerr.h"
+
+// STL includes
+#include <algorithm>
+#include <memory>
+#include <vector>
+
+#if defined(DEBUG) || defined(_DEBUG)
+#ifndef V
+#define V(x) { hr = (x); if( FAILED(hr) ) { DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } }
+#endif
+#ifndef V_RETURN
+#define V_RETURN(x) { hr = (x); if( FAILED(hr) ) { return DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } }
+#endif
+#else
+#ifndef V
+#define V(x) { hr = (x); }
+#endif
+#ifndef V_RETURN
+#define V_RETURN(x) { hr = (x); if( FAILED(hr) ) { return hr; } }
+#endif
+#endif
+
+#ifndef SAFE_DELETE
+#define SAFE_DELETE(p) { if (p) { delete (p); (p) = nullptr; } }
+#endif
+#ifndef SAFE_DELETE_ARRAY
+#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = nullptr; } }
+#endif
+#ifndef SAFE_RELEASE
+#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = nullptr; } }
+#endif
+
+#ifndef D3DCOLOR_ARGB
+#define D3DCOLOR_ARGB(a,r,g,b) \
+ ((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))
+#endif
+
+#define DXUT_VERSION 1114
+
+//--------------------------------------------------------------------------------------
+// Structs
+//--------------------------------------------------------------------------------------
+struct DXUTD3D11DeviceSettings
+{
+ UINT AdapterOrdinal;
+ D3D_DRIVER_TYPE DriverType;
+ UINT Output;
+ DXGI_SWAP_CHAIN_DESC sd;
+ UINT32 CreateFlags;
+ UINT32 SyncInterval;
+ DWORD PresentFlags;
+ bool AutoCreateDepthStencil; // DXUT will create the depth stencil resource and view if true
+ DXGI_FORMAT AutoDepthStencilFormat;
+ D3D_FEATURE_LEVEL DeviceFeatureLevel;
+};
+
+struct DXUTDeviceSettings
+{
+ D3D_FEATURE_LEVEL MinimumFeatureLevel;
+ DXUTD3D11DeviceSettings d3d11;
+};
+
+
+//--------------------------------------------------------------------------------------
+// Error codes
+//--------------------------------------------------------------------------------------
+#define DXUTERR_NODIRECT3D MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0901)
+#define DXUTERR_NOCOMPATIBLEDEVICES MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0902)
+#define DXUTERR_MEDIANOTFOUND MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0903)
+#define DXUTERR_NONZEROREFCOUNT MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0904)
+#define DXUTERR_CREATINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0905)
+#define DXUTERR_RESETTINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0906)
+#define DXUTERR_CREATINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0907)
+#define DXUTERR_RESETTINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0908)
+#define DXUTERR_DEVICEREMOVED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090A)
+
+
+//--------------------------------------------------------------------------------------
+// Callback registration
+//--------------------------------------------------------------------------------------
+
+// General callbacks
+typedef void (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)( _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext );
+typedef void (CALLBACK *LPDXUTCALLBACKKEYBOARD)( _In_ UINT nChar, _In_ bool bKeyDown, _In_ bool bAltDown, _In_opt_ void* pUserContext );
+typedef void (CALLBACK *LPDXUTCALLBACKMOUSE)( _In_ bool bLeftButtonDown, _In_ bool bRightButtonDown, _In_ bool bMiddleButtonDown,
+ _In_ bool bSideButton1Down, _In_ bool bSideButton2Down, _In_ int nMouseWheelDelta,
+ _In_ int xPos, _In_ int yPos, _In_opt_ void* pUserContext );
+typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam,
+ _Out_ bool* pbNoFurtherProcessing, _In_opt_ void* pUserContext );
+typedef void (CALLBACK *LPDXUTCALLBACKTIMER)( _In_ UINT idEvent, _In_opt_ void* pUserContext );
+typedef bool (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)( _In_ DXUTDeviceSettings* pDeviceSettings, _In_opt_ void* pUserContext );
+typedef bool (CALLBACK *LPDXUTCALLBACKDEVICEREMOVED)( _In_opt_ void* pUserContext );
+
+class CD3D11EnumAdapterInfo;
+class CD3D11EnumDeviceInfo;
+
+// Direct3D 11 callbacks
+typedef bool (CALLBACK *LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE)( _In_ const CD3D11EnumAdapterInfo *AdapterInfo, _In_ UINT Output, _In_ const CD3D11EnumDeviceInfo *DeviceInfo,
+ _In_ DXGI_FORMAT BackBufferFormat, _In_ bool bWindowed, _In_opt_ void* pUserContext );
+typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11DEVICECREATED)( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext );
+typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRESIZED)( _In_ ID3D11Device* pd3dDevice, _In_ IDXGISwapChain *pSwapChain, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext );
+typedef void (CALLBACK *LPDXUTCALLBACKD3D11FRAMERENDER)( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext, _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext );
+typedef void (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRELEASING)( _In_opt_ void* pUserContext );
+typedef void (CALLBACK *LPDXUTCALLBACKD3D11DEVICEDESTROYED)( _In_opt_ void* pUserContext );
+
+// General callbacks
+void WINAPI DXUTSetCallbackFrameMove( _In_ LPDXUTCALLBACKFRAMEMOVE pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackKeyboard( _In_ LPDXUTCALLBACKKEYBOARD pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackMouse( _In_ LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove = false, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackMsgProc( _In_ LPDXUTCALLBACKMSGPROC pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackDeviceChanging( _In_ LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackDeviceRemoved( _In_ LPDXUTCALLBACKDEVICEREMOVED pCallback, _In_opt_ void* pUserContext = nullptr );
+
+// Direct3D 11 callbacks
+void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackD3D11DeviceCreated( _In_ LPDXUTCALLBACKD3D11DEVICECREATED pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackD3D11SwapChainResized( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackD3D11FrameRender( _In_ LPDXUTCALLBACKD3D11FRAMERENDER pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, _In_opt_ void* pUserContext = nullptr );
+void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( _In_ LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, _In_opt_ void* pUserContext = nullptr );
+
+
+//--------------------------------------------------------------------------------------
+// Initialization
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTInit( _In_ bool bParseCommandLine = true,
+ _In_ bool bShowMsgBoxOnError = true,
+ _In_opt_ WCHAR* strExtraCommandLineParams = nullptr,
+ _In_ bool bThreadSafeDXUT = false );
+
+// Choose either DXUTCreateWindow or DXUTSetWindow. If using DXUTSetWindow, consider using DXUTStaticWndProc
+HRESULT WINAPI DXUTCreateWindow( _In_z_ const WCHAR* strWindowTitle = L"Direct3D Window",
+ _In_opt_ HINSTANCE hInstance = nullptr, _In_opt_ HICON hIcon = nullptr, _In_opt_ HMENU hMenu = nullptr,
+ _In_ int x = CW_USEDEFAULT, _In_ int y = CW_USEDEFAULT );
+HRESULT WINAPI DXUTSetWindow( _In_ HWND hWndFocus, _In_ HWND hWndDeviceFullScreen, _In_ HWND hWndDeviceWindowed, _In_ bool bHandleMessages = true );
+LRESULT CALLBACK DXUTStaticWndProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+// Choose either DXUTCreateDevice or DXUTCreateD3DDeviceFromSettings
+
+HRESULT WINAPI DXUTCreateDevice(_In_ D3D_FEATURE_LEVEL reqFL, _In_ bool bWindowed= true, _In_ int nSuggestedWidth =0,_In_ int nSuggestedHeight =0 );
+HRESULT WINAPI DXUTCreateDeviceFromSettings( _In_ DXUTDeviceSettings* pDeviceSettings, _In_ bool bClipWindowToSingleAdapter = true );
+
+// Choose either DXUTMainLoop or implement your own main loop
+HRESULT WINAPI DXUTMainLoop( _In_opt_ HACCEL hAccel = nullptr );
+
+// If not using DXUTMainLoop consider using DXUTRender3DEnvironment
+void WINAPI DXUTRender3DEnvironment();
+
+
+//--------------------------------------------------------------------------------------
+// Common Tasks
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTToggleFullScreen();
+HRESULT WINAPI DXUTToggleREF();
+HRESULT WINAPI DXUTToggleWARP();
+void WINAPI DXUTPause( _In_ bool bPauseTime, _In_ bool bPauseRendering );
+void WINAPI DXUTSetConstantFrameTime( _In_ bool bConstantFrameTime, _In_ float fTimePerFrame = 0.0333f );
+void WINAPI DXUTSetCursorSettings( _In_ bool bShowCursorWhenFullScreen = false, _In_ bool bClipCursorWhenFullScreen = false );
+void WINAPI DXUTSetHotkeyHandling( _In_ bool bAltEnterToToggleFullscreen = true, _In_ bool bEscapeToQuit = true, _In_ bool bPauseToToggleTimePause = true );
+void WINAPI DXUTSetMultimonSettings( _In_ bool bAutoChangeAdapter = true );
+void WINAPI DXUTSetShortcutKeySettings( _In_ bool bAllowWhenFullscreen = false, _In_ bool bAllowWhenWindowed = true ); // Controls the Windows key, and accessibility shortcut keys
+void WINAPI DXUTSetWindowSettings( _In_ bool bCallDefWindowProc = true );
+HRESULT WINAPI DXUTSetTimer( _In_ LPDXUTCALLBACKTIMER pCallbackTimer, _In_ float fTimeoutInSecs = 1.0f, _Out_opt_ UINT* pnIDEvent = nullptr, _In_opt_ void* pCallbackUserContext = nullptr );
+HRESULT WINAPI DXUTKillTimer( _In_ UINT nIDEvent );
+void WINAPI DXUTResetFrameworkState();
+void WINAPI DXUTShutdown( _In_ int nExitCode = 0 );
+void WINAPI DXUTSetIsInGammaCorrectMode( _In_ bool bGammaCorrect );
+bool WINAPI DXUTGetMSAASwapChainCreated();
+
+
+//--------------------------------------------------------------------------------------
+// State Retrieval
+//--------------------------------------------------------------------------------------
+
+// Direct3D 11.x (These do not addref unlike typical Get* APIs)
+IDXGIFactory1* WINAPI DXUTGetDXGIFactory();
+IDXGISwapChain* WINAPI DXUTGetDXGISwapChain();
+const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc();
+HRESULT WINAPI DXUTSetupD3D11Views( _In_ ID3D11DeviceContext* pd3dDeviceContext ); // Supports immediate or deferred context
+D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel(); // Returns the D3D11 devices current feature level
+ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView();
+ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView();
+
+ID3D11Device* WINAPI DXUTGetD3D11Device();
+ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext();
+
+ID3D11Device1* WINAPI DXUTGetD3D11Device1();
+ID3D11DeviceContext1* WINAPI DXUTGetD3D11DeviceContext1();
+
+#ifdef USE_DIRECT3D11_2
+ID3D11Device2* WINAPI DXUTGetD3D11Device2();
+ID3D11DeviceContext2* WINAPI DXUTGetD3D11DeviceContext2();
+#endif
+
+#ifdef USE_DIRECT3D11_3
+ID3D11Device3* WINAPI DXUTGetD3D11Device3();
+ID3D11DeviceContext3* WINAPI DXUTGetD3D11DeviceContext3();
+#endif
+
+// General
+DXUTDeviceSettings WINAPI DXUTGetDeviceSettings();
+HINSTANCE WINAPI DXUTGetHINSTANCE();
+HWND WINAPI DXUTGetHWND();
+HWND WINAPI DXUTGetHWNDFocus();
+HWND WINAPI DXUTGetHWNDDeviceFullScreen();
+HWND WINAPI DXUTGetHWNDDeviceWindowed();
+RECT WINAPI DXUTGetWindowClientRect();
+LONG WINAPI DXUTGetWindowWidth();
+LONG WINAPI DXUTGetWindowHeight();
+RECT WINAPI DXUTGetWindowClientRectAtModeChange(); // Useful for returning to windowed mode with the same resolution as before toggle to full screen mode
+RECT WINAPI DXUTGetFullsceenClientRectAtModeChange(); // Useful for returning to full screen mode with the same resolution as before toggle to windowed mode
+double WINAPI DXUTGetTime();
+float WINAPI DXUTGetElapsedTime();
+bool WINAPI DXUTIsWindowed();
+bool WINAPI DXUTIsInGammaCorrectMode();
+float WINAPI DXUTGetFPS();
+LPCWSTR WINAPI DXUTGetWindowTitle();
+LPCWSTR WINAPI DXUTGetFrameStats( _In_ bool bIncludeFPS = false );
+LPCWSTR WINAPI DXUTGetDeviceStats();
+
+bool WINAPI DXUTIsVsyncEnabled();
+bool WINAPI DXUTIsRenderingPaused();
+bool WINAPI DXUTIsTimePaused();
+bool WINAPI DXUTIsActive();
+int WINAPI DXUTGetExitCode();
+bool WINAPI DXUTGetShowMsgBoxOnError();
+bool WINAPI DXUTGetAutomation(); // Returns true if -automation parameter is used to launch the app
+bool WINAPI DXUTIsKeyDown( _In_ BYTE vKey ); // Pass a virtual-key code, ex. VK_F1, 'A', VK_RETURN, VK_LSHIFT, etc
+bool WINAPI DXUTWasKeyPressed( _In_ BYTE vKey ); // Like DXUTIsKeyDown() but return true only if the key was just pressed
+bool WINAPI DXUTIsMouseButtonDown( _In_ BYTE vButton ); // Pass a virtual-key code: VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, VK_XBUTTON2
+HRESULT WINAPI DXUTCreateState(); // Optional method to create DXUT's memory. If its not called by the application it will be automatically called when needed
+void WINAPI DXUTDestroyState(); // Optional method to destroy DXUT's memory. If its not called by the application it will be automatically called after the application exits WinMain
+
+//--------------------------------------------------------------------------------------
+// DXUT core layer includes
+//--------------------------------------------------------------------------------------
+#include "DXUTmisc.h"
+#include "DXUTDevice11.h"
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTDevice11.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTDevice11.h
new file mode 100644
index 0000000..1e38a63
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTDevice11.h
@@ -0,0 +1,210 @@
+//--------------------------------------------------------------------------------------
+// File: DXUTDevice11.h
+//
+// Enumerates D3D adapters, devices, modes, etc.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings);
+
+//--------------------------------------------------------------------------------------
+// Functions to get bit depth from formats
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( _In_ UINT AdapterOrdinal, _In_ UINT Output, _Out_ DXGI_MODE_DESC* pModeDesc );
+
+
+
+
+//--------------------------------------------------------------------------------------
+// Optional memory create/destory functions. If not call, these will be called automatically
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTCreateD3D11Enumeration();
+void WINAPI DXUTDestroyD3D11Enumeration();
+
+
+
+
+//--------------------------------------------------------------------------------------
+// Forward declarations
+//--------------------------------------------------------------------------------------
+class CD3D11EnumAdapterInfo;
+class CD3D11EnumDeviceInfo;
+class CD3D11EnumOutputInfo;
+struct CD3D11EnumDeviceSettingsCombo;
+
+
+
+//--------------------------------------------------------------------------------------
+// Enumerates available Direct3D11 adapters, devices, modes, etc.
+//--------------------------------------------------------------------------------------
+class CD3D11Enumeration
+{
+public:
+ // These should be called before Enumerate().
+ //
+ // Use these calls and the IsDeviceAcceptable to control the contents of
+ // the enumeration object, which affects the device selection and the device settings dialog.
+ void SetResolutionMinMax( _In_ UINT nMinWidth, _In_ UINT nMinHeight, _In_ UINT nMaxWidth, _In_ UINT nMaxHeight );
+ void SetRefreshMinMax( _In_ UINT nMin, _In_ UINT nMax );
+ void SetForceFeatureLevel( _In_ D3D_FEATURE_LEVEL forceFL) { m_forceFL = forceFL; }
+ void SetMultisampleQualityMax( _In_ UINT nMax );
+ void ResetPossibleDepthStencilFormats();
+ void SetEnumerateAllAdapterFormats( _In_ bool bEnumerateAllAdapterFormats );
+
+ // Call Enumerate() to enumerate available D3D11 adapters, devices, modes, etc.
+ bool HasEnumerated() { return m_bHasEnumerated; }
+ HRESULT Enumerate( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc,
+ _In_opt_ void* pIsD3D11DeviceAcceptableFuncUserContext );
+
+ // These should be called after Enumerate() is called
+ std::vector<CD3D11EnumAdapterInfo*>* GetAdapterInfoList();
+ CD3D11EnumAdapterInfo* GetAdapterInfo( _In_ UINT AdapterOrdinal ) const;
+ CD3D11EnumDeviceInfo* GetDeviceInfo( _In_ UINT AdapterOrdinal, _In_ D3D_DRIVER_TYPE DeviceType ) const;
+ CD3D11EnumOutputInfo* GetOutputInfo( _In_ UINT AdapterOrdinal, _In_ UINT Output ) const;
+ CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ DXUTD3D11DeviceSettings* pDeviceSettings ) const { return GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->sd.BufferDesc.Format, pDeviceSettings->sd.Windowed ); }
+ CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ UINT AdapterOrdinal, _In_ DXGI_FORMAT BackBufferFormat, _In_ BOOL Windowed ) const;
+ D3D_FEATURE_LEVEL GetWARPFeaturevel() const { return m_warpFL; }
+ D3D_FEATURE_LEVEL GetREFFeaturevel() const { return m_refFL; }
+
+ ~CD3D11Enumeration();
+
+private:
+ friend HRESULT WINAPI DXUTCreateD3D11Enumeration();
+
+ // Use DXUTGetD3D11Enumeration() to access global instance
+ CD3D11Enumeration();
+
+ bool m_bHasEnumerated;
+ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE m_IsD3D11DeviceAcceptableFunc;
+ void* m_pIsD3D11DeviceAcceptableFuncUserContext;
+
+ std::vector<DXGI_FORMAT> m_DepthStencilPossibleList;
+
+ bool m_bEnumerateAllAdapterFormats;
+ D3D_FEATURE_LEVEL m_forceFL;
+ D3D_FEATURE_LEVEL m_warpFL;
+ D3D_FEATURE_LEVEL m_refFL;
+
+ std::vector<CD3D11EnumAdapterInfo*> m_AdapterInfoList;
+
+ HRESULT EnumerateOutputs( _In_ CD3D11EnumAdapterInfo *pAdapterInfo );
+ HRESULT EnumerateDevices( _In_ CD3D11EnumAdapterInfo *pAdapterInfo );
+ HRESULT EnumerateDeviceCombos( _In_ CD3D11EnumAdapterInfo* pAdapterInfo );
+ HRESULT EnumerateDeviceCombosNoAdapter( _In_ CD3D11EnumAdapterInfo* pAdapterInfo );
+
+ HRESULT EnumerateDisplayModes( _In_ CD3D11EnumOutputInfo *pOutputInfo );
+ void BuildMultiSampleQualityList( _In_ DXGI_FORMAT fmt, _In_ CD3D11EnumDeviceSettingsCombo* pDeviceCombo );
+ void ClearAdapterInfoList();
+};
+
+CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration(_In_ bool bForceEnumerate = false, _In_ bool EnumerateAllAdapterFormats = true, _In_ D3D_FEATURE_LEVEL forceFL = ((D3D_FEATURE_LEVEL )0) );
+
+
+#define DXGI_MAX_DEVICE_IDENTIFIER_STRING 128
+
+//--------------------------------------------------------------------------------------
+// A class describing an adapter which contains a unique adapter ordinal
+// that is installed on the system
+//--------------------------------------------------------------------------------------
+class CD3D11EnumAdapterInfo
+{
+ const CD3D11EnumAdapterInfo &operator = ( const CD3D11EnumAdapterInfo &rhs );
+
+public:
+ CD3D11EnumAdapterInfo() :
+ AdapterOrdinal( 0 ),
+ m_pAdapter( nullptr ),
+ bAdapterUnavailable(false)
+ {
+ *szUniqueDescription = 0;
+ memset( &AdapterDesc, 0, sizeof(AdapterDesc) );
+ }
+ ~CD3D11EnumAdapterInfo();
+
+ UINT AdapterOrdinal;
+ DXGI_ADAPTER_DESC AdapterDesc;
+ WCHAR szUniqueDescription[DXGI_MAX_DEVICE_IDENTIFIER_STRING];
+ IDXGIAdapter *m_pAdapter;
+ bool bAdapterUnavailable;
+
+ std::vector<CD3D11EnumOutputInfo*> outputInfoList; // Array of CD3D11EnumOutputInfo*
+ std::vector<CD3D11EnumDeviceInfo*> deviceInfoList; // Array of CD3D11EnumDeviceInfo*
+ // List of CD3D11EnumDeviceSettingsCombo* with a unique set
+ // of BackBufferFormat, and Windowed
+ std::vector<CD3D11EnumDeviceSettingsCombo*> deviceSettingsComboList;
+};
+
+
+class CD3D11EnumOutputInfo
+{
+ const CD3D11EnumOutputInfo &operator = ( const CD3D11EnumOutputInfo &rhs );
+
+public:
+ CD3D11EnumOutputInfo() :
+ AdapterOrdinal( 0 ),
+ Output( 0 ),
+ m_pOutput( nullptr ) {}
+ ~CD3D11EnumOutputInfo();
+
+ UINT AdapterOrdinal;
+ UINT Output;
+ IDXGIOutput* m_pOutput;
+ DXGI_OUTPUT_DESC Desc;
+
+ std::vector <DXGI_MODE_DESC> displayModeList; // Array of supported D3DDISPLAYMODEs
+};
+
+
+//--------------------------------------------------------------------------------------
+// A class describing a Direct3D11 device that contains a unique supported driver type
+//--------------------------------------------------------------------------------------
+class CD3D11EnumDeviceInfo
+{
+ const CD3D11EnumDeviceInfo& operator =( const CD3D11EnumDeviceInfo& rhs );
+
+public:
+ ~CD3D11EnumDeviceInfo();
+
+ UINT AdapterOrdinal;
+ D3D_DRIVER_TYPE DeviceType;
+ D3D_FEATURE_LEVEL SelectedLevel;
+ D3D_FEATURE_LEVEL MaxLevel;
+ BOOL ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x;
+};
+
+
+//--------------------------------------------------------------------------------------
+// A struct describing device settings that contains a unique combination of
+// adapter format, back buffer format, and windowed that is compatible with a
+// particular Direct3D device and the app.
+//--------------------------------------------------------------------------------------
+struct CD3D11EnumDeviceSettingsCombo
+{
+ UINT AdapterOrdinal;
+ D3D_DRIVER_TYPE DeviceType;
+ DXGI_FORMAT BackBufferFormat;
+ BOOL Windowed;
+ UINT Output;
+
+ std::vector <UINT> multiSampleCountList; // List of valid sampling counts (multisampling)
+ std::vector <UINT> multiSampleQualityList; // List of number of quality levels for each multisample count
+
+ CD3D11EnumAdapterInfo* pAdapterInfo;
+ CD3D11EnumDeviceInfo* pDeviceInfo;
+ CD3D11EnumOutputInfo* pOutputInfo;
+};
+
+float DXUTRankD3D11DeviceCombo( _In_ CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo,
+ _In_ DXUTD3D11DeviceSettings* pOptimalDeviceSettings,
+ _Out_ int &bestModeIndex,
+ _Out_ int &bestMSAAIndex
+ );
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTmisc.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTmisc.h
new file mode 100644
index 0000000..9706ccc
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/DXUTmisc.h
@@ -0,0 +1,298 @@
+//--------------------------------------------------------------------------------------
+// File: DXUTMisc.h
+//
+// Helper functions for Direct3D programming.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+//--------------------------------------------------------------------------------------
+// XInput helper state/function
+// This performs extra processing on XInput gamepad data to make it slightly more convenient to use
+//
+// Example usage:
+//
+// DXUT_GAMEPAD gamepad[4];
+// for( DWORD iPort=0; iPort<DXUT_MAX_CONTROLLERS; iPort++ )
+// DXUTGetGamepadState( iPort, gamepad[iPort] );
+//
+//--------------------------------------------------------------------------------------
+#define DXUT_MAX_CONTROLLERS 4 // XInput handles up to 4 controllers
+
+struct DXUT_GAMEPAD
+{
+ // From XINPUT_GAMEPAD
+ WORD wButtons;
+ BYTE bLeftTrigger;
+ BYTE bRightTrigger;
+ SHORT sThumbLX;
+ SHORT sThumbLY;
+ SHORT sThumbRX;
+ SHORT sThumbRY;
+
+ // Device properties
+ XINPUT_CAPABILITIES caps;
+ bool bConnected; // If the controller is currently connected
+ bool bInserted; // If the controller was inserted this frame
+ bool bRemoved; // If the controller was removed this frame
+
+ // Thumb stick values converted to range [-1,+1]
+ float fThumbRX;
+ float fThumbRY;
+ float fThumbLX;
+ float fThumbLY;
+
+ // Records which buttons were pressed this frame.
+ // These are only set on the first frame that the button is pressed
+ WORD wPressedButtons;
+ bool bPressedLeftTrigger;
+ bool bPressedRightTrigger;
+
+ // Last state of the buttons
+ WORD wLastButtons;
+ bool bLastLeftTrigger;
+ bool bLastRightTrigger;
+};
+
+HRESULT DXUTGetGamepadState( _In_ DWORD dwPort, _In_ DXUT_GAMEPAD* pGamePad, _In_ bool bThumbstickDeadZone = true,
+ _In_ bool bSnapThumbstickToCardinals = true );
+HRESULT DXUTStopRumbleOnAllControllers();
+void DXUTEnableXInput( _In_ bool bEnable );
+
+
+//--------------------------------------------------------------------------------------
+// Takes a screen shot of a 32bit D3D11 back buffer and saves the images to a BMP or DDS file
+//--------------------------------------------------------------------------------------
+
+HRESULT DXUTSnapD3D11Screenshot( _In_z_ LPCWSTR szFileName, _In_ bool usedds = true );
+
+//--------------------------------------------------------------------------------------
+// Performs timer operations
+// Use DXUTGetGlobalTimer() to get the global instance
+//--------------------------------------------------------------------------------------
+class CDXUTTimer
+{
+public:
+ CDXUTTimer();
+
+ void Reset(); // resets the timer
+ void Start(); // starts the timer
+ void Stop(); // stop (or pause) the timer
+ void Advance(); // advance the timer by 0.1 seconds
+ double GetAbsoluteTime() const; // get the absolute system time
+ double GetTime() const; // get the current time
+ float GetElapsedTime(); // get the time that elapsed between Get*ElapsedTime() calls
+ void GetTimeValues( _Out_ double* pfTime, _Out_ double* pfAbsoluteTime, _Out_ float* pfElapsedTime ); // get all time values at once
+ bool IsStopped() const { return m_bTimerStopped; } // returns true if timer stopped
+
+ // Limit the current thread to one processor (the current one). This ensures that timing code runs
+ // on only one processor, and will not suffer any ill effects from power management.
+ void LimitThreadAffinityToCurrentProc();
+
+protected:
+ LARGE_INTEGER GetAdjustedCurrentTime() const;
+
+ bool m_bUsingQPF;
+ bool m_bTimerStopped;
+ LONGLONG m_llQPFTicksPerSec;
+
+ LONGLONG m_llStopTime;
+ LONGLONG m_llLastElapsedTime;
+ LONGLONG m_llBaseTime;
+};
+
+CDXUTTimer* WINAPI DXUTGetGlobalTimer();
+
+
+//--------------------------------------------------------------------------------------
+// Returns the string for the given DXGI_FORMAT.
+// bWithPrefix determines whether the string should include the "DXGI_FORMAT_"
+//--------------------------------------------------------------------------------------
+LPCWSTR WINAPI DXUTDXGIFormatToString( _In_ DXGI_FORMAT format, _In_ bool bWithPrefix );
+
+
+//--------------------------------------------------------------------------------------
+// Debug printing support
+// See dxerr.h for more debug printing support
+//--------------------------------------------------------------------------------------
+void WINAPI DXUTOutputDebugStringW( _In_z_ LPCWSTR strMsg, ... );
+void WINAPI DXUTOutputDebugStringA( _In_z_ LPCSTR strMsg, ... );
+HRESULT WINAPI DXUTTrace( _In_z_ const CHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_z_ const WCHAR* strMsg, _In_ bool bPopMsgBox );
+const WCHAR* WINAPI DXUTTraceWindowsMessage( _In_ UINT uMsg );
+
+#ifdef UNICODE
+#define DXUTOutputDebugString DXUTOutputDebugStringW
+#else
+#define DXUTOutputDebugString DXUTOutputDebugStringA
+#endif
+
+// These macros are very similar to dxerr's but it special cases the HRESULT defined
+// by DXUT to pop better message boxes.
+#if defined(DEBUG) || defined(_DEBUG)
+#define DXUT_ERR(str,hr) DXUTTrace( __FILE__, (DWORD)__LINE__, hr, str, false )
+#define DXUT_ERR_MSGBOX(str,hr) DXUTTrace( __FILE__, (DWORD)__LINE__, hr, str, true )
+#define DXUTTRACE DXUTOutputDebugString
+#else
+#define DXUT_ERR(str,hr) (hr)
+#define DXUT_ERR_MSGBOX(str,hr) (hr)
+#define DXUTTRACE (__noop)
+#endif
+
+
+//--------------------------------------------------------------------------------------
+// Direct3D dynamic linking support -- calls top-level D3D APIs with graceful
+// failure if APIs are not present.
+//--------------------------------------------------------------------------------------
+
+int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( _In_ DWORD col, _In_z_ LPCWSTR wszName );
+int WINAPI DXUT_Dynamic_D3DPERF_EndEvent( void );
+void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( _In_ DWORD col, _In_z_ LPCWSTR wszName );
+void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( _In_ DWORD col, _In_z_ LPCWSTR wszName );
+BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame( void );
+void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( _In_ DWORD dwOptions );
+DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus();
+HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( _In_ REFIID rInterface, _Out_ void** ppOut );
+HRESULT WINAPI DXUT_Dynamic_DXGIGetDebugInterface( _In_ REFIID rInterface, _Out_ void** ppOut );
+
+HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( _In_opt_ IDXGIAdapter* pAdapter,
+ _In_ D3D_DRIVER_TYPE DriverType,
+ _In_opt_ HMODULE Software,
+ _In_ UINT32 Flags,
+ _In_reads_(FeatureLevels) const D3D_FEATURE_LEVEL* pFeatureLevels,
+ _In_ UINT FeatureLevels,
+ _In_ UINT32 SDKVersion,
+ _Deref_out_ ID3D11Device** ppDevice,
+ _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel,
+ _Out_opt_ ID3D11DeviceContext** ppImmediateContext );
+
+bool DXUT_EnsureD3D11APIs();
+
+
+//--------------------------------------------------------------------------------------
+// Profiling/instrumentation support
+//--------------------------------------------------------------------------------------
+
+// Use DXUT_SetDebugName() to attach names to D3D objects for use by
+// SDKDebugLayer, PIX's object table, etc.
+#if defined(PROFILE) || defined(DEBUG)
+inline void DXUT_SetDebugName( _In_ IDXGIObject* pObj, _In_z_ const CHAR* pstrName )
+{
+ if ( pObj )
+ pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName );
+}
+inline void DXUT_SetDebugName( _In_ ID3D11Device* pObj, _In_z_ const CHAR* pstrName )
+{
+ if ( pObj )
+ pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName );
+}
+inline void DXUT_SetDebugName( _In_ ID3D11DeviceChild* pObj, _In_z_ const CHAR* pstrName )
+{
+ if ( pObj )
+ pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName );
+}
+#else
+#define DXUT_SetDebugName( pObj, pstrName )
+#endif
+
+
+//--------------------------------------------------------------------------------------
+// Some D3DPERF APIs take a color that can be used when displaying user events in
+// performance analysis tools. The following constants are provided for your
+// convenience, but you can use any colors you like.
+//--------------------------------------------------------------------------------------
+const DWORD DXUT_PERFEVENTCOLOR = 0xFFC86464;
+const DWORD DXUT_PERFEVENTCOLOR2 = 0xFF64C864;
+const DWORD DXUT_PERFEVENTCOLOR3 = 0xFF6464C8;
+
+//--------------------------------------------------------------------------------------
+// The following macros provide a convenient way for your code to call the D3DPERF
+// functions only when PROFILE is defined. If PROFILE is not defined (as for the final
+// release version of a program), these macros evaluate to nothing, so no detailed event
+// information is embedded in your shipping program. It is recommended that you create
+// and use three build configurations for your projects:
+// Debug (nonoptimized code, asserts active, PROFILE defined to assist debugging)
+// Profile (optimized code, asserts disabled, PROFILE defined to assist optimization)
+// Release (optimized code, asserts disabled, PROFILE not defined)
+//--------------------------------------------------------------------------------------
+#ifdef PROFILE
+// PROFILE is defined, so these macros call the D3DPERF functions
+#define DXUT_BeginPerfEvent( color, pstrMessage ) DXUT_Dynamic_D3DPERF_BeginEvent( color, pstrMessage )
+#define DXUT_EndPerfEvent() DXUT_Dynamic_D3DPERF_EndEvent()
+#define DXUT_SetPerfMarker( color, pstrMessage ) DXUT_Dynamic_D3DPERF_SetMarker( color, pstrMessage )
+#else
+// PROFILE is not defined, so these macros do nothing
+#define DXUT_BeginPerfEvent( color, pstrMessage ) (__noop)
+#define DXUT_EndPerfEvent() (__noop)
+#define DXUT_SetPerfMarker( color, pstrMessage ) (__noop)
+#endif
+
+//--------------------------------------------------------------------------------------
+// CDXUTPerfEventGenerator is a helper class that makes it easy to attach begin and end
+// events to a block of code. Simply define a CDXUTPerfEventGenerator variable anywhere
+// in a block of code, and the class's constructor will call DXUT_BeginPerfEvent when
+// the block of code begins, and the class's destructor will call DXUT_EndPerfEvent when
+// the block ends.
+//--------------------------------------------------------------------------------------
+class CDXUTPerfEventGenerator
+{
+public:
+CDXUTPerfEventGenerator( _In_ DWORD color, _In_z_ LPCWSTR pstrMessage )
+{
+#ifdef PROFILE
+ DXUT_BeginPerfEvent( color, pstrMessage );
+#else
+ UNREFERENCED_PARAMETER(color);
+ UNREFERENCED_PARAMETER(pstrMessage);
+#endif
+}
+~CDXUTPerfEventGenerator()
+{
+ DXUT_EndPerfEvent();
+}
+};
+
+
+//--------------------------------------------------------------------------------------
+// Multimon handling to support OSes with or without multimon API support.
+// Purposely avoiding the use of multimon.h so DXUT.lib doesn't require
+// COMPILE_MULTIMON_STUBS and cause complication with MFC or other users of multimon.h
+//--------------------------------------------------------------------------------------
+#ifndef MONITOR_DEFAULTTOPRIMARY
+#define MONITORINFOF_PRIMARY 0x00000001
+#define MONITOR_DEFAULTTONULL 0x00000000
+#define MONITOR_DEFAULTTOPRIMARY 0x00000001
+#define MONITOR_DEFAULTTONEAREST 0x00000002
+typedef struct tagMONITORINFO
+{
+ DWORD cbSize;
+ RECT rcMonitor;
+ RECT rcWork;
+ DWORD dwFlags;
+} MONITORINFO, *LPMONITORINFO;
+typedef struct tagMONITORINFOEXW : public tagMONITORINFO
+{
+ WCHAR szDevice[CCHDEVICENAME];
+} MONITORINFOEXW, *LPMONITORINFOEXW;
+typedef MONITORINFOEXW MONITORINFOEX;
+typedef LPMONITORINFOEXW LPMONITORINFOEX;
+#endif
+
+HMONITOR WINAPI DXUTMonitorFromWindow( _In_ HWND hWnd, _In_ DWORD dwFlags );
+HMONITOR WINAPI DXUTMonitorFromRect( _In_ LPCRECT lprcScreenCoords, _In_ DWORD dwFlags );
+BOOL WINAPI DXUTGetMonitorInfo( _In_ HMONITOR hMonitor, _Out_ LPMONITORINFO lpMonitorInfo );
+void WINAPI DXUTGetDesktopResolution( _In_ UINT AdapterOrdinal, _Out_ UINT* pWidth, _Out_ UINT* pHeight );
+
+
+//--------------------------------------------------------------------------------------
+// Helper functions to create SRGB formats from typeless formats and vice versa
+//--------------------------------------------------------------------------------------
+DXGI_FORMAT MAKE_SRGB( _In_ DXGI_FORMAT format );
+DXGI_FORMAT MAKE_TYPELESS( _In_ DXGI_FORMAT format );
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/ScreenGrab.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/ScreenGrab.h
new file mode 100644
index 0000000..d643073
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/ScreenGrab.h
@@ -0,0 +1,43 @@
+//--------------------------------------------------------------------------------------
+// File: ScreenGrab.h
+//
+// Function for capturing a 2D texture and saving it to a file (aka a 'screenshot'
+// when used on a Direct3D 11 Render Target).
+//
+// Note these functions are useful as a light-weight runtime screen grabber. For
+// full-featured texture capture, DDS writer, and texture processing pipeline,
+// see the 'Texconv' sample and the 'DirectXTex' library.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+// http://go.microsoft.com/fwlink/?LinkId=248929
+//--------------------------------------------------------------------------------------
+
+#pragma once
+
+#include <d3d11_1.h>
+
+#include <ocidl.h>
+#include <stdint.h>
+#include <functional>
+
+
+namespace DirectX
+{
+ HRESULT SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext,
+ _In_ ID3D11Resource* pSource,
+ _In_z_ LPCWSTR fileName );
+
+ HRESULT SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext,
+ _In_ ID3D11Resource* pSource,
+ _In_ REFGUID guidContainerFormat,
+ _In_z_ LPCWSTR fileName,
+ _In_opt_ const GUID* targetFormat = nullptr,
+ _In_opt_ std::function<void(IPropertyBag2*)> setCustomProps = nullptr );
+} \ No newline at end of file
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/WICTextureLoader.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/WICTextureLoader.h
new file mode 100644
index 0000000..2b0340c
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/WICTextureLoader.h
@@ -0,0 +1,123 @@
+//--------------------------------------------------------------------------------------
+// File: WICTextureLoader.h
+//
+// Function for loading a WIC image and creating a Direct3D 11 runtime texture for it
+// (auto-generating mipmaps if possible)
+//
+// Note: Assumes application has already called CoInitializeEx
+//
+// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for
+// auto-gen mipmap support.
+//
+// Note these functions are useful for images created as simple 2D textures. For
+// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader.
+// For a full-featured DDS file reader, writer, and texture processing pipeline see
+// the 'Texconv' sample and the 'DirectXTex' library.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+// http://go.microsoft.com/fwlink/?LinkId=248929
+//--------------------------------------------------------------------------------------
+
+#pragma once
+
+#include <d3d11_1.h>
+#include <stdint.h>
+
+
+namespace DirectX
+{
+ // Standard version
+ HRESULT CreateWICTextureFromMemory( _In_ ID3D11Device* d3dDevice,
+ _In_reads_bytes_(wicDataSize) const uint8_t* wicData,
+ _In_ size_t wicDataSize,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0
+ );
+
+ HRESULT CreateWICTextureFromFile( _In_ ID3D11Device* d3dDevice,
+ _In_z_ const wchar_t* szFileName,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0
+ );
+
+ // Standard version with optional auto-gen mipmap support
+ HRESULT CreateWICTextureFromMemory( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_reads_bytes_(wicDataSize) const uint8_t* wicData,
+ _In_ size_t wicDataSize,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0
+ );
+
+ HRESULT CreateWICTextureFromFile( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_z_ const wchar_t* szFileName,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView,
+ _In_ size_t maxsize = 0
+ );
+
+ // Extended version
+ HRESULT CreateWICTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
+ _In_reads_bytes_(wicDataSize) const uint8_t* wicData,
+ _In_ size_t wicDataSize,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView
+ );
+
+ HRESULT CreateWICTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
+ _In_z_ const wchar_t* szFileName,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView
+ );
+
+ // Extended version with optional auto-gen mipmap support
+ HRESULT CreateWICTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_reads_bytes_(wicDataSize) const uint8_t* wicData,
+ _In_ size_t wicDataSize,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView
+ );
+
+ HRESULT CreateWICTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
+ _In_opt_ ID3D11DeviceContext* d3dContext,
+ _In_z_ const wchar_t* szFileName,
+ _In_ size_t maxsize,
+ _In_ D3D11_USAGE usage,
+ _In_ unsigned int bindFlags,
+ _In_ unsigned int cpuAccessFlags,
+ _In_ unsigned int miscFlags,
+ _In_ bool forceSRGB,
+ _Out_opt_ ID3D11Resource** texture,
+ _Out_opt_ ID3D11ShaderResourceView** textureView
+ );
+} \ No newline at end of file
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Core/dxerr.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/dxerr.h
new file mode 100644
index 0000000..39e348d
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Core/dxerr.h
@@ -0,0 +1,76 @@
+//--------------------------------------------------------------------------------------
+// File: DXErr.h
+//
+// DirectX Error Library
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//--------------------------------------------------------------------------------------
+
+// This version only supports UNICODE.
+
+#pragma once
+
+#include <windows.h>
+#include <sal.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------------------------
+// DXGetErrorString
+//--------------------------------------------------------------------------------------
+const WCHAR* WINAPI DXGetErrorStringW( _In_ HRESULT hr );
+
+#define DXGetErrorString DXGetErrorStringW
+
+//--------------------------------------------------------------------------------------
+// DXGetErrorDescription has to be modified to return a copy in a buffer rather than
+// the original static string.
+//--------------------------------------------------------------------------------------
+void WINAPI DXGetErrorDescriptionW( _In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count );
+
+#define DXGetErrorDescription DXGetErrorDescriptionW
+
+//--------------------------------------------------------------------------------------
+// DXTrace
+//
+// Desc: Outputs a formatted error message to the debug stream
+//
+// Args: WCHAR* strFile The current file, typically passed in using the
+// __FILEW__ macro.
+// DWORD dwLine The current line number, typically passed in using the
+// __LINE__ macro.
+// HRESULT hr An HRESULT that will be traced to the debug stream.
+// CHAR* strMsg A string that will be traced to the debug stream (may be NULL)
+// BOOL bPopMsgBox If TRUE, then a message box will popup also containing the passed info.
+//
+// Return: The hr that was passed in.
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXTraceW( _In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox );
+
+#define DXTrace DXTraceW
+
+//--------------------------------------------------------------------------------------
+//
+// Helper macros
+//
+//--------------------------------------------------------------------------------------
+#if defined(DEBUG) || defined(_DEBUG)
+#define DXTRACE_MSG(str) DXTrace( __FILEW__, (DWORD)__LINE__, 0, str, false )
+#define DXTRACE_ERR(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, false )
+#define DXTRACE_ERR_MSGBOX(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, true )
+#else
+#define DXTRACE_MSG(str) (0L)
+#define DXTRACE_ERR(str,hr) (hr)
+#define DXTRACE_ERR_MSGBOX(str,hr) (hr)
+#endif
+
+#ifdef __cplusplus
+}
+#endif //__cplusplus
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..7f275b0
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/dxutopt.pdb
new file mode 100644
index 0000000..88ff303
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/Win32/Debug/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..7f275b0
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/dxutopt.pdb
new file mode 100644
index 0000000..88ff303
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Debug/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/DXUTOpt.lib
new file mode 100644
index 0000000..1ac2426
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/dxutopt.pdb
new file mode 100644
index 0000000..ca0e159
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/Win32/Release/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..97d0afb
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/dxutopt.pdb
new file mode 100644
index 0000000..24dca7d
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Debug/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/DXUTOpt.lib
new file mode 100644
index 0000000..c9d32a0
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/dxutopt.pdb
new file mode 100644
index 0000000..85c771e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2013/x64/Release/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..635c553
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.pdb
new file mode 100644
index 0000000..89b4bab
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Debug/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.lib
new file mode 100644
index 0000000..6984b55
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.pdb
new file mode 100644
index 0000000..0c28b2e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/Win32/Release/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..8540d6b
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.pdb
new file mode 100644
index 0000000..cc20170
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Debug/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.lib
new file mode 100644
index 0000000..298f121
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.pdb
new file mode 100644
index 0000000..4c0748e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/dynamiccrt/vs2015/x64/Release/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..b7bd479
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/dxutopt.pdb
new file mode 100644
index 0000000..670d106
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Debug/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/DXUTOpt.lib
new file mode 100644
index 0000000..68c4933
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/dxutopt.pdb
new file mode 100644
index 0000000..5e44847
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/Win32/Release/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..3049c41
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/dxutopt.pdb
new file mode 100644
index 0000000..e0db268
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Debug/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/DXUTOpt.lib
new file mode 100644
index 0000000..e3d071e
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/dxutopt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/dxutopt.pdb
new file mode 100644
index 0000000..cefc664
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2013/x64/Release/dxutopt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..d5d77a2
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.pdb
new file mode 100644
index 0000000..e718bb0
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Debug/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.lib
new file mode 100644
index 0000000..e66fdbd
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.pdb
new file mode 100644
index 0000000..9b0dcd7
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/Win32/Release/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.lib
new file mode 100644
index 0000000..0023238
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.pdb
new file mode 100644
index 0000000..2e3c329
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Debug/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.lib b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.lib
new file mode 100644
index 0000000..e1d99d1
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.lib
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.pdb b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.pdb
new file mode 100644
index 0000000..e4b57e0
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/Bin/staticcrt/vs2015/x64/Release/DXUTOpt.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTLockFreePipe.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTLockFreePipe.h
new file mode 100644
index 0000000..e6bd360
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTLockFreePipe.h
@@ -0,0 +1,226 @@
+//--------------------------------------------------------------------------------------
+// DXUTLockFreePipe.h
+//
+// See the "Lockless Programming Considerations for Xbox 360 and Microsoft Windows"
+// article for more details.
+//
+// http://msdn.microsoft.com/en-us/library/ee418650.aspx
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+#include <sal.h>
+#include <algorithm>
+
+#pragma pack(push)
+#pragma pack(8)
+#include <windows.h>
+#pragma pack (pop)
+
+extern "C"
+ void _ReadWriteBarrier();
+#pragma intrinsic(_ReadWriteBarrier)
+
+// Prevent the compiler from rearranging loads
+// and stores, sufficiently for read-acquire
+// and write-release. This is sufficient on
+// x86 and x64.
+#define DXUTImportBarrier _ReadWriteBarrier
+#define DXUTExportBarrier _ReadWriteBarrier
+
+//
+// Pipe class designed for use by at most two threads: one reader, one writer.
+// Access by more than two threads isn't guaranteed to be safe.
+//
+// In order to provide efficient access the size of the buffer is passed
+// as a template parameter and restricted to powers of two less than 31.
+//
+
+template <BYTE cbBufferSizeLog2> class DXUTLockFreePipe
+{
+public:
+ DXUTLockFreePipe() : m_readOffset( 0 ),
+ m_writeOffset( 0 )
+ {
+ }
+
+ DWORD GetBufferSize() const
+ {
+ return c_cbBufferSize;
+ }
+
+ __forceinline unsigned long BytesAvailable() const
+ {
+ return m_writeOffset - m_readOffset;
+ }
+
+ bool __forceinline Read( _Out_writes_(cbDest) void* pvDest, _In_ unsigned long cbDest )
+ {
+ // Store the read and write offsets into local variables--this is
+ // essentially a snapshot of their values so that they stay constant
+ // for the duration of the function (and so we don't end up with cache
+ // misses due to false sharing).
+ DWORD readOffset = m_readOffset;
+ DWORD writeOffset = m_writeOffset;
+
+ // Compare the two offsets to see if we have anything to read.
+ // Note that we don't do anything to synchronize the offsets here.
+ // Really there's not much we *can* do unless we're willing to completely
+ // synchronize access to the entire object. We have to assume that as we
+ // read, someone else may be writing, and the write offset we have now
+ // may be out of date by the time we read it. Fortunately that's not a
+ // very big deal. We might miss reading some data that was just written.
+ // But the assumption is that we'll be back before long to grab more data
+ // anyway.
+ //
+ // Note that this comparison works because we're careful to constrain
+ // the total buffer size to be a power of 2, which means it will divide
+ // evenly into ULONG_MAX+1. That, and the fact that the offsets are
+ // unsigned, means that the calculation returns correct results even
+ // when the values wrap around.
+ DWORD cbAvailable = writeOffset - readOffset;
+ if( cbDest > cbAvailable )
+ {
+ return false;
+ }
+
+ // The data has been made available, but we need to make sure
+ // that our view on the data is up to date -- at least as up to
+ // date as the control values we just read. We need to prevent
+ // the compiler or CPU from moving any of the data reads before
+ // the control value reads. This import barrier serves this
+ // purpose, on Xbox 360 and on Windows.
+
+ // Reading a control value and then having a barrier is known
+ // as a "read-acquire."
+ DXUTImportBarrier();
+
+ unsigned char* pbDest = ( unsigned char* )pvDest;
+
+ unsigned long actualReadOffset = readOffset & c_sizeMask;
+ unsigned long bytesLeft = cbDest;
+
+ //
+ // Copy from the tail, then the head. Note that there's no explicit
+ // check to see if the write offset comes between the read offset
+ // and the end of the buffer--that particular condition is implicitly
+ // checked by the comparison with AvailableToRead(), above. If copying
+ // cbDest bytes off the tail would cause us to cross the write offset,
+ // then the previous comparison would have failed since that would imply
+ // that there were less than cbDest bytes available to read.
+ //
+ unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualReadOffset );
+ memcpy( pbDest, m_pbBuffer + actualReadOffset, cbTailBytes );
+ bytesLeft -= cbTailBytes;
+
+ if( bytesLeft )
+ {
+ memcpy( pbDest + cbTailBytes, m_pbBuffer, bytesLeft );
+ }
+
+ // When we update the read offset we are, effectively, 'freeing' buffer
+ // memory so that the writing thread can use it. We need to make sure that
+ // we don't free the memory before we have finished reading it. That is,
+ // we need to make sure that the write to m_readOffset can't get reordered
+ // above the reads of the buffer data. The only way to guarantee this is to
+ // have an export barrier to prevent both compiler and CPU rearrangements.
+ DXUTExportBarrier();
+
+ // Advance the read offset. From the CPUs point of view this is several
+ // operations--read, modify, store--and we'd normally want to make sure that
+ // all of the operations happened atomically. But in the case of a single
+ // reader, only one thread updates this value and so the only operation that
+ // must be atomic is the store. That's lucky, because 32-bit aligned stores are
+ // atomic on all modern processors.
+ //
+ readOffset += cbDest;
+ m_readOffset = readOffset;
+
+ return true;
+ }
+
+ bool __forceinline Write( _In_reads_(cbSrc) const void* pvSrc, _In_ unsigned long cbSrc )
+ {
+ // Reading the read offset here has the same caveats as reading
+ // the write offset had in the Read() function above.
+ DWORD readOffset = m_readOffset;
+ DWORD writeOffset = m_writeOffset;
+
+ // Compute the available write size. This comparison relies on
+ // the fact that the buffer size is always a power of 2, and the
+ // offsets are unsigned integers, so that when the write pointer
+ // wraps around the subtraction still yields a value (assuming
+ // we haven't messed up somewhere else) between 0 and c_cbBufferSize - 1.
+ DWORD cbAvailable = c_cbBufferSize - ( writeOffset - readOffset );
+ if( cbSrc > cbAvailable )
+ {
+ return false;
+ }
+
+ // It is theoretically possible for writes of the data to be reordered
+ // above the reads to see if the data is available. Improbable perhaps,
+ // but possible. This barrier guarantees that the reordering will not
+ // happen.
+ DXUTImportBarrier();
+
+ // Write the data
+ const unsigned char* pbSrc = ( const unsigned char* )pvSrc;
+ unsigned long actualWriteOffset = writeOffset & c_sizeMask;
+ unsigned long bytesLeft = cbSrc;
+
+ // See the explanation in the Read() function as to why we don't
+ // explicitly check against the read offset here.
+ unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualWriteOffset );
+ memcpy( m_pbBuffer + actualWriteOffset, pbSrc, cbTailBytes );
+ bytesLeft -= cbTailBytes;
+
+ if( bytesLeft )
+ {
+ memcpy( m_pbBuffer, pbSrc + cbTailBytes, bytesLeft );
+ }
+
+ // Now it's time to update the write offset, but since the updated position
+ // of the write offset will imply that there's data to be read, we need to
+ // make sure that the data all actually gets written before the update to
+ // the write offset. The writes could be reordered by the compiler (on any
+ // platform) or by the CPU (on Xbox 360). We need a barrier which prevents
+ // the writes from being reordered past each other.
+ //
+ // Having a barrier and then writing a control value is called "write-release."
+ DXUTExportBarrier();
+
+ // See comments in Read() as to why this operation isn't interlocked.
+ writeOffset += cbSrc;
+ m_writeOffset = writeOffset;
+
+ return true;
+ }
+
+private:
+ // Values derived from the buffer size template parameter
+ //
+ const static BYTE c_cbBufferSizeLog2 = __min( cbBufferSizeLog2, 31 );
+ const static DWORD c_cbBufferSize = ( 1 << c_cbBufferSizeLog2 );
+ const static DWORD c_sizeMask = c_cbBufferSize - 1;
+
+ // Leave these private and undefined to prevent their use
+ DXUTLockFreePipe( const DXUTLockFreePipe& );
+ DXUTLockFreePipe& operator =( const DXUTLockFreePipe& );
+
+ // Member data
+ //
+ BYTE m_pbBuffer[c_cbBufferSize];
+ // Note that these offsets are not clamped to the buffer size.
+ // Instead the calculations rely on wrapping at ULONG_MAX+1.
+ // See the comments in Read() for details.
+ volatile DWORD __declspec( align( 4 ) ) m_readOffset;
+ volatile DWORD __declspec( align( 4 ) ) m_writeOffset;
+}; \ No newline at end of file
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTcamera.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTcamera.h
new file mode 100644
index 0000000..047760d
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTcamera.h
@@ -0,0 +1,426 @@
+//--------------------------------------------------------------------------------------
+// File: Camera.h
+//
+// Helper functions for Direct3D programming.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+//--------------------------------------------------------------------------------------
+class CD3DArcBall
+{
+public:
+ CD3DArcBall();
+
+ // Functions to change behavior
+ void Reset();
+ void SetTranslationRadius( _In_ float fRadiusTranslation )
+ {
+ m_fRadiusTranslation = fRadiusTranslation;
+ }
+ void SetWindow( _In_ INT nWidth, _In_ INT nHeight, _In_ float fRadius = 0.9f )
+ {
+ m_nWidth = nWidth;
+ m_nHeight = nHeight;
+ m_fRadius = fRadius;
+ m_vCenter.x = float(m_nWidth) / 2.0f;
+ m_vCenter.y = float(m_nHeight) / 2.0f;
+ }
+ void SetOffset( _In_ INT nX, _In_ INT nY ) { m_Offset.x = nX; m_Offset.y = nY; }
+
+ // Call these from client and use GetRotationMatrix() to read new rotation matrix
+ void OnBegin( _In_ int nX, _In_ int nY ); // start the rotation (pass current mouse position)
+ void OnMove( _In_ int nX, _In_ int nY ); // continue the rotation (pass current mouse position)
+ void OnEnd(); // end the rotation
+
+ // Or call this to automatically handle left, middle, right buttons
+ LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+ // Functions to get/set state
+ DirectX::XMMATRIX GetRotationMatrix() const
+ {
+ using namespace DirectX;
+ XMVECTOR q = XMLoadFloat4( &m_qNow );
+ return DirectX::XMMatrixRotationQuaternion( q );
+ }
+ DirectX::XMMATRIX GetTranslationMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslation ); }
+ DirectX::XMMATRIX GetTranslationDeltaMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslationDelta ); }
+ bool IsBeingDragged() const { return m_bDrag; }
+ DirectX::XMVECTOR GetQuatNow() const { return DirectX::XMLoadFloat4( &m_qNow ); }
+ void SetQuatNow( _In_ DirectX::FXMVECTOR& q ) { DirectX::XMStoreFloat4( &m_qNow, q ); }
+
+ static DirectX::XMVECTOR QuatFromBallPoints( _In_ DirectX::FXMVECTOR vFrom, _In_ DirectX::FXMVECTOR vTo )
+ {
+ using namespace DirectX;
+
+ XMVECTOR dot = XMVector3Dot( vFrom, vTo );
+ XMVECTOR vPart = XMVector3Cross( vFrom, vTo );
+ return XMVectorSelect( dot, vPart, g_XMSelect1110 );
+ }
+
+protected:
+ DirectX::XMFLOAT4X4 m_mRotation; // Matrix for arc ball's orientation
+ DirectX::XMFLOAT4X4 m_mTranslation; // Matrix for arc ball's position
+ DirectX::XMFLOAT4X4 m_mTranslationDelta;// Matrix for arc ball's position
+
+ POINT m_Offset; // window offset, or upper-left corner of window
+ INT m_nWidth; // arc ball's window width
+ INT m_nHeight; // arc ball's window height
+ DirectX::XMFLOAT2 m_vCenter; // center of arc ball
+ float m_fRadius; // arc ball's radius in screen coords
+ float m_fRadiusTranslation; // arc ball's radius for translating the target
+
+ DirectX::XMFLOAT4 m_qDown; // Quaternion before button down
+ DirectX::XMFLOAT4 m_qNow; // Composite quaternion for current drag
+ bool m_bDrag; // Whether user is dragging arc ball
+
+ POINT m_ptLastMouse; // position of last mouse point
+ DirectX::XMFLOAT3 m_vDownPt; // starting point of rotation arc
+ DirectX::XMFLOAT3 m_vCurrentPt; // current point of rotation arc
+
+ DirectX::XMVECTOR ScreenToVector( _In_ float fScreenPtX, _In_ float fScreenPtY )
+ {
+ // Scale to screen
+ float x = -( fScreenPtX - m_Offset.x - m_nWidth / 2 ) / ( m_fRadius * m_nWidth / 2 );
+ float y = ( fScreenPtY - m_Offset.y - m_nHeight / 2 ) / ( m_fRadius * m_nHeight / 2 );
+
+ float z = 0.0f;
+ float mag = x * x + y * y;
+
+ if( mag > 1.0f )
+ {
+ float scale = 1.0f / sqrtf( mag );
+ x *= scale;
+ y *= scale;
+ }
+ else
+ z = sqrtf( 1.0f - mag );
+
+ return DirectX::XMVectorSet( x, y, z, 0 );
+ }
+};
+
+
+//--------------------------------------------------------------------------------------
+// used by CCamera to map WM_KEYDOWN keys
+//--------------------------------------------------------------------------------------
+enum D3DUtil_CameraKeys
+{
+ CAM_STRAFE_LEFT = 0,
+ CAM_STRAFE_RIGHT,
+ CAM_MOVE_FORWARD,
+ CAM_MOVE_BACKWARD,
+ CAM_MOVE_UP,
+ CAM_MOVE_DOWN,
+ CAM_RESET,
+ CAM_CONTROLDOWN,
+ CAM_MAX_KEYS,
+ CAM_UNKNOWN = 0xFF
+};
+
+#define KEY_WAS_DOWN_MASK 0x80
+#define KEY_IS_DOWN_MASK 0x01
+
+#define MOUSE_LEFT_BUTTON 0x01
+#define MOUSE_MIDDLE_BUTTON 0x02
+#define MOUSE_RIGHT_BUTTON 0x04
+#define MOUSE_WHEEL 0x08
+
+
+//--------------------------------------------------------------------------------------
+// Simple base camera class that moves and rotates. The base class
+// records mouse and keyboard input for use by a derived class, and
+// keeps common state.
+//--------------------------------------------------------------------------------------
+class CBaseCamera
+{
+public:
+ CBaseCamera();
+
+ // Call these from client and use Get*Matrix() to read new matrices
+ virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+ virtual void FrameMove( _In_ float fElapsedTime ) = 0;
+
+ // Functions to change camera matrices
+ virtual void Reset();
+ virtual void SetViewParams( _In_ DirectX::FXMVECTOR vEyePt, _In_ DirectX::FXMVECTOR vLookatPt );
+ virtual void SetProjParams( _In_ float fFOV, _In_ float fAspect, _In_ float fNearPlane, _In_ float fFarPlane );
+
+ // Functions to change behavior
+ virtual void SetDragRect( _In_ const RECT& rc ) { m_rcDrag = rc; }
+ void SetInvertPitch( _In_ bool bInvertPitch ) { m_bInvertPitch = bInvertPitch; }
+ void SetDrag( _In_ bool bMovementDrag, _In_ float fTotalDragTimeToZero = 0.25f )
+ {
+ m_bMovementDrag = bMovementDrag;
+ m_fTotalDragTimeToZero = fTotalDragTimeToZero;
+ }
+ void SetEnableYAxisMovement( _In_ bool bEnableYAxisMovement ) { m_bEnableYAxisMovement = bEnableYAxisMovement; }
+ void SetEnablePositionMovement( _In_ bool bEnablePositionMovement ) { m_bEnablePositionMovement = bEnablePositionMovement; }
+ void SetClipToBoundary( _In_ bool bClipToBoundary, _In_opt_ DirectX::XMFLOAT3* pvMinBoundary, _In_opt_ DirectX::XMFLOAT3* pvMaxBoundary )
+ {
+ m_bClipToBoundary = bClipToBoundary;
+ if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary;
+ if( pvMaxBoundary ) m_vMaxBoundary = *pvMaxBoundary;
+ }
+ void SetScalers( _In_ float fRotationScaler = 0.01f, _In_ float fMoveScaler = 5.0f )
+ {
+ m_fRotationScaler = fRotationScaler;
+ m_fMoveScaler = fMoveScaler;
+ }
+ void SetNumberOfFramesToSmoothMouseData( _In_ int nFrames ) { if( nFrames > 0 ) m_fFramesToSmoothMouseData = ( float )nFrames; }
+ void SetResetCursorAfterMove( _In_ bool bResetCursorAfterMove ) { m_bResetCursorAfterMove = bResetCursorAfterMove; }
+
+ // Functions to get state
+ DirectX::XMMATRIX GetViewMatrix() const { return DirectX::XMLoadFloat4x4( &m_mView ); }
+ DirectX::XMMATRIX GetProjMatrix() const { return DirectX::XMLoadFloat4x4( &m_mProj ); }
+ DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( &m_vEye ); }
+ DirectX::XMVECTOR GetLookAtPt() const { return DirectX::XMLoadFloat3( &m_vLookAt ); }
+ float GetNearClip() const { return m_fNearPlane; }
+ float GetFarClip() const { return m_fFarPlane; }
+
+ bool IsBeingDragged() const { return ( m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown ); }
+ bool IsMouseLButtonDown() const { return m_bMouseLButtonDown; }
+ bool IsMouseMButtonDown() const { return m_bMouseMButtonDown; }
+ bool sMouseRButtonDown() const { return m_bMouseRButtonDown; }
+
+protected:
+ // Functions to map a WM_KEYDOWN key to a D3DUtil_CameraKeys enum
+ virtual D3DUtil_CameraKeys MapKey( _In_ UINT nKey );
+
+ bool IsKeyDown( _In_ BYTE key ) const { return( ( key & KEY_IS_DOWN_MASK ) == KEY_IS_DOWN_MASK ); }
+ bool WasKeyDown( _In_ BYTE key ) const { return( ( key & KEY_WAS_DOWN_MASK ) == KEY_WAS_DOWN_MASK ); }
+
+ DirectX::XMVECTOR ConstrainToBoundary( _In_ DirectX::FXMVECTOR v )
+ {
+ using namespace DirectX;
+
+ XMVECTOR vMin = XMLoadFloat3( &m_vMinBoundary );
+ XMVECTOR vMax = XMLoadFloat3( &m_vMaxBoundary );
+
+ // Constrain vector to a bounding box
+ return XMVectorClamp( v, vMin, vMax );
+ }
+
+ void UpdateMouseDelta();
+ void UpdateVelocity( _In_ float fElapsedTime );
+ void GetInput( _In_ bool bGetKeyboardInput, _In_ bool bGetMouseInput, _In_ bool bGetGamepadInput );
+
+ DirectX::XMFLOAT4X4 m_mView; // View matrix
+ DirectX::XMFLOAT4X4 m_mProj; // Projection matrix
+
+ DXUT_GAMEPAD m_GamePad[DXUT_MAX_CONTROLLERS]; // XInput controller state
+ DirectX::XMFLOAT3 m_vGamePadLeftThumb;
+ DirectX::XMFLOAT3 m_vGamePadRightThumb;
+ double m_GamePadLastActive[DXUT_MAX_CONTROLLERS];
+
+ int m_cKeysDown; // Number of camera keys that are down.
+ BYTE m_aKeys[CAM_MAX_KEYS]; // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK
+ DirectX::XMFLOAT3 m_vKeyboardDirection; // Direction vector of keyboard input
+ POINT m_ptLastMousePosition; // Last absolute position of mouse cursor
+ int m_nCurrentButtonMask; // mask of which buttons are down
+ int m_nMouseWheelDelta; // Amount of middle wheel scroll (+/-)
+ DirectX::XMFLOAT2 m_vMouseDelta; // Mouse relative delta smoothed over a few frames
+ float m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over
+ DirectX::XMFLOAT3 m_vDefaultEye; // Default camera eye position
+ DirectX::XMFLOAT3 m_vDefaultLookAt; // Default LookAt position
+ DirectX::XMFLOAT3 m_vEye; // Camera eye position
+ DirectX::XMFLOAT3 m_vLookAt; // LookAt position
+ float m_fCameraYawAngle; // Yaw angle of camera
+ float m_fCameraPitchAngle; // Pitch angle of camera
+
+ RECT m_rcDrag; // Rectangle within which a drag can be initiated.
+ DirectX::XMFLOAT3 m_vVelocity; // Velocity of camera
+ DirectX::XMFLOAT3 m_vVelocityDrag; // Velocity drag force
+ float m_fDragTimer; // Countdown timer to apply drag
+ float m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0
+ DirectX::XMFLOAT2 m_vRotVelocity; // Velocity of camera
+
+ float m_fFOV; // Field of view
+ float m_fAspect; // Aspect ratio
+ float m_fNearPlane; // Near plane
+ float m_fFarPlane; // Far plane
+
+ float m_fRotationScaler; // Scaler for rotation
+ float m_fMoveScaler; // Scaler for movement
+
+ bool m_bMouseLButtonDown; // True if left button is down
+ bool m_bMouseMButtonDown; // True if middle button is down
+ bool m_bMouseRButtonDown; // True if right button is down
+ bool m_bMovementDrag; // If true, then camera movement will slow to a stop otherwise movement is instant
+ bool m_bInvertPitch; // Invert the pitch axis
+ bool m_bEnablePositionMovement; // If true, then the user can translate the camera/model
+ bool m_bEnableYAxisMovement; // If true, then camera can move in the y-axis
+ bool m_bClipToBoundary; // If true, then the camera will be clipped to the boundary
+ bool m_bResetCursorAfterMove; // If true, the class will reset the cursor position so that the cursor always has space to move
+
+ DirectX::XMFLOAT3 m_vMinBoundary; // Min point in clip boundary
+ DirectX::XMFLOAT3 m_vMaxBoundary; // Max point in clip boundary
+};
+
+
+//--------------------------------------------------------------------------------------
+// Simple first person camera class that moves and rotates.
+// It allows yaw and pitch but not roll. It uses WM_KEYDOWN and
+// GetCursorPos() to respond to keyboard and mouse input and updates the
+// view matrix based on input.
+//--------------------------------------------------------------------------------------
+class CFirstPersonCamera : public CBaseCamera
+{
+public:
+ CFirstPersonCamera();
+
+ // Call these from client and use Get*Matrix() to read new matrices
+ virtual void FrameMove( _In_ float fElapsedTime ) override;
+
+ // Functions to change behavior
+ void SetRotateButtons( _In_ bool bLeft, _In_ bool bMiddle, _In_ bool bRight, _In_ bool bRotateWithoutButtonDown = false );
+
+ // Functions to get state
+ DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mCameraWorld ); }
+
+ DirectX::XMVECTOR GetWorldRight() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._11 ) ); }
+ DirectX::XMVECTOR GetWorldUp() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._21 ) ); }
+ DirectX::XMVECTOR GetWorldAhead() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._31 ) ); }
+ DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( reinterpret_cast<const DirectX::XMFLOAT3*>( &m_mCameraWorld._41 ) ); }
+
+protected:
+ DirectX::XMFLOAT4X4 m_mCameraWorld; // World matrix of the camera (inverse of the view matrix)
+
+ int m_nActiveButtonMask; // Mask to determine which button to enable for rotation
+ bool m_bRotateWithoutButtonDown;
+};
+
+
+//--------------------------------------------------------------------------------------
+// Simple model viewing camera class that rotates around the object.
+//--------------------------------------------------------------------------------------
+class CModelViewerCamera : public CBaseCamera
+{
+public:
+ CModelViewerCamera();
+
+ // Call these from client and use Get*Matrix() to read new matrices
+ virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void FrameMove( _In_ float fElapsedTime ) override;
+
+ // Functions to change behavior
+ virtual void SetDragRect( _In_ const RECT& rc ) override;
+ virtual void Reset() override;
+ virtual void SetViewParams( _In_ DirectX::FXMVECTOR pvEyePt, _In_ DirectX::FXMVECTOR pvLookatPt ) override;
+ void SetButtonMasks( _In_ int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, _In_ int nZoomButtonMask = MOUSE_WHEEL,
+ _In_ int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON )
+ {
+ m_nRotateModelButtonMask = nRotateModelButtonMask, m_nZoomButtonMask = nZoomButtonMask;
+ m_nRotateCameraButtonMask = nRotateCameraButtonMask;
+ }
+ void SetAttachCameraToModel( _In_ bool bEnable = false ) { m_bAttachCameraToModel = bEnable; }
+ void SetWindow( _In_ int nWidth, _In_ int nHeight, _In_ float fArcballRadius=0.9f )
+ {
+ m_WorldArcBall.SetWindow( nWidth, nHeight, fArcballRadius );
+ m_ViewArcBall.SetWindow( nWidth, nHeight, fArcballRadius );
+ }
+ void SetRadius( _In_ float fDefaultRadius=5.0f, _In_ float fMinRadius=1.0f, _In_ float fMaxRadius=FLT_MAX )
+ {
+ m_fDefaultRadius = m_fRadius = fDefaultRadius; m_fMinRadius = fMinRadius; m_fMaxRadius = fMaxRadius;
+ m_bDragSinceLastUpdate = true;
+ }
+ void SetModelCenter( _In_ const DirectX::XMFLOAT3& vModelCenter ) { m_vModelCenter = vModelCenter; }
+ void SetLimitPitch( _In_ bool bLimitPitch ) { m_bLimitPitch = bLimitPitch; }
+ void SetViewQuat( _In_ DirectX::FXMVECTOR q )
+ {
+ m_ViewArcBall.SetQuatNow( q );
+ m_bDragSinceLastUpdate = true;
+ }
+ void SetWorldQuat( _In_ DirectX::FXMVECTOR q )
+ {
+ m_WorldArcBall.SetQuatNow( q );
+ m_bDragSinceLastUpdate = true;
+ }
+
+ // Functions to get state
+ DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mWorld ); }
+ void SetWorldMatrix( _In_ DirectX::CXMMATRIX mWorld )
+ {
+ XMStoreFloat4x4( &m_mWorld, mWorld );
+ m_bDragSinceLastUpdate = true;
+ }
+
+protected:
+ CD3DArcBall m_WorldArcBall;
+ CD3DArcBall m_ViewArcBall;
+ DirectX::XMFLOAT3 m_vModelCenter;
+ DirectX::XMFLOAT4X4 m_mModelLastRot; // Last arcball rotation matrix for model
+ DirectX::XMFLOAT4X4 m_mModelRot; // Rotation matrix of model
+ DirectX::XMFLOAT4X4 m_mWorld; // World matrix of model
+
+ int m_nRotateModelButtonMask;
+ int m_nZoomButtonMask;
+ int m_nRotateCameraButtonMask;
+
+ bool m_bAttachCameraToModel;
+ bool m_bLimitPitch;
+ bool m_bDragSinceLastUpdate; // True if mouse drag has happened since last time FrameMove is called.
+ float m_fRadius; // Distance from the camera to model
+ float m_fDefaultRadius; // Distance from the camera to model
+ float m_fMinRadius; // Min radius
+ float m_fMaxRadius; // Max radius
+
+ DirectX::XMFLOAT4X4 m_mCameraRotLast;
+};
+
+
+//--------------------------------------------------------------------------------------
+// Manages the mesh, direction, mouse events of a directional arrow that
+// rotates around a radius controlled by an arcball
+//--------------------------------------------------------------------------------------
+class CDXUTDirectionWidget
+{
+public:
+ CDXUTDirectionWidget();
+
+ LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+ HRESULT OnRender( _In_ DirectX::FXMVECTOR color, _In_ DirectX::CXMMATRIX pmView, _In_ DirectX::CXMMATRIX pmProj, _In_ DirectX::FXMVECTOR vEyePt );
+
+ DirectX::XMVECTOR GetLightDirection() const { return DirectX::XMLoadFloat3( &m_vCurrentDir ); }
+ void SetLightDirection( _In_ DirectX::FXMVECTOR vDir )
+ {
+ DirectX::XMStoreFloat3( &m_vCurrentDir, vDir );
+ m_vDefaultDir = m_vCurrentDir;
+ }
+ void SetLightDirection( _In_ DirectX::XMFLOAT3 vDir )
+ {
+ m_vDefaultDir = m_vCurrentDir = vDir;
+ }
+ void SetButtonMask( _In_ int nRotate = MOUSE_RIGHT_BUTTON ) { m_nRotateMask = nRotate; }
+
+ float GetRadius() const { return m_fRadius; }
+ void SetRadius( _In_ float fRadius ) { m_fRadius = fRadius; }
+
+ bool IsBeingDragged() { return m_ArcBall.IsBeingDragged(); }
+
+ static HRESULT WINAPI StaticOnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext );
+ static void WINAPI StaticOnD3D11DestroyDevice();
+
+protected:
+ HRESULT UpdateLightDir();
+
+ // TODO - need support for Direct3D 11 widget
+
+ DirectX::XMFLOAT4X4 m_mRot;
+ DirectX::XMFLOAT4X4 m_mRotSnapshot;
+ float m_fRadius;
+ int m_nRotateMask;
+ CD3DArcBall m_ArcBall;
+ DirectX::XMFLOAT3 m_vDefaultDir;
+ DirectX::XMFLOAT3 m_vCurrentDir;
+ DirectX::XMFLOAT4X4 m_mView;
+};
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTgui.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTgui.h
new file mode 100644
index 0000000..870d1e6
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTgui.h
@@ -0,0 +1,1125 @@
+//--------------------------------------------------------------------------------------
+// File: DXUTgui.h
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+#include <usp10.h>
+#include <dimm.h>
+
+#ifdef DXUT_AUTOLIB
+#pragma comment( lib, "usp10.lib" )
+#endif
+
+//--------------------------------------------------------------------------------------
+// Defines and macros
+//--------------------------------------------------------------------------------------
+#define EVENT_BUTTON_CLICKED 0x0101
+#define EVENT_COMBOBOX_SELECTION_CHANGED 0x0201
+#define EVENT_RADIOBUTTON_CHANGED 0x0301
+#define EVENT_CHECKBOX_CHANGED 0x0401
+#define EVENT_SLIDER_VALUE_CHANGED 0x0501
+#define EVENT_SLIDER_VALUE_CHANGED_UP 0x0502
+
+#define EVENT_EDITBOX_STRING 0x0601
+// EVENT_EDITBOX_CHANGE is sent when the listbox content changes
+// due to user input.
+#define EVENT_EDITBOX_CHANGE 0x0602
+#define EVENT_LISTBOX_ITEM_DBLCLK 0x0701
+// EVENT_LISTBOX_SELECTION is fired off when the selection changes in
+// a single selection list box.
+#define EVENT_LISTBOX_SELECTION 0x0702
+#define EVENT_LISTBOX_SELECTION_END 0x0703
+
+
+//--------------------------------------------------------------------------------------
+// Forward declarations
+//--------------------------------------------------------------------------------------
+class CDXUTDialogResourceManager;
+class CDXUTControl;
+class CDXUTButton;
+class CDXUTStatic;
+class CDXUTCheckBox;
+class CDXUTRadioButton;
+class CDXUTComboBox;
+class CDXUTSlider;
+class CDXUTEditBox;
+class CDXUTListBox;
+class CDXUTScrollBar;
+class CDXUTElement;
+struct DXUTElementHolder;
+struct DXUTTextureNode;
+struct DXUTFontNode;
+typedef void ( CALLBACK*PCALLBACKDXUTGUIEVENT )( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl,
+ _In_opt_ void* pUserContext );
+
+
+//--------------------------------------------------------------------------------------
+// Enums for pre-defined control types
+//--------------------------------------------------------------------------------------
+enum DXUT_CONTROL_TYPE
+{
+ DXUT_CONTROL_BUTTON,
+ DXUT_CONTROL_STATIC,
+ DXUT_CONTROL_CHECKBOX,
+ DXUT_CONTROL_RADIOBUTTON,
+ DXUT_CONTROL_COMBOBOX,
+ DXUT_CONTROL_SLIDER,
+ DXUT_CONTROL_EDITBOX,
+ DXUT_CONTROL_IMEEDITBOX,
+ DXUT_CONTROL_LISTBOX,
+ DXUT_CONTROL_SCROLLBAR,
+};
+
+enum DXUT_CONTROL_STATE
+{
+ DXUT_STATE_NORMAL = 0,
+ DXUT_STATE_DISABLED,
+ DXUT_STATE_HIDDEN,
+ DXUT_STATE_FOCUS,
+ DXUT_STATE_MOUSEOVER,
+ DXUT_STATE_PRESSED,
+};
+
+#define MAX_CONTROL_STATES 6
+
+struct DXUTBlendColor
+{
+ void Init( _In_ DWORD defaultColor, _In_ DWORD disabledColor = D3DCOLOR_ARGB( 200, 128, 128, 128 ), _In_ DWORD hiddenColor = 0 );
+ void Blend( _In_ UINT iState, _In_ float fElapsedTime, _In_ float fRate = 0.7f );
+
+ DWORD States[ MAX_CONTROL_STATES ]; // Modulate colors for all possible control states
+ DirectX::XMFLOAT4 Current;
+
+ void SetCurrent( DWORD color );
+};
+
+
+//-----------------------------------------------------------------------------
+// Contains all the display tweakables for a sub-control
+//-----------------------------------------------------------------------------
+class CDXUTElement
+{
+public:
+ void SetTexture( _In_ UINT texture, _In_ RECT* prcTexture, _In_ DWORD defaultTextureColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ) );
+ void SetFont( _In_ UINT font, _In_ DWORD defaultFontColor = D3DCOLOR_ARGB( 255, 255, 255, 255 ), DWORD textFormat = DT_CENTER | DT_VCENTER );
+
+ void Refresh();
+
+ UINT iTexture; // Index of the texture for this Element
+ UINT iFont; // Index of the font for this Element
+ DWORD dwTextFormat; // The format argument to DrawText
+
+ RECT rcTexture; // Bounding rect of this element on the composite texture
+
+ DXUTBlendColor TextureColor;
+ DXUTBlendColor FontColor;
+};
+
+
+//-----------------------------------------------------------------------------
+// All controls must be assigned to a dialog, which handles
+// input and rendering for the controls.
+//-----------------------------------------------------------------------------
+class CDXUTDialog
+{
+ friend class CDXUTDialogResourceManager;
+
+public:
+ CDXUTDialog();
+ ~CDXUTDialog();
+
+ // Need to call this now
+ void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog = true );
+ void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog,
+ _In_z_ LPCWSTR pszControlTextureFilename );
+ void Init( _In_ CDXUTDialogResourceManager* pManager, _In_ bool bRegisterDialog,
+ _In_z_ LPCWSTR szControlTextureResourceName, _In_ HMODULE hControlTextureResourceModule );
+
+ // Windows message handler
+ bool MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+ // Control creation
+ HRESULT AddStatic( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bIsDefault=false,
+ _Out_opt_ CDXUTStatic** ppCreated = nullptr );
+ HRESULT AddButton( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotkey=0,
+ _In_ bool bIsDefault=false, _Out_opt_ CDXUTButton** ppCreated = nullptr );
+ HRESULT AddCheckBox( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bChecked=false,
+ _In_ UINT nHotkey=0, _In_ bool bIsDefault=false, _Out_opt_ CDXUTCheckBox** ppCreated = nullptr );
+ HRESULT AddRadioButton( _In_ int ID, _In_ UINT nButtonGroup, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width,
+ _In_ int height, _In_ bool bChecked=false, _In_ UINT nHotkey=0, _In_ bool bIsDefault=false,
+ _Out_opt_ CDXUTRadioButton** ppCreated = nullptr );
+ HRESULT AddComboBox( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ UINT nHotKey=0, _In_ bool bIsDefault=false,
+ _Out_opt_ CDXUTComboBox** ppCreated = nullptr );
+ HRESULT AddSlider( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ int min=0, _In_ int max=100, _In_ int value=50,
+ _In_ bool bIsDefault=false, _Out_opt_ CDXUTSlider** ppCreated = nullptr );
+ // AddIMEEditBox has been renamed into DXUTguiIME.cpp as CDXUTIMEEditBox::CreateIMEEditBox
+ HRESULT AddEditBox( _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ bool bIsDefault=false,
+ _Out_opt_ CDXUTEditBox** ppCreated = nullptr );
+ HRESULT AddListBox( _In_ int ID, _In_ int x, _In_ int y, _In_ int width, _In_ int height, _In_ DWORD dwStyle=0,
+ _Out_opt_ CDXUTListBox** ppCreated = nullptr );
+ HRESULT AddControl( _In_ CDXUTControl* pControl );
+ HRESULT InitControl( _In_ CDXUTControl* pControl );
+
+ // Control retrieval
+ CDXUTStatic* GetStatic( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTStatic*>( GetControl( ID, DXUT_CONTROL_STATIC ) );
+ }
+ CDXUTButton* GetButton( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTButton*>( GetControl(ID, DXUT_CONTROL_BUTTON) );
+ }
+ CDXUTCheckBox* GetCheckBox( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTCheckBox*>( GetControl(ID, DXUT_CONTROL_CHECKBOX) );
+ }
+ CDXUTRadioButton* GetRadioButton( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTRadioButton*>( GetControl(ID, DXUT_CONTROL_RADIOBUTTON) );
+ }
+ CDXUTComboBox* GetComboBox( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTComboBox*>( GetControl(ID, DXUT_CONTROL_COMBOBOX) );
+ }
+ CDXUTSlider* GetSlider( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTSlider*>( GetControl(ID, DXUT_CONTROL_SLIDER) );
+ }
+ CDXUTEditBox* GetEditBox( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTEditBox*>( GetControl(ID, DXUT_CONTROL_EDITBOX) );
+ }
+ CDXUTListBox* GetListBox( _In_ int ID ) const
+ {
+ return reinterpret_cast<CDXUTListBox*>( GetControl(ID, DXUT_CONTROL_LISTBOX) );
+ }
+
+ CDXUTControl* GetControl( _In_ int ID ) const;
+ CDXUTControl* GetControl( _In_ int ID, _In_ UINT nControlType ) const;
+ CDXUTControl* GetControlAtPoint( _In_ const POINT& pt ) const;
+
+ bool GetControlEnabled( _In_ int ID ) const;
+ void SetControlEnabled( _In_ int ID, _In_ bool bEnabled );
+
+ void ClearRadioButtonGroup( _In_ UINT nGroup );
+ void ClearComboBox( _In_ int ID );
+
+ // Access the default display Elements used when adding new controls
+ HRESULT SetDefaultElement( _In_ UINT nControlType, _In_ UINT iElement, _In_ CDXUTElement* pElement );
+ CDXUTElement* GetDefaultElement( _In_ UINT nControlType, _In_ UINT iElement ) const;
+
+ // Methods called by controls
+ void SendEvent( _In_ UINT nEvent, _In_ bool bTriggeredByUser, _In_ CDXUTControl* pControl );
+ void RequestFocus( _In_ CDXUTControl* pControl );
+
+ // Render helpers
+ HRESULT DrawRect( _In_ const RECT* pRect, _In_ DWORD color );
+ HRESULT DrawSprite( _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ float fDepth );
+ HRESULT DrawSprite11( _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ float fDepth );
+ HRESULT CalcTextRect( _In_z_ LPCWSTR strText, _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ int nCount = -1 );
+ HRESULT DrawText( _In_z_ LPCWSTR strText, _In_ CDXUTElement* pElement, _In_ const RECT* prcDest, _In_ bool bShadow = false,
+ _In_ bool bCenter = false );
+
+ // Attributes
+ bool GetVisible() const { return m_bVisible; }
+ void SetVisible( _In_ bool bVisible ) { m_bVisible = bVisible; }
+ bool GetMinimized() const { return m_bMinimized; }
+ void SetMinimized( _In_ bool bMinimized ) {m_bMinimized = bMinimized; }
+ void SetBackgroundColors( _In_ DWORD colorAllCorners ) { SetBackgroundColors( colorAllCorners, colorAllCorners, colorAllCorners, colorAllCorners ); }
+ void SetBackgroundColors( _In_ DWORD colorTopLeft, _In_ DWORD colorTopRight, _In_ DWORD colorBottomLeft, _In_ DWORD colorBottomRight );
+ void EnableCaption( _In_ bool bEnable ) { m_bCaption = bEnable; }
+ int GetCaptionHeight() const { return m_nCaptionHeight; }
+ void SetCaptionHeight( _In_ int nHeight ) { m_nCaptionHeight = nHeight; }
+ void SetCaptionText( _In_ const WCHAR* pwszText ) { wcscpy_s( m_wszCaption, sizeof( m_wszCaption ) / sizeof( m_wszCaption[0] ), pwszText ); }
+ void GetLocation( _Out_ POINT& Pt ) const
+ {
+ Pt.x = m_x;
+ Pt.y = m_y;
+ }
+ void SetLocation( _In_ int x, _In_ int y )
+ {
+ m_x = x;
+ m_y = y;
+ }
+ void SetSize( _In_ int width, _In_ int height )
+ {
+ m_width = width;
+ m_height = height;
+ }
+ int GetWidth() const { return m_width; }
+ int GetHeight() const { return m_height; }
+
+ static void WINAPI SetRefreshTime( _In_ float fTime ) { s_fTimeRefresh = fTime; }
+
+ static CDXUTControl* WINAPI GetNextControl( _In_ CDXUTControl* pControl );
+ static CDXUTControl* WINAPI GetPrevControl( _In_ CDXUTControl* pControl );
+
+ void RemoveControl( _In_ int ID );
+ void RemoveAllControls();
+
+ // Sets the callback used to notify the app of control events
+ void SetCallback( _In_ PCALLBACKDXUTGUIEVENT pCallback, _In_opt_ void* pUserContext = nullptr );
+ void EnableNonUserEvents( _In_ bool bEnable ) { m_bNonUserEvents = bEnable; }
+ void EnableKeyboardInput( _In_ bool bEnable ) { m_bKeyboardInput = bEnable; }
+ void EnableMouseInput( _In_ bool bEnable ) { m_bMouseInput = bEnable; }
+ bool IsKeyboardInputEnabled() const { return m_bKeyboardInput; }
+
+ // Device state notification
+ void Refresh();
+ HRESULT OnRender( _In_ float fElapsedTime );
+
+ // Shared resource access. Indexed fonts and textures are shared among
+ // all the controls.
+ HRESULT SetFont( _In_ UINT index, _In_z_ LPCWSTR strFaceName, _In_ LONG height, _In_ LONG weight );
+ DXUTFontNode* GetFont( _In_ UINT index ) const;
+
+ HRESULT SetTexture( _In_ UINT index, _In_z_ LPCWSTR strFilename );
+ HRESULT SetTexture( _In_ UINT index, _In_z_ LPCWSTR strResourceName, _In_ HMODULE hResourceModule );
+ DXUTTextureNode* GetTexture( _In_ UINT index ) const;
+
+ CDXUTDialogResourceManager* GetManager() const { return m_pManager; }
+
+ static void WINAPI ClearFocus();
+ void FocusDefaultControl();
+
+ bool m_bNonUserEvents;
+ bool m_bKeyboardInput;
+ bool m_bMouseInput;
+
+private:
+ int m_nDefaultControlID;
+
+ static double s_fTimeRefresh;
+ double m_fTimeLastRefresh;
+
+ // Initialize default Elements
+ void InitDefaultElements();
+
+ // Windows message handlers
+ void OnMouseMove( _In_ const POINT& pt );
+ void OnMouseUp( _In_ const POINT& pt );
+
+ void SetNextDialog( _In_ CDXUTDialog* pNextDialog );
+
+ // Control events
+ bool OnCycleFocus( _In_ bool bForward );
+
+ static CDXUTControl* s_pControlFocus; // The control which has focus
+ static CDXUTControl* s_pControlPressed; // The control currently pressed
+
+ CDXUTControl* m_pControlMouseOver; // The control which is hovered over
+
+ bool m_bVisible;
+ bool m_bCaption;
+ bool m_bMinimized;
+ bool m_bDrag;
+ WCHAR m_wszCaption[256];
+
+ int m_x;
+ int m_y;
+ int m_width;
+ int m_height;
+ int m_nCaptionHeight;
+
+ DWORD m_colorTopLeft;
+ DWORD m_colorTopRight;
+ DWORD m_colorBottomLeft;
+ DWORD m_colorBottomRight;
+
+ CDXUTDialogResourceManager* m_pManager;
+ PCALLBACKDXUTGUIEVENT m_pCallbackEvent;
+ void* m_pCallbackEventUserContext;
+
+ std::vector<int> m_Textures; // Index into m_TextureCache;
+ std::vector<int> m_Fonts; // Index into m_FontCache;
+
+ std::vector<CDXUTControl*> m_Controls;
+ std::vector<DXUTElementHolder*> m_DefaultElements;
+
+ CDXUTElement m_CapElement; // Element for the caption
+
+ CDXUTDialog* m_pNextDialog;
+ CDXUTDialog* m_pPrevDialog;
+};
+
+
+//--------------------------------------------------------------------------------------
+// Structs for shared resources
+//--------------------------------------------------------------------------------------
+struct DXUTTextureNode
+{
+ bool bFileSource; // True if this texture is loaded from a file. False if from resource.
+ HMODULE hResourceModule;
+ int nResourceID; // Resource ID. If 0, string-based ID is used and stored in strFilename.
+ WCHAR strFilename[MAX_PATH];
+ DWORD dwWidth;
+ DWORD dwHeight;
+ ID3D11Texture2D* pTexture11;
+ ID3D11ShaderResourceView* pTexResView11;
+};
+
+struct DXUTFontNode
+{
+ WCHAR strFace[MAX_PATH];
+ LONG nHeight;
+ LONG nWeight;
+};
+
+struct DXUTSpriteVertex
+{
+ DirectX::XMFLOAT3 vPos;
+ DirectX::XMFLOAT4 vColor;
+ DirectX::XMFLOAT2 vTex;
+};
+
+
+//-----------------------------------------------------------------------------
+// Manages shared resources of dialogs
+//-----------------------------------------------------------------------------
+class CDXUTDialogResourceManager
+{
+public:
+ CDXUTDialogResourceManager();
+ ~CDXUTDialogResourceManager();
+
+ bool MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+ // D3D11 specific
+ HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext );
+ HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc );
+ void OnD3D11ReleasingSwapChain();
+ void OnD3D11DestroyDevice();
+ void StoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext );
+ void RestoreD3D11State( _In_ ID3D11DeviceContext* pd3dImmediateContext );
+ void ApplyRenderUI11( _In_ ID3D11DeviceContext* pd3dImmediateContext );
+ void ApplyRenderUIUntex11( _In_ ID3D11DeviceContext* pd3dImmediateContext );
+ void BeginSprites11( );
+ void EndSprites11( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext );
+
+ ID3D11Device* GetD3D11Device() const { return m_pd3d11Device; }
+ ID3D11DeviceContext* GetD3D11DeviceContext() const { return m_pd3d11DeviceContext; }
+
+ DXUTFontNode* GetFontNode( _In_ size_t iIndex ) const { return m_FontCache[ iIndex ]; }
+ DXUTTextureNode* GetTextureNode( _In_ size_t iIndex ) const { return m_TextureCache[ iIndex ]; }
+
+ int AddFont( _In_z_ LPCWSTR strFaceName, _In_ LONG height, _In_ LONG weight );
+ int AddTexture( _In_z_ LPCWSTR strFilename );
+ int AddTexture( _In_z_ LPCWSTR strResourceName, _In_ HMODULE hResourceModule );
+
+ bool RegisterDialog( _In_ CDXUTDialog* pDialog );
+ void UnregisterDialog( _In_ CDXUTDialog* pDialog );
+ void EnableKeyboardInputForAllDialogs();
+
+ // Shared between all dialogs
+
+ // D3D11
+ // Shaders
+ ID3D11VertexShader* m_pVSRenderUI11;
+ ID3D11PixelShader* m_pPSRenderUI11;
+ ID3D11PixelShader* m_pPSRenderUIUntex11;
+
+ // States
+ ID3D11DepthStencilState* m_pDepthStencilStateUI11;
+ ID3D11RasterizerState* m_pRasterizerStateUI11;
+ ID3D11BlendState* m_pBlendStateUI11;
+ ID3D11SamplerState* m_pSamplerStateUI11;
+
+ // Stored states
+ ID3D11DepthStencilState* m_pDepthStencilStateStored11;
+ UINT m_StencilRefStored11;
+ ID3D11RasterizerState* m_pRasterizerStateStored11;
+ ID3D11BlendState* m_pBlendStateStored11;
+ float m_BlendFactorStored11[4];
+ UINT m_SampleMaskStored11;
+ ID3D11SamplerState* m_pSamplerStateStored11;
+
+ ID3D11InputLayout* m_pInputLayout11;
+ ID3D11Buffer* m_pVBScreenQuad11;
+
+ // Sprite workaround
+ ID3D11Buffer* m_pSpriteBuffer11;
+ UINT m_SpriteBufferBytes11;
+ std::vector<DXUTSpriteVertex> m_SpriteVertices;
+
+ UINT m_nBackBufferWidth;
+ UINT m_nBackBufferHeight;
+
+ std::vector<CDXUTDialog*> m_Dialogs; // Dialogs registered
+
+protected:
+ // D3D11 specific
+ ID3D11Device* m_pd3d11Device;
+ ID3D11DeviceContext* m_pd3d11DeviceContext;
+ HRESULT CreateTexture11( _In_ UINT index );
+
+ std::vector<DXUTTextureNode*> m_TextureCache; // Shared textures
+ std::vector<DXUTFontNode*> m_FontCache; // Shared fonts
+};
+
+
+//-----------------------------------------------------------------------------
+// Base class for controls
+//-----------------------------------------------------------------------------
+class CDXUTControl
+{
+public:
+ CDXUTControl( _In_opt_ CDXUTDialog* pDialog = nullptr );
+ virtual ~CDXUTControl();
+
+ virtual HRESULT OnInit() { return S_OK; }
+ virtual void Refresh();
+ virtual void Render( _In_ float fElapsedTime ) { UNREFERENCED_PARAMETER(fElapsedTime); }
+
+ // Windows message handler
+ virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam )
+ {
+ UNREFERENCED_PARAMETER(uMsg);
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ return false;
+ }
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam )
+ {
+ UNREFERENCED_PARAMETER(uMsg);
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ return false;
+ }
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam )
+ {
+ UNREFERENCED_PARAMETER(uMsg);
+ UNREFERENCED_PARAMETER(pt);
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ return false;
+ }
+
+ virtual bool CanHaveFocus() { return false; }
+ virtual void OnFocusIn() { m_bHasFocus = true; }
+ virtual void OnFocusOut() { m_bHasFocus = false; }
+ virtual void OnMouseEnter() { m_bMouseOver = true; }
+ virtual void OnMouseLeave() { m_bMouseOver = false; }
+ virtual void OnHotkey() { }
+
+ virtual bool ContainsPoint( _In_ const POINT& pt ) { return PtInRect( &m_rcBoundingBox, pt ) != 0; }
+
+ virtual void SetEnabled( _In_ bool bEnabled ) { m_bEnabled = bEnabled; }
+ virtual bool GetEnabled() const { return m_bEnabled; }
+ virtual void SetVisible( _In_ bool bVisible ) { m_bVisible = bVisible; }
+ virtual bool GetVisible() const { return m_bVisible; }
+
+ UINT GetType() const { return m_Type; }
+
+ int GetID() const { return m_ID; }
+ void SetID( _In_ int ID ) { m_ID = ID; }
+
+ void SetLocation( _In_ int x, _In_ int y )
+ {
+ m_x = x;
+ m_y = y;
+ UpdateRects();
+ }
+ void SetSize( int width, int height )
+ {
+ m_width = width;
+ m_height = height;
+ UpdateRects();
+ }
+
+ void SetHotkey( _In_ UINT nHotkey ) { m_nHotkey = nHotkey; }
+ UINT GetHotkey() const { return m_nHotkey; }
+
+ void SetUserData( _In_opt_ void* pUserData ) { m_pUserData = pUserData; }
+ void* GetUserData() const { return m_pUserData; }
+
+ virtual void SetTextColor( _In_ DWORD Color );
+ CDXUTElement* GetElement( _In_ UINT iElement ) const { return m_Elements[ iElement ]; }
+ HRESULT SetElement( _In_ UINT iElement, _In_ CDXUTElement* pElement );
+
+ bool m_bVisible; // Shown/hidden flag
+ bool m_bMouseOver; // Mouse pointer is above control
+ bool m_bHasFocus; // Control has input focus
+ bool m_bIsDefault; // Is the default control
+
+ // Size, scale, and positioning members
+ int m_x, m_y;
+ int m_width, m_height;
+
+ // These members are set by the container
+ CDXUTDialog* m_pDialog; // Parent container
+ UINT m_Index; // Index within the control list
+
+ std::vector<CDXUTElement*> m_Elements; // All display elements
+
+protected:
+ virtual void UpdateRects();
+
+ int m_ID; // ID number
+ DXUT_CONTROL_TYPE m_Type; // Control type, set once in constructor
+ UINT m_nHotkey; // Virtual key code for this control's hotkey
+ void* m_pUserData; // Data associated with this control that is set by user.
+
+ bool m_bEnabled; // Enabled/disabled flag
+
+ RECT m_rcBoundingBox; // Rectangle defining the active region of the control
+};
+
+
+//-----------------------------------------------------------------------------
+// Contains all the display information for a given control type
+//-----------------------------------------------------------------------------
+struct DXUTElementHolder
+{
+ UINT nControlType;
+ UINT iElement;
+
+ CDXUTElement Element;
+};
+
+
+//-----------------------------------------------------------------------------
+// Static control
+//-----------------------------------------------------------------------------
+class CDXUTStatic : public CDXUTControl
+{
+public:
+ CDXUTStatic( _In_opt_ CDXUTDialog* pDialog = nullptr );
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+ virtual bool ContainsPoint( _In_ const POINT& pt ) override
+ {
+ UNREFERENCED_PARAMETER( pt );
+ return false;
+ }
+
+ HRESULT GetTextCopy( _Out_writes_(bufferCount) LPWSTR strDest, _In_ UINT bufferCount ) const;
+ LPCWSTR GetText() const { return m_strText; }
+ HRESULT SetText( _In_z_ LPCWSTR strText );
+
+protected:
+ WCHAR m_strText[MAX_PATH]; // Window text
+};
+
+
+//-----------------------------------------------------------------------------
+// Button control
+//-----------------------------------------------------------------------------
+class CDXUTButton : public CDXUTStatic
+{
+public:
+ CDXUTButton( _In_opt_ CDXUTDialog* pDialog = nullptr );
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void OnHotkey() override
+ {
+ if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this );
+ m_pDialog->SendEvent( EVENT_BUTTON_CLICKED, true, this );
+ }
+
+ virtual bool ContainsPoint( _In_ const POINT& pt ) override
+ {
+ return PtInRect( &m_rcBoundingBox, pt ) != 0;
+ }
+ virtual bool CanHaveFocus() override
+ {
+ return ( m_bVisible && m_bEnabled );
+ }
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+
+protected:
+ bool m_bPressed;
+};
+
+
+//-----------------------------------------------------------------------------
+// CheckBox control
+//-----------------------------------------------------------------------------
+class CDXUTCheckBox : public CDXUTButton
+{
+public:
+ CDXUTCheckBox( _In_opt_ CDXUTDialog* pDialog = nullptr );
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void OnHotkey() override
+ {
+ if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this );
+ SetCheckedInternal( !m_bChecked, true );
+ }
+
+ virtual bool ContainsPoint( _In_ const POINT& pt ) override;
+ virtual void UpdateRects() override;
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+
+ bool GetChecked() const { return m_bChecked; }
+ void SetChecked( _In_ bool bChecked ) { SetCheckedInternal( bChecked, false ); }
+
+protected:
+ virtual void SetCheckedInternal( _In_ bool bChecked, _In_ bool bFromInput );
+
+ bool m_bChecked;
+ RECT m_rcButton;
+ RECT m_rcText;
+};
+
+
+//-----------------------------------------------------------------------------
+// RadioButton control
+//-----------------------------------------------------------------------------
+class CDXUTRadioButton : public CDXUTCheckBox
+{
+public:
+ CDXUTRadioButton( _In_opt_ CDXUTDialog* pDialog = nullptr );
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void OnHotkey() override
+ {
+ if( m_pDialog->IsKeyboardInputEnabled() ) m_pDialog->RequestFocus( this );
+ SetCheckedInternal( true, true, true );
+ }
+
+ void SetChecked( _In_ bool bChecked, _In_ bool bClearGroup=true ) { SetCheckedInternal( bChecked, bClearGroup, false ); }
+ void SetButtonGroup( _In_ UINT nButtonGroup ) { m_nButtonGroup = nButtonGroup; }
+ UINT GetButtonGroup() const { return m_nButtonGroup; }
+
+protected:
+ virtual void SetCheckedInternal( _In_ bool bChecked, _In_ bool bClearGroup, _In_ bool bFromInput );
+ UINT m_nButtonGroup;
+};
+
+
+//-----------------------------------------------------------------------------
+// Scrollbar control
+//-----------------------------------------------------------------------------
+class CDXUTScrollBar : public CDXUTControl
+{
+public:
+ CDXUTScrollBar( _In_opt_ CDXUTDialog* pDialog = nullptr );
+ virtual ~CDXUTScrollBar();
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+ virtual void UpdateRects() override;
+
+ void SetTrackRange( _In_ int nStart, _In_ int nEnd );
+ int GetTrackPos() const { return m_nPosition; }
+ void SetTrackPos( _In_ int nPosition )
+ {
+ m_nPosition = nPosition;
+ Cap();
+ UpdateThumbRect();
+ }
+ int GetPageSize() const { return m_nPageSize; }
+ void SetPageSize( _In_ int nPageSize )
+ {
+ m_nPageSize = nPageSize;
+ Cap();
+ UpdateThumbRect();
+ }
+
+ void Scroll( _In_ int nDelta ); // Scroll by nDelta items (plus or minus)
+ void ShowItem( _In_ int nIndex ); // Ensure that item nIndex is displayed, scroll if necessary
+
+protected:
+ // ARROWSTATE indicates the state of the arrow buttons.
+ // CLEAR No arrow is down.
+ // CLICKED_UP Up arrow is clicked.
+ // CLICKED_DOWN Down arrow is clicked.
+ // HELD_UP Up arrow is held down for sustained period.
+ // HELD_DOWN Down arrow is held down for sustained period.
+ enum ARROWSTATE
+ {
+ CLEAR,
+ CLICKED_UP,
+ CLICKED_DOWN,
+ HELD_UP,
+ HELD_DOWN
+ };
+
+ void UpdateThumbRect();
+ void Cap(); // Clips position at boundaries. Ensures it stays within legal range.
+
+ bool m_bShowThumb;
+ bool m_bDrag;
+ RECT m_rcUpButton;
+ RECT m_rcDownButton;
+ RECT m_rcTrack;
+ RECT m_rcThumb;
+ int m_nPosition; // Position of the first displayed item
+ int m_nPageSize; // How many items are displayable in one page
+ int m_nStart; // First item
+ int m_nEnd; // The index after the last item
+ POINT m_LastMouse;// Last mouse position
+ ARROWSTATE m_Arrow; // State of the arrows
+ double m_dArrowTS; // Timestamp of last arrow event.
+};
+
+
+//-----------------------------------------------------------------------------
+// ListBox control
+//-----------------------------------------------------------------------------
+struct DXUTListBoxItem
+{
+ WCHAR strText[256];
+ void* pData;
+
+ RECT rcActive;
+ bool bSelected;
+};
+
+class CDXUTListBox : public CDXUTControl
+{
+public:
+ CDXUTListBox( _In_opt_ CDXUTDialog* pDialog = nullptr );
+ virtual ~CDXUTListBox();
+
+ virtual HRESULT OnInit() override
+ {
+ return m_pDialog->InitControl( &m_ScrollBar );
+ }
+ virtual bool CanHaveFocus() override
+ {
+ return ( m_bVisible && m_bEnabled );
+ }
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+ virtual void UpdateRects() override;
+
+ DWORD GetStyle() const { return m_dwStyle; }
+ size_t GetSize() const { return m_Items.size(); }
+ void SetStyle( _In_ DWORD dwStyle ) { m_dwStyle = dwStyle; }
+ int GetScrollBarWidth() const{ return m_nSBWidth; }
+ void SetScrollBarWidth( _In_ int nWidth )
+ {
+ m_nSBWidth = nWidth;
+ UpdateRects();
+ }
+ void SetBorder( _In_ int nBorder, _In_ int nMargin )
+ {
+ m_nBorder = nBorder;
+ m_nMargin = nMargin;
+ }
+ HRESULT AddItem( _In_z_ const WCHAR* wszText, _In_opt_ void* pData );
+ HRESULT InsertItem( _In_ int nIndex, _In_z_ const WCHAR* wszText, _In_opt_ void* pData );
+ void RemoveItem( _In_ int nIndex );
+ void RemoveAllItems();
+
+ DXUTListBoxItem* GetItem( _In_ int nIndex ) const;
+ int GetSelectedIndex( _In_ int nPreviousSelected = -1 ) const;
+ DXUTListBoxItem* GetSelectedItem( _In_ int nPreviousSelected = -1 ) const
+ {
+ return GetItem( GetSelectedIndex( nPreviousSelected ) );
+ }
+ void SelectItem( _In_ int nNewIndex );
+
+ enum STYLE
+ {
+ MULTISELECTION = 1
+ };
+
+protected:
+ RECT m_rcText; // Text rendering bound
+ RECT m_rcSelection; // Selection box bound
+ CDXUTScrollBar m_ScrollBar;
+ int m_nSBWidth;
+ int m_nBorder;
+ int m_nMargin;
+ int m_nTextHeight; // Height of a single line of text
+ DWORD m_dwStyle; // List box style
+ int m_nSelected; // Index of the selected item for single selection list box
+ int m_nSelStart; // Index of the item where selection starts (for handling multi-selection)
+ bool m_bDrag; // Whether the user is dragging the mouse to select
+
+ std::vector<DXUTListBoxItem*> m_Items;
+};
+
+
+//-----------------------------------------------------------------------------
+// ComboBox control
+//-----------------------------------------------------------------------------
+struct DXUTComboBoxItem
+{
+ WCHAR strText[256];
+ void* pData;
+
+ RECT rcActive;
+ bool bVisible;
+};
+
+class CDXUTComboBox : public CDXUTButton
+{
+public:
+ CDXUTComboBox( _In_opt_ CDXUTDialog* pDialog = nullptr );
+ virtual ~CDXUTComboBox();
+
+ virtual void SetTextColor( _In_ DWORD Color ) override;
+ virtual HRESULT OnInit() override
+ {
+ return m_pDialog->InitControl( &m_ScrollBar );
+ }
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void OnHotkey() override;
+
+ virtual bool CanHaveFocus() override
+ {
+ return ( m_bVisible && m_bEnabled );
+ }
+ virtual void OnFocusOut() override;
+ virtual void Render( _In_ float fElapsedTime ) override;
+
+ virtual void UpdateRects() override;
+
+ HRESULT AddItem( _In_z_ const WCHAR* strText, _In_opt_ void* pData );
+ void RemoveAllItems();
+ void RemoveItem( _In_ UINT index );
+ bool ContainsItem( _In_z_ const WCHAR* strText, _In_ UINT iStart=0 );
+ int FindItem( _In_z_ const WCHAR* strText, _In_ UINT iStart=0 ) const;
+ void* GetItemData( _In_z_ const WCHAR* strText ) const;
+ void* GetItemData( _In_ int nIndex ) const;
+ void SetDropHeight( _In_ UINT nHeight )
+ {
+ m_nDropHeight = nHeight;
+ UpdateRects();
+ }
+ int GetScrollBarWidth() const { return m_nSBWidth; }
+ void SetScrollBarWidth( _In_ int nWidth )
+ {
+ m_nSBWidth = nWidth;
+ UpdateRects();
+ }
+
+ int GetSelectedIndex() const { return m_iSelected; }
+ void* GetSelectedData() const;
+ DXUTComboBoxItem* GetSelectedItem() const;
+
+ UINT GetNumItems() { return static_cast<UINT>( m_Items.size() ); }
+ DXUTComboBoxItem* GetItem( _In_ UINT index ) { return m_Items[ index ]; }
+
+ HRESULT SetSelectedByIndex( _In_ UINT index );
+ HRESULT SetSelectedByText( _In_z_ const WCHAR* strText );
+ HRESULT SetSelectedByData( _In_ void* pData );
+
+protected:
+ int m_iSelected;
+ int m_iFocused;
+ int m_nDropHeight;
+ CDXUTScrollBar m_ScrollBar;
+ int m_nSBWidth;
+
+ bool m_bOpened;
+
+ RECT m_rcText;
+ RECT m_rcButton;
+ RECT m_rcDropdown;
+ RECT m_rcDropdownText;
+
+ std::vector<DXUTComboBoxItem*> m_Items;
+};
+
+
+//-----------------------------------------------------------------------------
+// Slider control
+//-----------------------------------------------------------------------------
+class CDXUTSlider : public CDXUTControl
+{
+public:
+ CDXUTSlider( _In_opt_ CDXUTDialog* pDialog = nullptr );
+
+ virtual bool ContainsPoint( _In_ const POINT& pt ) override;
+ virtual bool CanHaveFocus() override
+ {
+ return ( m_bVisible && m_bEnabled );
+ }
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+
+ virtual void UpdateRects() override;
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+
+ void SetValue( int nValue ) { SetValueInternal( nValue, false ); }
+ int GetValue() const { return m_nValue; }
+
+ void GetRange( _Out_ int& nMin, _Out_ int& nMax ) const
+ {
+ nMin = m_nMin;
+ nMax = m_nMax;
+ }
+ void SetRange( _In_ int nMin, _In_ int nMax );
+
+protected:
+ void SetValueInternal( _In_ int nValue, _In_ bool bFromInput );
+ int ValueFromPos( _In_ int x );
+
+ int m_nValue;
+
+ int m_nMin;
+ int m_nMax;
+
+ int m_nDragX; // Mouse position at start of drag
+ int m_nDragOffset; // Drag offset from the center of the button
+ int m_nButtonX;
+
+ bool m_bPressed;
+ RECT m_rcButton;
+};
+
+
+//-----------------------------------------------------------------------------
+// CUniBuffer class for the edit control
+//-----------------------------------------------------------------------------
+class CUniBuffer
+{
+public:
+ CUniBuffer( _In_ int nInitialSize = 1 );
+ ~CUniBuffer();
+
+ size_t GetBufferSize() const { return m_nBufferSize; }
+ bool SetBufferSize( _In_ int nSize );
+ int GetTextSize() const { return (int)wcslen( m_pwszBuffer ); }
+ const WCHAR* GetBuffer() const
+ {
+ return m_pwszBuffer;
+ }
+ const WCHAR& operator[]( _In_ int n ) const
+ {
+ return m_pwszBuffer[n];
+ }
+ WCHAR& operator[]( _In_ int n );
+ DXUTFontNode* GetFontNode() const { return m_pFontNode; }
+ void SetFontNode( _In_opt_ DXUTFontNode* pFontNode ) { m_pFontNode = pFontNode; }
+ void Clear();
+
+ bool InsertChar( _In_ int nIndex, _In_ WCHAR wChar );
+ // Inserts the char at specified index. If nIndex == -1, insert to the end.
+
+ bool RemoveChar( _In_ int nIndex );
+ // Removes the char at specified index. If nIndex == -1, remove the last char.
+
+ bool InsertString( _In_ int nIndex, _In_z_ const WCHAR* pStr, _In_ int nCount = -1 );
+ // Inserts the first nCount characters of the string pStr at specified index. If nCount == -1, the entire string is inserted. If nIndex == -1, insert to the end.
+
+ bool SetText( _In_z_ LPCWSTR wszText );
+
+ // Uniscribe
+ bool CPtoX( _In_ int nCP, _In_ bool bTrail, _Out_ int* pX );
+ bool XtoCP( _In_ int nX, _Out_ int* pCP, _Out_ int* pnTrail );
+ void GetPriorItemPos( _In_ int nCP, _Out_ int* pPrior );
+ void GetNextItemPos( _In_ int nCP, _Out_ int* pPrior );
+
+private:
+ HRESULT Analyse(); // Uniscribe -- Analyse() analyses the string in the buffer
+
+ WCHAR* m_pwszBuffer; // Buffer to hold text
+ int m_nBufferSize; // Size of the buffer allocated, in characters
+
+ // Uniscribe-specific
+ DXUTFontNode* m_pFontNode; // Font node for the font that this buffer uses
+ bool m_bAnalyseRequired; // True if the string has changed since last analysis.
+ SCRIPT_STRING_ANALYSIS m_Analysis; // Analysis for the current string
+};
+
+
+//-----------------------------------------------------------------------------
+// EditBox control
+//-----------------------------------------------------------------------------
+class CDXUTEditBox : public CDXUTControl
+{
+public:
+ CDXUTEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr );
+ virtual ~CDXUTEditBox();
+
+ virtual bool HandleKeyboard( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void UpdateRects() override;
+ virtual bool CanHaveFocus() override
+ {
+ return ( m_bVisible && m_bEnabled );
+ }
+ virtual void Render( _In_ float fElapsedTime ) override;
+ virtual void OnFocusIn() override;
+
+ void SetText( _In_z_ LPCWSTR wszText, _In_ bool bSelected = false );
+ LPCWSTR GetText() const { return m_Buffer.GetBuffer(); }
+ size_t GetTextLength() const { return m_Buffer.GetTextSize(); } // Returns text length in chars excluding nul.
+ HRESULT GetTextCopy( _Out_writes_(bufferCount) LPWSTR strDest, _In_ UINT bufferCount ) const;
+ void ClearText();
+
+ virtual void SetTextColor( _In_ DWORD Color ) override { m_TextColor = Color; } // Text color
+ void SetSelectedTextColor( _In_ DWORD Color ) { m_SelTextColor = Color; } // Selected text color
+ void SetSelectedBackColor( _In_ DWORD Color ) { m_SelBkColor = Color; } // Selected background color
+ void SetCaretColor( _In_ DWORD Color ) { m_CaretColor = Color; } // Caret color
+ void SetBorderWidth( _In_ int nBorder )
+ {
+ m_nBorder = nBorder;
+ UpdateRects();
+ } // Border of the window
+ void SetSpacing( _In_ int nSpacing )
+ {
+ m_nSpacing = nSpacing;
+ UpdateRects();
+ }
+ void ParseFloatArray( _In_reads_(nCount) float* pNumbers, _In_ int nCount );
+ void SetTextFloatArray( _In_reads_(nCount) const float* pNumbers, _In_ int nCount );
+
+protected:
+ void PlaceCaret( _In_ int nCP );
+ void DeleteSelectionText();
+ void ResetCaretBlink();
+ void CopyToClipboard();
+ void PasteFromClipboard();
+
+ CUniBuffer m_Buffer; // Buffer to hold text
+ int m_nBorder; // Border of the window
+ int m_nSpacing; // Spacing between the text and the edge of border
+ RECT m_rcText; // Bounding rectangle for the text
+ RECT m_rcRender[9]; // Convenient rectangles for rendering elements
+ double m_dfBlink; // Caret blink time in milliseconds
+ double m_dfLastBlink; // Last timestamp of caret blink
+ bool m_bCaretOn; // Flag to indicate whether caret is currently visible
+ int m_nCaret; // Caret position, in characters
+ bool m_bInsertMode; // If true, control is in insert mode. Else, overwrite mode.
+ int m_nSelStart; // Starting position of the selection. The caret marks the end.
+ int m_nFirstVisible;// First visible character in the edit control
+ DWORD m_TextColor; // Text color
+ DWORD m_SelTextColor; // Selected text color
+ DWORD m_SelBkColor; // Selected background color
+ DWORD m_CaretColor; // Caret color
+
+ // Mouse-specific
+ bool m_bMouseDrag; // True to indicate drag in progress
+
+ // Static
+ static bool s_bHideCaret; // If true, we don't render the caret.
+};
+
+
+//-----------------------------------------------------------------------------
+void BeginText11();
+void DrawText11DXUT( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext,
+ _In_z_ LPCWSTR strText, _In_ const RECT& rcScreen, _In_ DirectX::XMFLOAT4 vFontColor,
+ _In_ float fBBWidth, _In_ float fBBHeight, _In_ bool bCenter );
+void EndText11( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3d11DeviceContext );
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTguiIME.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTguiIME.h
new file mode 100644
index 0000000..9ceb59f
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTguiIME.h
@@ -0,0 +1,141 @@
+//--------------------------------------------------------------------------------------
+// File: DXUTguiIME.h
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+#include <usp10.h>
+#include <dimm.h>
+#include "ImeUi.h"
+
+//--------------------------------------------------------------------------------------
+// Forward declarations
+//--------------------------------------------------------------------------------------
+class CDXUTIMEEditBox;
+
+
+//-----------------------------------------------------------------------------
+// IME-enabled EditBox control
+//-----------------------------------------------------------------------------
+#define MAX_COMPSTRING_SIZE 256
+
+
+class CDXUTIMEEditBox : public CDXUTEditBox
+{
+public:
+
+ static HRESULT CreateIMEEditBox( _In_ CDXUTDialog* pDialog, _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width,
+ _In_ int height, _In_ bool bIsDefault=false, _Outptr_opt_ CDXUTIMEEditBox** ppCreated=nullptr );
+
+ CDXUTIMEEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr );
+ virtual ~CDXUTIMEEditBox();
+
+ static void InitDefaultElements( _In_ CDXUTDialog* pDialog );
+
+ static void WINAPI Initialize( _In_ HWND hWnd );
+ static void WINAPI Uninitialize();
+
+ static HRESULT WINAPI StaticOnCreateDevice();
+ static bool WINAPI StaticMsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+ static void WINAPI SetImeEnableFlag( _In_ bool bFlag );
+
+ virtual void Render( _In_ float fElapsedTime ) override;
+ virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override;
+ virtual void UpdateRects() override;
+ virtual void OnFocusIn() override;
+ virtual void OnFocusOut() override;
+
+ void PumpMessage();
+
+ virtual void RenderCandidateReadingWindow( _In_ bool bReading );
+ virtual void RenderComposition();
+ virtual void RenderIndicator( _In_ float fElapsedTime );
+
+protected:
+ static void WINAPI EnableImeSystem( _In_ bool bEnable );
+
+ static WORD WINAPI GetLanguage()
+ {
+ return ImeUi_GetLanguage();
+ }
+ static WORD WINAPI GetPrimaryLanguage()
+ {
+ return ImeUi_GetPrimaryLanguage();
+ }
+ static void WINAPI SendKey( _In_ BYTE nVirtKey );
+ static DWORD WINAPI GetImeId( _In_ UINT uIndex = 0 )
+ {
+ return ImeUi_GetImeId( uIndex );
+ };
+ static void WINAPI CheckInputLocale();
+ static void WINAPI CheckToggleState();
+ static void WINAPI SetupImeApi();
+ static void WINAPI ResetCompositionString();
+
+
+ static void SetupImeUiCallback();
+
+protected:
+ enum
+ {
+ INDICATOR_NON_IME,
+ INDICATOR_CHS,
+ INDICATOR_CHT,
+ INDICATOR_KOREAN,
+ INDICATOR_JAPANESE
+ };
+
+ struct CCandList
+ {
+ CUniBuffer HoriCand; // Candidate list string (for horizontal candidate window)
+ int nFirstSelected; // First character position of the selected string in HoriCand
+ int nHoriSelectedLen; // Length of the selected string in HoriCand
+ RECT rcCandidate; // Candidate rectangle computed and filled each time before rendered
+ };
+
+ static POINT s_ptCompString; // Composition string position. Updated every frame.
+ static int s_nFirstTargetConv; // Index of the first target converted char in comp string. If none, -1.
+ static CUniBuffer s_CompString; // Buffer to hold the composition string (we fix its length)
+ static DWORD s_adwCompStringClause[MAX_COMPSTRING_SIZE];
+ static CCandList s_CandList; // Data relevant to the candidate list
+ static WCHAR s_wszReadingString[32];// Used only with horizontal reading window (why?)
+ static bool s_bImeFlag; // Is ime enabled
+
+ // Color of various IME elements
+ DWORD m_ReadingColor; // Reading string color
+ DWORD m_ReadingWinColor; // Reading window color
+ DWORD m_ReadingSelColor; // Selected character in reading string
+ DWORD m_ReadingSelBkColor; // Background color for selected char in reading str
+ DWORD m_CandidateColor; // Candidate string color
+ DWORD m_CandidateWinColor; // Candidate window color
+ DWORD m_CandidateSelColor; // Selected candidate string color
+ DWORD m_CandidateSelBkColor; // Selected candidate background color
+ DWORD m_CompColor; // Composition string color
+ DWORD m_CompWinColor; // Composition string window color
+ DWORD m_CompCaretColor; // Composition string caret color
+ DWORD m_CompTargetColor; // Composition string target converted color
+ DWORD m_CompTargetBkColor; // Composition string target converted background
+ DWORD m_CompTargetNonColor; // Composition string target non-converted color
+ DWORD m_CompTargetNonBkColor;// Composition string target non-converted background
+ DWORD m_IndicatorImeColor; // Indicator text color for IME
+ DWORD m_IndicatorEngColor; // Indicator text color for English
+ DWORD m_IndicatorBkColor; // Indicator text background color
+
+ // Edit-control-specific data
+ int m_nIndicatorWidth; // Width of the indicator symbol
+ RECT m_rcIndicator; // Rectangle for drawing the indicator button
+
+#if defined(DEBUG) || defined(_DEBUG)
+ static bool m_bIMEStaticMsgProcCalled;
+#endif
+};
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTres.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTres.h
new file mode 100644
index 0000000..ffd1de2
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTres.h
@@ -0,0 +1,17 @@
+//----------------------------------------------------------------------------
+// File: dxutres.h
+//
+// Functions to create DXUT media from arrays in memory
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//-----------------------------------------------------------------------------
+#pragma once
+
+HRESULT WINAPI DXUTCreateGUITextureFromInternalArray( _In_ ID3D11Device* pd3dDevice, _Outptr_ ID3D11Texture2D** ppTexture );
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTsettingsdlg.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTsettingsdlg.h
new file mode 100644
index 0000000..92d2752
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/DXUTsettingsdlg.h
@@ -0,0 +1,173 @@
+//--------------------------------------------------------------------------------------
+// File: DXUTSettingsDlg.h
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+//--------------------------------------------------------------------------------------
+// Header Includes
+//--------------------------------------------------------------------------------------
+#include "DXUTgui.h"
+
+//--------------------------------------------------------------------------------------
+// Control IDs
+//--------------------------------------------------------------------------------------
+#define DXUTSETTINGSDLG_STATIC -1
+#define DXUTSETTINGSDLG_OK 1
+#define DXUTSETTINGSDLG_CANCEL 2
+#define DXUTSETTINGSDLG_ADAPTER 3
+#define DXUTSETTINGSDLG_DEVICE_TYPE 4
+#define DXUTSETTINGSDLG_WINDOWED 5
+#define DXUTSETTINGSDLG_FULLSCREEN 6
+#define DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL 26
+#define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT 28
+#define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL 29
+#define DXUTSETTINGSDLG_D3D11_RESOLUTION 30
+#define DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL 31
+#define DXUTSETTINGSDLG_D3D11_REFRESH_RATE 32
+#define DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL 33
+#define DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT 34
+#define DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL 35
+#define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT 36
+#define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL 37
+#define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY 38
+#define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL 39
+#define DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL 40
+#define DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL 41
+#define DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE 42
+#define DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL 43
+#define DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL 44
+
+#define DXUTSETTINGSDLG_MODE_CHANGE_ACCEPT 58
+#define DXUTSETTINGSDLG_MODE_CHANGE_REVERT 59
+#define DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT 60
+#define DXUTSETTINGSDLG_WINDOWED_GROUP 0x0100
+
+#ifdef USE_DIRECT3D11_3
+#define TOTAL_FEATURE_LEVELS 9
+#else
+#define TOTAL_FEATURE_LEVELS 7
+#endif
+
+//--------------------------------------------------------------------------------------
+// Dialog for selection of device settings
+// Use DXUTGetD3DSettingsDialog() to access global instance
+// To control the contents of the dialog, use the CD3D11Enumeration class.
+//--------------------------------------------------------------------------------------
+class CD3DSettingsDlg
+{
+public:
+ CD3DSettingsDlg();
+ ~CD3DSettingsDlg();
+
+ void Init( _In_ CDXUTDialogResourceManager* pManager );
+ void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR szControlTextureFileName );
+ void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR pszControlTextureResourcename,
+ _In_ HMODULE hModule );
+
+ HRESULT Refresh();
+ void OnRender( _In_ float fElapsedTime );
+
+ HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice );
+ HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice,
+ _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc );
+ void OnD3D11DestroyDevice();
+
+ CDXUTDialog* GetDialogControl() { return &m_Dialog; }
+ bool IsActive() const { return m_bActive; }
+ void SetActive( _In_ bool bActive )
+ {
+ m_bActive = bActive;
+ if( bActive ) Refresh();
+ }
+
+ LRESULT MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam );
+
+protected:
+ friend CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog();
+
+ void CreateControls();
+ void SetSelectedD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate );
+ HRESULT UpdateD3D11Resolutions();
+ HRESULT UpdateD3D11RefreshRates();
+
+ void OnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl );
+
+ static void WINAPI StaticOnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl, _In_opt_ void* pUserData );
+ static void WINAPI StaticOnModeChangeTimer( _In_ UINT nIDEvent, _In_opt_ void* pUserContext );
+
+ CD3D11EnumAdapterInfo* GetCurrentD3D11AdapterInfo() const;
+ CD3D11EnumDeviceInfo* GetCurrentD3D11DeviceInfo() const;
+ CD3D11EnumOutputInfo* GetCurrentD3D11OutputInfo() const;
+ CD3D11EnumDeviceSettingsCombo* GetCurrentD3D11DeviceSettingsCombo() const;
+
+ void AddAdapter( _In_z_ const WCHAR* strDescription, _In_ UINT iAdapter );
+ UINT GetSelectedAdapter() const;
+
+ void SetWindowed( _In_ bool bWindowed );
+ bool IsWindowed() const;
+
+ // D3D11
+ void AddD3D11DeviceType( _In_ D3D_DRIVER_TYPE devType );
+ D3D_DRIVER_TYPE GetSelectedD3D11DeviceType() const;
+
+ void AddD3D11AdapterOutput( _In_z_ const WCHAR* strName, _In_ UINT nOutput );
+ UINT GetSelectedD3D11AdapterOutput() const;
+
+ void AddD3D11Resolution( _In_ DWORD dwWidth, _In_ DWORD dwHeight );
+ void GetSelectedD3D11Resolution( _Out_ DWORD* pdwWidth, _Out_ DWORD* pdwHeight ) const;
+
+ void AddD3D11FeatureLevel( _In_ D3D_FEATURE_LEVEL fl );
+ D3D_FEATURE_LEVEL GetSelectedFeatureLevel() const;
+
+ void AddD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate );
+ DXGI_RATIONAL GetSelectedD3D11RefreshRate() const;
+
+ void AddD3D11BackBufferFormat( _In_ DXGI_FORMAT format );
+ DXGI_FORMAT GetSelectedD3D11BackBufferFormat() const;
+
+ void AddD3D11MultisampleCount( _In_ UINT count );
+ UINT GetSelectedD3D11MultisampleCount() const;
+
+ void AddD3D11MultisampleQuality( _In_ UINT Quality );
+ UINT GetSelectedD3D11MultisampleQuality() const;
+
+ DWORD GetSelectedD3D11PresentInterval() const;
+ bool GetSelectedDebugDeviceValue() const;
+
+ HRESULT OnD3D11ResolutionChanged ();
+ HRESULT OnFeatureLevelChanged();
+ HRESULT OnAdapterChanged();
+ HRESULT OnDeviceTypeChanged();
+ HRESULT OnWindowedFullScreenChanged();
+ HRESULT OnAdapterOutputChanged();
+ HRESULT OnRefreshRateChanged();
+ HRESULT OnBackBufferFormatChanged();
+ HRESULT OnMultisampleTypeChanged();
+ HRESULT OnMultisampleQualityChanged();
+ HRESULT OnPresentIntervalChanged();
+ HRESULT OnDebugDeviceChanged();
+
+ void UpdateModeChangeTimeoutText( _In_ int nSecRemaining );
+
+ CDXUTDialog* m_pActiveDialog;
+ CDXUTDialog m_Dialog;
+ CDXUTDialog m_RevertModeDialog;
+ int m_nRevertModeTimeout;
+ UINT m_nIDEvent;
+ bool m_bActive;
+
+ D3D_FEATURE_LEVEL m_Levels[TOTAL_FEATURE_LEVELS];
+
+};
+
+
+CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog();
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/ImeUi.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/ImeUi.h
new file mode 100644
index 0000000..fdb33f3
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/ImeUi.h
@@ -0,0 +1,126 @@
+//--------------------------------------------------------------------------------------
+// File: ImeUi.h
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+#include <windows.h>
+
+class CImeUiFont_Base
+{
+public:
+ virtual void SetHeight( _In_ UINT uHeight )
+ {
+ UNREFERENCED_PARAMETER(uHeight);
+ }; // for backward compatibility
+ virtual void SetColor( _In_ DWORD color ) = 0;
+ virtual void SetPosition( _In_ int x, _In_ int y ) = 0;
+ virtual void GetTextExtent( _In_z_ LPCTSTR szText, _Out_ DWORD* puWidth, _Out_ DWORD* puHeight ) = 0;
+ virtual void DrawText( _In_z_ LPCTSTR pszText ) = 0;
+};
+
+typedef struct
+{
+ // symbol (Henkan-kyu)
+ DWORD symbolColor;
+ DWORD symbolColorOff;
+ DWORD symbolColorText;
+ BYTE symbolHeight;
+ BYTE symbolTranslucence;
+ BYTE symbolPlacement;
+ CImeUiFont_Base* symbolFont;
+
+ // candidate list
+ DWORD candColorBase;
+ DWORD candColorBorder;
+ DWORD candColorText;
+
+ // composition string
+ DWORD compColorInput;
+ DWORD compColorTargetConv;
+ DWORD compColorConverted;
+ DWORD compColorTargetNotConv;
+ DWORD compColorInputErr;
+ BYTE compTranslucence;
+ DWORD compColorText;
+
+ // caret
+ BYTE caretWidth;
+ BYTE caretYMargin;
+} IMEUI_APPEARANCE;
+
+typedef struct // D3DTLVERTEX compatible
+{
+ float sx;
+ float sy;
+ float sz;
+ float rhw;
+ DWORD color;
+ DWORD specular;
+ float tu;
+ float tv;
+} IMEUI_VERTEX;
+
+// IME States
+#define IMEUI_STATE_OFF 0
+#define IMEUI_STATE_ON 1
+#define IMEUI_STATE_ENGLISH 2
+
+// IME const
+#define MAX_CANDLIST 10
+
+// IME Flags
+#define IMEUI_FLAG_SUPPORT_CARET 0x00000001
+
+bool ImeUi_Initialize( _In_ HWND hwnd, _In_ bool bDisable = false );
+void ImeUi_Uninitialize();
+void ImeUi_SetAppearance( _In_opt_ const IMEUI_APPEARANCE* pia );
+void ImeUi_GetAppearance( _Out_opt_ IMEUI_APPEARANCE* pia );
+bool ImeUi_IgnoreHotKey( _In_ const MSG* pmsg );
+LPARAM ImeUi_ProcessMessage( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _Inout_ LPARAM& lParam, _Out_ bool* trapped );
+void ImeUi_SetScreenDimension( _In_ UINT width, _In_ UINT height );
+void ImeUi_RenderUI( _In_ bool bDrawCompAttr = true, _In_ bool bDrawOtherUi = true );
+void ImeUi_SetCaretPosition( _In_ UINT x, _In_ UINT y );
+void ImeUi_SetCompStringAppearance( _In_ CImeUiFont_Base* pFont, _In_ DWORD color, _In_ const RECT* prc );
+bool ImeUi_GetCaretStatus();
+void ImeUi_SetInsertMode( _In_ bool bInsert );
+void ImeUi_SetState( _In_ DWORD dwState );
+DWORD ImeUi_GetState();
+void ImeUi_EnableIme( _In_ bool bEnable );
+bool ImeUi_IsEnabled();
+void ImeUi_FinalizeString( _In_ bool bSend = false );
+void ImeUi_ToggleLanguageBar( _In_ BOOL bRestore );
+bool ImeUi_IsSendingKeyMessage();
+void ImeUi_SetWindow( _In_ HWND hwnd );
+UINT ImeUi_GetInputCodePage();
+DWORD ImeUi_GetFlags();
+void ImeUi_SetFlags( _In_ DWORD dwFlags, _In_ bool bSet );
+
+WORD ImeUi_GetPrimaryLanguage();
+DWORD ImeUi_GetImeId( _In_ UINT uIndex );
+WORD ImeUi_GetLanguage();
+LPTSTR ImeUi_GetIndicatior();
+bool ImeUi_IsShowReadingWindow();
+bool ImeUi_IsShowCandListWindow();
+bool ImeUi_IsVerticalCand();
+bool ImeUi_IsHorizontalReading();
+TCHAR* ImeUi_GetCandidate( _In_ UINT idx );
+TCHAR* ImeUi_GetCompositionString();
+DWORD ImeUi_GetCandidateSelection();
+DWORD ImeUi_GetCandidateCount();
+BYTE* ImeUi_GetCompStringAttr();
+DWORD ImeUi_GetImeCursorChars();
+
+extern void ( CALLBACK*ImeUiCallback_DrawRect )( _In_ int x1, _In_ int y1, _In_ int x2, _In_ int y2, _In_ DWORD color );
+extern void* ( __cdecl*ImeUiCallback_Malloc )( _In_ size_t bytes );
+extern void ( __cdecl*ImeUiCallback_Free )( _In_ void* ptr );
+extern void ( CALLBACK*ImeUiCallback_DrawFans )( _In_ const IMEUI_VERTEX* paVertex, _In_ UINT uNum );
+extern void ( CALLBACK*ImeUiCallback_OnChar )( _In_ WCHAR wc );
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmesh.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmesh.h
new file mode 100644
index 0000000..499d707
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmesh.h
@@ -0,0 +1,460 @@
+//--------------------------------------------------------------------------------------
+// File: SDKMesh.h
+//
+// Disclaimer:
+// The SDK Mesh format (.sdkmesh) is not a recommended file format for shipping titles.
+// It was designed to meet the specific needs of the SDK samples. Any real-world
+// applications should avoid this file format in favor of a destination format that
+// meets the specific needs of the application.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+#undef D3DCOLOR_ARGB
+#include <d3d9.h>
+
+//--------------------------------------------------------------------------------------
+// Hard Defines for the various structures
+//--------------------------------------------------------------------------------------
+#define SDKMESH_FILE_VERSION 101
+#define MAX_VERTEX_ELEMENTS 32
+#define MAX_VERTEX_STREAMS 16
+#define MAX_FRAME_NAME 100
+#define MAX_MESH_NAME 100
+#define MAX_SUBSET_NAME 100
+#define MAX_MATERIAL_NAME 100
+#define MAX_TEXTURE_NAME MAX_PATH
+#define MAX_MATERIAL_PATH MAX_PATH
+#define INVALID_FRAME ((UINT)-1)
+#define INVALID_MESH ((UINT)-1)
+#define INVALID_MATERIAL ((UINT)-1)
+#define INVALID_SUBSET ((UINT)-1)
+#define INVALID_ANIMATION_DATA ((UINT)-1)
+#define INVALID_SAMPLER_SLOT ((UINT)-1)
+#define ERROR_RESOURCE_VALUE 1
+
+template<typename TYPE> BOOL IsErrorResource( TYPE data )
+{
+ if( ( TYPE )ERROR_RESOURCE_VALUE == data )
+ return TRUE;
+ return FALSE;
+}
+//--------------------------------------------------------------------------------------
+// Enumerated Types.
+//--------------------------------------------------------------------------------------
+enum SDKMESH_PRIMITIVE_TYPE
+{
+ PT_TRIANGLE_LIST = 0,
+ PT_TRIANGLE_STRIP,
+ PT_LINE_LIST,
+ PT_LINE_STRIP,
+ PT_POINT_LIST,
+ PT_TRIANGLE_LIST_ADJ,
+ PT_TRIANGLE_STRIP_ADJ,
+ PT_LINE_LIST_ADJ,
+ PT_LINE_STRIP_ADJ,
+ PT_QUAD_PATCH_LIST,
+ PT_TRIANGLE_PATCH_LIST,
+};
+
+enum SDKMESH_INDEX_TYPE
+{
+ IT_16BIT = 0,
+ IT_32BIT,
+};
+
+enum FRAME_TRANSFORM_TYPE
+{
+ FTT_RELATIVE = 0,
+ FTT_ABSOLUTE, //This is not currently used but is here to support absolute transformations in the future
+};
+
+//--------------------------------------------------------------------------------------
+// Structures. Unions with pointers are forced to 64bit.
+//--------------------------------------------------------------------------------------
+#pragma pack(push,8)
+
+struct SDKMESH_HEADER
+{
+ //Basic Info and sizes
+ UINT Version;
+ BYTE IsBigEndian;
+ UINT64 HeaderSize;
+ UINT64 NonBufferDataSize;
+ UINT64 BufferDataSize;
+
+ //Stats
+ UINT NumVertexBuffers;
+ UINT NumIndexBuffers;
+ UINT NumMeshes;
+ UINT NumTotalSubsets;
+ UINT NumFrames;
+ UINT NumMaterials;
+
+ //Offsets to Data
+ UINT64 VertexStreamHeadersOffset;
+ UINT64 IndexStreamHeadersOffset;
+ UINT64 MeshDataOffset;
+ UINT64 SubsetDataOffset;
+ UINT64 FrameDataOffset;
+ UINT64 MaterialDataOffset;
+};
+
+struct SDKMESH_VERTEX_BUFFER_HEADER
+{
+ UINT64 NumVertices;
+ UINT64 SizeBytes;
+ UINT64 StrideBytes;
+ D3DVERTEXELEMENT9 Decl[MAX_VERTEX_ELEMENTS];
+ union
+ {
+ UINT64 DataOffset; //(This also forces the union to 64bits)
+ ID3D11Buffer* pVB11;
+ };
+};
+
+struct SDKMESH_INDEX_BUFFER_HEADER
+{
+ UINT64 NumIndices;
+ UINT64 SizeBytes;
+ UINT IndexType;
+ union
+ {
+ UINT64 DataOffset; //(This also forces the union to 64bits)
+ ID3D11Buffer* pIB11;
+ };
+};
+
+struct SDKMESH_MESH
+{
+ char Name[MAX_MESH_NAME];
+ BYTE NumVertexBuffers;
+ UINT VertexBuffers[MAX_VERTEX_STREAMS];
+ UINT IndexBuffer;
+ UINT NumSubsets;
+ UINT NumFrameInfluences; //aka bones
+
+ DirectX::XMFLOAT3 BoundingBoxCenter;
+ DirectX::XMFLOAT3 BoundingBoxExtents;
+
+ union
+ {
+ UINT64 SubsetOffset; //Offset to list of subsets (This also forces the union to 64bits)
+ UINT* pSubsets; //Pointer to list of subsets
+ };
+ union
+ {
+ UINT64 FrameInfluenceOffset; //Offset to list of frame influences (This also forces the union to 64bits)
+ UINT* pFrameInfluences; //Pointer to list of frame influences
+ };
+};
+
+struct SDKMESH_SUBSET
+{
+ char Name[MAX_SUBSET_NAME];
+ UINT MaterialID;
+ UINT PrimitiveType;
+ UINT64 IndexStart;
+ UINT64 IndexCount;
+ UINT64 VertexStart;
+ UINT64 VertexCount;
+};
+
+struct SDKMESH_FRAME
+{
+ char Name[MAX_FRAME_NAME];
+ UINT Mesh;
+ UINT ParentFrame;
+ UINT ChildFrame;
+ UINT SiblingFrame;
+ DirectX::XMFLOAT4X4 Matrix;
+ UINT AnimationDataIndex; //Used to index which set of keyframes transforms this frame
+};
+
+struct SDKMESH_MATERIAL
+{
+ char Name[MAX_MATERIAL_NAME];
+
+ // Use MaterialInstancePath
+ char MaterialInstancePath[MAX_MATERIAL_PATH];
+
+ // Or fall back to d3d8-type materials
+ char DiffuseTexture[MAX_TEXTURE_NAME];
+ char NormalTexture[MAX_TEXTURE_NAME];
+ char SpecularTexture[MAX_TEXTURE_NAME];
+
+ DirectX::XMFLOAT4 Diffuse;
+ DirectX::XMFLOAT4 Ambient;
+ DirectX::XMFLOAT4 Specular;
+ DirectX::XMFLOAT4 Emissive;
+ float Power;
+
+ union
+ {
+ UINT64 Force64_1; //Force the union to 64bits
+ ID3D11Texture2D* pDiffuseTexture11;
+ };
+ union
+ {
+ UINT64 Force64_2; //Force the union to 64bits
+ ID3D11Texture2D* pNormalTexture11;
+ };
+ union
+ {
+ UINT64 Force64_3; //Force the union to 64bits
+ ID3D11Texture2D* pSpecularTexture11;
+ };
+
+ union
+ {
+ UINT64 Force64_4; //Force the union to 64bits
+ ID3D11ShaderResourceView* pDiffuseRV11;
+ };
+ union
+ {
+ UINT64 Force64_5; //Force the union to 64bits
+ ID3D11ShaderResourceView* pNormalRV11;
+ };
+ union
+ {
+ UINT64 Force64_6; //Force the union to 64bits
+ ID3D11ShaderResourceView* pSpecularRV11;
+ };
+
+};
+
+struct SDKANIMATION_FILE_HEADER
+{
+ UINT Version;
+ BYTE IsBigEndian;
+ UINT FrameTransformType;
+ UINT NumFrames;
+ UINT NumAnimationKeys;
+ UINT AnimationFPS;
+ UINT64 AnimationDataSize;
+ UINT64 AnimationDataOffset;
+};
+
+struct SDKANIMATION_DATA
+{
+ DirectX::XMFLOAT3 Translation;
+ DirectX::XMFLOAT4 Orientation;
+ DirectX::XMFLOAT3 Scaling;
+};
+
+struct SDKANIMATION_FRAME_DATA
+{
+ char FrameName[MAX_FRAME_NAME];
+ union
+ {
+ UINT64 DataOffset;
+ SDKANIMATION_DATA* pAnimationData;
+ };
+};
+
+#pragma pack(pop)
+
+static_assert( sizeof(D3DVERTEXELEMENT9) == 8, "Direct3D9 Decl structure size incorrect" );
+static_assert( sizeof(SDKMESH_HEADER)== 104, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKMESH_VERTEX_BUFFER_HEADER) == 288, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKMESH_INDEX_BUFFER_HEADER) == 32, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKMESH_MESH) == 224, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKMESH_SUBSET) == 144, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKMESH_FRAME) == 184, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKMESH_MATERIAL) == 1256, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKANIMATION_FILE_HEADER) == 40, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKANIMATION_DATA) == 40, "SDK Mesh structure size incorrect" );
+static_assert( sizeof(SDKANIMATION_FRAME_DATA) == 112, "SDK Mesh structure size incorrect" );
+
+#ifndef _CONVERTER_APP_
+
+//--------------------------------------------------------------------------------------
+// AsyncLoading callbacks
+//--------------------------------------------------------------------------------------
+typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE11 )( _In_ ID3D11Device* pDev, _In_z_ char* szFileName,
+ _Outptr_ ID3D11ShaderResourceView** ppRV, _In_opt_ void* pContext );
+typedef void ( CALLBACK*LPCREATEVERTEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer,
+ _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext );
+typedef void ( CALLBACK*LPCREATEINDEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer,
+ _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext );
+struct SDKMESH_CALLBACKS11
+{
+ LPCREATETEXTUREFROMFILE11 pCreateTextureFromFile;
+ LPCREATEVERTEXBUFFER11 pCreateVertexBuffer;
+ LPCREATEINDEXBUFFER11 pCreateIndexBuffer;
+ void* pContext;
+};
+
+//--------------------------------------------------------------------------------------
+// CDXUTSDKMesh class. This class reads the sdkmesh file format for use by the samples
+//--------------------------------------------------------------------------------------
+class CDXUTSDKMesh
+{
+private:
+ UINT m_NumOutstandingResources;
+ bool m_bLoading;
+ //BYTE* m_pBufferData;
+ HANDLE m_hFile;
+ HANDLE m_hFileMappingObject;
+ std::vector<BYTE*> m_MappedPointers;
+ ID3D11Device* m_pDev11;
+ ID3D11DeviceContext* m_pDevContext11;
+
+protected:
+ //These are the pointers to the two chunks of data loaded in from the mesh file
+ BYTE* m_pStaticMeshData;
+ BYTE* m_pHeapData;
+ BYTE* m_pAnimationData;
+ BYTE** m_ppVertices;
+ BYTE** m_ppIndices;
+
+ //Keep track of the path
+ WCHAR m_strPathW[MAX_PATH];
+ char m_strPath[MAX_PATH];
+
+ //General mesh info
+ SDKMESH_HEADER* m_pMeshHeader;
+ SDKMESH_VERTEX_BUFFER_HEADER* m_pVertexBufferArray;
+ SDKMESH_INDEX_BUFFER_HEADER* m_pIndexBufferArray;
+ SDKMESH_MESH* m_pMeshArray;
+ SDKMESH_SUBSET* m_pSubsetArray;
+ SDKMESH_FRAME* m_pFrameArray;
+ SDKMESH_MATERIAL* m_pMaterialArray;
+
+ // Adjacency information (not part of the m_pStaticMeshData, so it must be created and destroyed separately )
+ SDKMESH_INDEX_BUFFER_HEADER* m_pAdjacencyIndexBufferArray;
+
+ //Animation
+ SDKANIMATION_FILE_HEADER* m_pAnimationHeader;
+ SDKANIMATION_FRAME_DATA* m_pAnimationFrameData;
+ DirectX::XMFLOAT4X4* m_pBindPoseFrameMatrices;
+ DirectX::XMFLOAT4X4* m_pTransformedFrameMatrices;
+ DirectX::XMFLOAT4X4* m_pWorldPoseFrameMatrices;
+
+protected:
+ void LoadMaterials( _In_ ID3D11Device* pd3dDevice, _In_reads_(NumMaterials) SDKMESH_MATERIAL* pMaterials,
+ _In_ UINT NumMaterials, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr );
+
+ HRESULT CreateVertexBuffer( _In_ ID3D11Device* pd3dDevice,
+ _In_ SDKMESH_VERTEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pVertices,
+ _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr );
+
+ HRESULT CreateIndexBuffer( _In_ ID3D11Device* pd3dDevice,
+ _In_ SDKMESH_INDEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pIndices,
+ _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr );
+
+ virtual HRESULT CreateFromFile( _In_opt_ ID3D11Device* pDev11,
+ _In_z_ LPCWSTR szFileName,
+ _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr );
+
+ virtual HRESULT CreateFromMemory( _In_opt_ ID3D11Device* pDev11,
+ _In_reads_(DataBytes) BYTE* pData,
+ _In_ size_t DataBytes,
+ _In_ bool bCopyStatic,
+ _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr );
+
+ //frame manipulation
+ void TransformBindPoseFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld );
+ void TransformFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld, _In_ double fTime );
+ void TransformFrameAbsolute( _In_ UINT iFrame, _In_ double fTime );
+
+ //Direct3D 11 rendering helpers
+ void RenderMesh( _In_ UINT iMesh,
+ _In_ bool bAdjacent,
+ _In_ ID3D11DeviceContext* pd3dDeviceContext,
+ _In_ UINT iDiffuseSlot,
+ _In_ UINT iNormalSlot,
+ _In_ UINT iSpecularSlot );
+ void RenderFrame( _In_ UINT iFrame,
+ _In_ bool bAdjacent,
+ _In_ ID3D11DeviceContext* pd3dDeviceContext,
+ _In_ UINT iDiffuseSlot,
+ _In_ UINT iNormalSlot,
+ _In_ UINT iSpecularSlot );
+
+public:
+ CDXUTSDKMesh();
+ virtual ~CDXUTSDKMesh();
+
+ virtual HRESULT Create( _In_ ID3D11Device* pDev11, _In_z_ LPCWSTR szFileName, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr );
+ virtual HRESULT Create( _In_ ID3D11Device* pDev11, BYTE* pData, size_t DataBytes, _In_ bool bCopyStatic=false,
+ _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr );
+ virtual HRESULT LoadAnimation( _In_z_ const WCHAR* szFileName );
+ virtual void Destroy();
+
+ //Frame manipulation
+ void TransformBindPose( _In_ DirectX::CXMMATRIX world ) { TransformBindPoseFrame( 0, world ); };
+ void TransformMesh( _In_ DirectX::CXMMATRIX world, _In_ double fTime );
+
+ //Direct3D 11 Rendering
+ virtual void Render( _In_ ID3D11DeviceContext* pd3dDeviceContext,
+ _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT,
+ _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT,
+ _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT );
+ virtual void RenderAdjacent( _In_ ID3D11DeviceContext* pd3dDeviceContext,
+ _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT,
+ _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT,
+ _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT );
+
+ //Helpers (D3D11 specific)
+ static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType11( _In_ SDKMESH_PRIMITIVE_TYPE PrimType );
+ DXGI_FORMAT GetIBFormat11( _In_ UINT iMesh ) const;
+ ID3D11Buffer* GetVB11( _In_ UINT iMesh, _In_ UINT iVB ) const;
+ ID3D11Buffer* GetIB11( _In_ UINT iMesh ) const;
+ SDKMESH_INDEX_TYPE GetIndexType( _In_ UINT iMesh ) const;
+
+ ID3D11Buffer* GetAdjIB11( _In_ UINT iMesh ) const;
+
+ //Helpers (general)
+ const char* GetMeshPathA() const;
+ const WCHAR* GetMeshPathW() const;
+ UINT GetNumMeshes() const;
+ UINT GetNumMaterials() const;
+ UINT GetNumVBs() const;
+ UINT GetNumIBs() const;
+
+ ID3D11Buffer* GetVB11At( _In_ UINT iVB ) const;
+ ID3D11Buffer* GetIB11At( _In_ UINT iIB ) const;
+
+ BYTE* GetRawVerticesAt( _In_ UINT iVB ) const;
+ BYTE* GetRawIndicesAt( _In_ UINT iIB ) const;
+
+ SDKMESH_MATERIAL* GetMaterial( _In_ UINT iMaterial ) const;
+ SDKMESH_MESH* GetMesh( _In_ UINT iMesh ) const;
+ UINT GetNumSubsets( _In_ UINT iMesh ) const;
+ SDKMESH_SUBSET* GetSubset( _In_ UINT iMesh, _In_ UINT iSubset ) const;
+ UINT GetVertexStride( _In_ UINT iMesh, _In_ UINT iVB ) const;
+ UINT GetNumFrames() const;
+ SDKMESH_FRAME* GetFrame( _In_ UINT iFrame ) const;
+ SDKMESH_FRAME* FindFrame( _In_z_ const char* pszName ) const;
+ UINT64 GetNumVertices( _In_ UINT iMesh, _In_ UINT iVB ) const;
+ UINT64 GetNumIndices( _In_ UINT iMesh ) const;
+ DirectX::XMVECTOR GetMeshBBoxCenter( _In_ UINT iMesh ) const;
+ DirectX::XMVECTOR GetMeshBBoxExtents( _In_ UINT iMesh ) const;
+ UINT GetOutstandingResources() const;
+ UINT GetOutstandingBufferResources() const;
+ bool CheckLoadDone();
+ bool IsLoaded() const;
+ bool IsLoading() const;
+ void SetLoading( _In_ bool bLoading );
+ BOOL HadLoadingError() const;
+
+ //Animation
+ UINT GetNumInfluences( _In_ UINT iMesh ) const;
+ DirectX::XMMATRIX GetMeshInfluenceMatrix( _In_ UINT iMesh, _In_ UINT iInfluence ) const;
+ UINT GetAnimationKeyFromTime( _In_ double fTime ) const;
+ DirectX::XMMATRIX GetWorldMatrix( _In_ UINT iFrameIndex ) const;
+ DirectX::XMMATRIX GetInfluenceMatrix( _In_ UINT iFrameIndex ) const;
+ bool GetAnimationProperties( _Out_ UINT* pNumKeys, _Out_ float* pFrameTime ) const;
+};
+
+#endif
+
diff --git a/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmisc.h b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmisc.h
new file mode 100644
index 0000000..14ee349
--- /dev/null
+++ b/NvCloth/samples/external/DXUT/9.15.2016.1/Optional/SDKmisc.h
@@ -0,0 +1,134 @@
+//--------------------------------------------------------------------------------------
+// File: SDKMisc.h
+//
+// Various helper functionality that is shared between SDK samples
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=320437
+//--------------------------------------------------------------------------------------
+#pragma once
+
+//-----------------------------------------------------------------------------
+// Resource cache for textures, fonts, meshs, and effects.
+// Use DXUTGetGlobalResourceCache() to access the global cache
+//-----------------------------------------------------------------------------
+
+struct DXUTCache_Texture
+{
+ WCHAR wszSource[MAX_PATH];
+ bool bSRGB;
+ ID3D11ShaderResourceView* pSRV11;
+
+ DXUTCache_Texture() :
+ pSRV11(nullptr)
+ {
+ }
+};
+
+
+class CDXUTResourceCache
+{
+public:
+ ~CDXUTResourceCache();
+
+ HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCWSTR pSrcFile,
+ _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false );
+ HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCSTR pSrcFile,
+ _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false );
+public:
+ HRESULT OnDestroyDevice();
+
+protected:
+ friend CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache();
+ friend HRESULT WINAPI DXUTInitialize3DEnvironment();
+ friend HRESULT WINAPI DXUTReset3DEnvironment();
+ friend void WINAPI DXUTCleanup3DEnvironment( bool bReleaseSettings );
+
+ CDXUTResourceCache() { }
+
+ std::vector<DXUTCache_Texture> m_TextureCache;
+};
+
+CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache();
+
+
+//--------------------------------------------------------------------------------------
+// Manages the insertion point when drawing text
+//--------------------------------------------------------------------------------------
+class CDXUTDialogResourceManager;
+class CDXUTTextHelper
+{
+public:
+ CDXUTTextHelper( _In_ ID3D11Device* pd3d11Device, _In_ ID3D11DeviceContext* pd3dDeviceContext, _In_ CDXUTDialogResourceManager* pManager, _In_ int nLineHeight );
+ ~CDXUTTextHelper();
+
+ void Init( _In_ int nLineHeight = 15 );
+
+ void SetInsertionPos( _In_ int x, _In_ int y )
+ {
+ m_pt.x = x;
+ m_pt.y = y;
+ }
+ void SetForegroundColor( _In_ DirectX::XMFLOAT4 clr ) { m_clr = clr; }
+ void SetForegroundColor( _In_ DirectX::FXMVECTOR clr ) { XMStoreFloat4( &m_clr, clr ); }
+
+ void Begin();
+ HRESULT DrawFormattedTextLine( _In_z_ const WCHAR* strMsg, ... );
+ HRESULT DrawTextLine( _In_z_ const WCHAR* strMsg );
+ HRESULT DrawFormattedTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg, ... );
+ HRESULT DrawTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg );
+ void End();
+
+protected:
+ DirectX::XMFLOAT4 m_clr;
+ POINT m_pt;
+ int m_nLineHeight;
+
+ // D3D11 font
+ ID3D11Device* m_pd3d11Device;
+ ID3D11DeviceContext* m_pd3d11DeviceContext;
+ CDXUTDialogResourceManager* m_pManager;
+};
+
+
+//--------------------------------------------------------------------------------------
+// Shared code for samples to ask user if they want to use a REF device or quit
+//--------------------------------------------------------------------------------------
+void WINAPI DXUTDisplaySwitchingToREFWarning();
+
+//--------------------------------------------------------------------------------------
+// Tries to finds a media file by searching in common locations
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTFindDXSDKMediaFileCch( _Out_writes_(cchDest) WCHAR* strDestPath,
+ _In_ int cchDest,
+ _In_z_ LPCWSTR strFilename );
+HRESULT WINAPI DXUTSetMediaSearchPath( _In_z_ LPCWSTR strPath );
+LPCWSTR WINAPI DXUTGetMediaSearchPath();
+
+
+//--------------------------------------------------------------------------------------
+// Compiles HLSL shaders
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTCompileFromFile( _In_z_ LPCWSTR pFileName,
+ _In_reads_opt_(_Inexpressible_(pDefines->Name != NULL)) const D3D_SHADER_MACRO* pDefines,
+ _In_z_ LPCSTR pEntrypoint, _In_z_ LPCSTR pTarget,
+ _In_ UINT Flags1, _In_ UINT Flags2,
+ _Outptr_ ID3DBlob** ppCode );
+
+//--------------------------------------------------------------------------------------
+// Texture utilities
+//--------------------------------------------------------------------------------------
+HRESULT WINAPI DXUTCreateShaderResourceViewFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11ShaderResourceView** textureView );
+HRESULT WINAPI DXUTCreateTextureFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11Resource** texture );
+HRESULT WINAPI DXUTSaveTextureToFile( _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_ bool usedds, _In_z_ const wchar_t* szFileName );
+
+//--------------------------------------------------------------------------------------
+// Returns a view matrix for rendering to a face of a cubemap.
+//--------------------------------------------------------------------------------------
+DirectX::XMMATRIX WINAPI DXUTGetCubeMapViewMatrix( _In_ DWORD dwFace );
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/DirectXTex.lib
new file mode 100644
index 0000000..997aea2
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/directxtex.pdb
new file mode 100644
index 0000000..17e59eb
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Debug/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/DirectXTex.lib
new file mode 100644
index 0000000..de2d07a
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/directxtex.pdb
new file mode 100644
index 0000000..9f23b21
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/Win32/Release/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/DirectXTex.lib
new file mode 100644
index 0000000..a57b2d7
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/directxtex.pdb
new file mode 100644
index 0000000..ba864f3
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Debug/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/DirectXTex.lib
new file mode 100644
index 0000000..6dab420
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/directxtex.pdb
new file mode 100644
index 0000000..588f72d
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2013/x64/Release/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.lib
new file mode 100644
index 0000000..39a78a4
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.pdb
new file mode 100644
index 0000000..2307ceb
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Debug/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.lib
new file mode 100644
index 0000000..ea268bd
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.pdb
new file mode 100644
index 0000000..8469ac4
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/Win32/Release/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.lib
new file mode 100644
index 0000000..c7185e2
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.pdb
new file mode 100644
index 0000000..f818d01
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Debug/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.lib
new file mode 100644
index 0000000..62d7955
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.pdb
new file mode 100644
index 0000000..5dc8c6e
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/dynamiccrt/vs2015/x64/Release/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/DirectXTex.lib
new file mode 100644
index 0000000..fb12df6
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/directxtex.pdb
new file mode 100644
index 0000000..dd97134
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Debug/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/DirectXTex.lib
new file mode 100644
index 0000000..da06dda
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/directxtex.pdb
new file mode 100644
index 0000000..607d0a6
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/Win32/Release/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/DirectXTex.lib
new file mode 100644
index 0000000..4cb2733
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/directxtex.pdb
new file mode 100644
index 0000000..6d13872
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Debug/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/DirectXTex.lib
new file mode 100644
index 0000000..3e74fe6
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/directxtex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/directxtex.pdb
new file mode 100644
index 0000000..ff21366
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2013/x64/Release/directxtex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.lib
new file mode 100644
index 0000000..6252c58
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.pdb
new file mode 100644
index 0000000..9fb0d19
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Debug/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.lib
new file mode 100644
index 0000000..cee3cde
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.pdb
new file mode 100644
index 0000000..dea5b06
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/Win32/Release/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.lib
new file mode 100644
index 0000000..af61dde
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.pdb
new file mode 100644
index 0000000..7241f67
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Debug/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.lib b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.lib
new file mode 100644
index 0000000..70a0671
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.lib
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.pdb b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.pdb
new file mode 100644
index 0000000..4b244b7
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/bin/staticcrt/vs2015/x64/Release/DirectXTex.pdb
Binary files differ
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BC.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BC.h
new file mode 100644
index 0000000..8ddb366
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BC.h
@@ -0,0 +1,891 @@
+//-------------------------------------------------------------------------------------
+// BC.h
+//
+// Block-compression (BC) functionality
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+#include <assert.h>
+#include <directxmath.h>
+#include <directxpackedvector.h>
+
+namespace DirectX
+{
+
+//-------------------------------------------------------------------------------------
+// Constants
+//-------------------------------------------------------------------------------------
+
+const uint16_t F16S_MASK = 0x8000; // f16 sign mask
+const uint16_t F16EM_MASK = 0x7fff; // f16 exp & mantissa mask
+const uint16_t F16MAX = 0x7bff; // MAXFLT bit pattern for XMHALF
+
+#define SIGN_EXTEND(x,nb) ((((x)&(1<<((nb)-1)))?((~0)<<(nb)):0)|(x))
+
+// Because these are used in SAL annotations, they need to remain macros rather than const values
+#define NUM_PIXELS_PER_BLOCK 16
+#define BC6H_MAX_REGIONS 2
+#define BC6H_MAX_INDICES 16
+#define BC7_MAX_REGIONS 3
+#define BC7_MAX_INDICES 16
+
+const size_t BC6H_NUM_CHANNELS = 3;
+const size_t BC6H_MAX_SHAPES = 32;
+
+const size_t BC7_NUM_CHANNELS = 4;
+const size_t BC7_MAX_SHAPES = 64;
+
+const int32_t BC67_WEIGHT_MAX = 64;
+const uint32_t BC67_WEIGHT_SHIFT = 6;
+const int32_t BC67_WEIGHT_ROUND = 32;
+
+extern const int g_aWeights2[4];
+extern const int g_aWeights3[8];
+extern const int g_aWeights4[16];
+
+enum BC_FLAGS
+{
+ BC_FLAGS_NONE = 0x0,
+ BC_FLAGS_DITHER_RGB = 0x10000, // Enables dithering for RGB colors for BC1-3
+ BC_FLAGS_DITHER_A = 0x20000, // Enables dithering for Alpha channel for BC1-3
+ BC_FLAGS_UNIFORM = 0x40000, // By default, uses perceptual weighting for BC1-3; this flag makes it a uniform weighting
+ BC_FLAGS_USE_3SUBSETS = 0x80000,// By default, BC7 skips mode 0 & 2; this flag adds those modes back
+};
+
+//-------------------------------------------------------------------------------------
+// Structures
+//-------------------------------------------------------------------------------------
+class HDRColorA;
+
+class LDRColorA
+{
+public:
+ uint8_t r, g, b, a;
+
+ LDRColorA() = default;
+ LDRColorA(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a) : r(_r), g(_g), b(_b), a(_a) {}
+
+ const uint8_t& operator [] (_In_range_(0,3) size_t uElement) const
+ {
+ switch(uElement)
+ {
+ case 0: return r;
+ case 1: return g;
+ case 2: return b;
+ case 3: return a;
+ default: assert(false); return r;
+ }
+ }
+
+ uint8_t& operator [] (_In_range_(0,3) size_t uElement)
+ {
+ switch(uElement)
+ {
+ case 0: return r;
+ case 1: return g;
+ case 2: return b;
+ case 3: return a;
+ default: assert(false); return r;
+ }
+ }
+
+ LDRColorA operator = (_In_ const HDRColorA& c);
+
+ static void InterpolateRGB(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wc, _In_ _In_range_(2, 4) size_t wcprec, _Out_ LDRColorA& out)
+ {
+ const int* aWeights = nullptr;
+ switch(wcprec)
+ {
+ case 2: aWeights = g_aWeights2; assert( wc < 4 ); _Analysis_assume_( wc < 4 ); break;
+ case 3: aWeights = g_aWeights3; assert( wc < 8 ); _Analysis_assume_( wc < 8 ); break;
+ case 4: aWeights = g_aWeights4; assert( wc < 16 ); _Analysis_assume_( wc < 16 ); break;
+ default: assert(false); out.r = out.g = out.b = 0; return;
+ }
+ out.r = uint8_t((uint32_t(c0.r) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.r) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
+ out.g = uint8_t((uint32_t(c0.g) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.g) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
+ out.b = uint8_t((uint32_t(c0.b) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.b) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
+ }
+
+ static void InterpolateA(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wa, _In_range_(2, 4) _In_ size_t waprec, _Out_ LDRColorA& out)
+ {
+ const int* aWeights = nullptr;
+ switch(waprec)
+ {
+ case 2: aWeights = g_aWeights2; assert( wa < 4 ); _Analysis_assume_( wa < 4 ); break;
+ case 3: aWeights = g_aWeights3; assert( wa < 8 ); _Analysis_assume_( wa < 8 ); break;
+ case 4: aWeights = g_aWeights4; assert( wa < 16 ); _Analysis_assume_( wa < 16 ); break;
+ default: assert(false); out.a = 0; return;
+ }
+ out.a = uint8_t((uint32_t(c0.a) * uint32_t(BC67_WEIGHT_MAX - aWeights[wa]) + uint32_t(c1.a) * uint32_t(aWeights[wa]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT);
+ }
+
+ static void Interpolate(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wc, _In_ size_t wa, _In_ _In_range_(2, 4) size_t wcprec, _In_ _In_range_(2, 4) size_t waprec, _Out_ LDRColorA& out)
+ {
+ InterpolateRGB(c0, c1, wc, wcprec, out);
+ InterpolateA(c0, c1, wa, waprec, out);
+ }
+};
+
+static_assert( sizeof(LDRColorA) == 4, "Unexpected packing");
+
+class HDRColorA
+{
+public:
+ float r, g, b, a;
+
+public:
+ HDRColorA() = default;
+ HDRColorA(float _r, float _g, float _b, float _a) : r(_r), g(_g), b(_b), a(_a) {}
+ HDRColorA(const HDRColorA& c) : r(c.r), g(c.g), b(c.b), a(c.a) {}
+ HDRColorA(const LDRColorA& c)
+ {
+ r = float(c.r) * (1.0f/255.0f);
+ g = float(c.g) * (1.0f/255.0f);
+ b = float(c.b) * (1.0f/255.0f);
+ a = float(c.a) * (1.0f/255.0f);
+ }
+
+ // binary operators
+ HDRColorA operator + ( _In_ const HDRColorA& c ) const
+ {
+ return HDRColorA(r + c.r, g + c.g, b + c.b, a + c.a);
+ }
+
+ HDRColorA operator - ( _In_ const HDRColorA& c ) const
+ {
+ return HDRColorA(r - c.r, g - c.g, b - c.b, a - c.a);
+ }
+
+ HDRColorA operator * ( _In_ float f ) const
+ {
+ return HDRColorA(r * f, g * f, b * f, a * f);
+ }
+
+ HDRColorA operator / ( _In_ float f ) const
+ {
+ float fInv = 1.0f / f;
+ return HDRColorA(r * fInv, g * fInv, b * fInv, a * fInv);
+ }
+
+ float operator * ( _In_ const HDRColorA& c ) const
+ {
+ return r * c.r + g * c.g + b * c.b + a * c.a;
+ }
+
+ // assignment operators
+ HDRColorA& operator += ( _In_ const HDRColorA& c )
+ {
+ r += c.r;
+ g += c.g;
+ b += c.b;
+ a += c.a;
+ return *this;
+ }
+
+ HDRColorA& operator -= ( _In_ const HDRColorA& c )
+ {
+ r -= c.r;
+ g -= c.g;
+ b -= c.b;
+ a -= c.a;
+ return *this;
+ }
+
+ HDRColorA& operator *= ( _In_ float f )
+ {
+ r *= f;
+ g *= f;
+ b *= f;
+ a *= f;
+ return *this;
+ }
+
+ HDRColorA& operator /= ( _In_ float f )
+ {
+ float fInv = 1.0f / f;
+ r *= fInv;
+ g *= fInv;
+ b *= fInv;
+ a *= fInv;
+ return *this;
+ }
+
+ HDRColorA& operator = (_In_ const LDRColorA& c)
+ {
+ r = (float) c.r;
+ g = (float) c.g;
+ b = (float) c.b;
+ a = (float) c.a;
+ return *this;
+ }
+
+ HDRColorA& Clamp(_In_ float fMin, _In_ float fMax)
+ {
+ r = std::min<float>(fMax, std::max<float>(fMin, r));
+ g = std::min<float>(fMax, std::max<float>(fMin, g));
+ b = std::min<float>(fMax, std::max<float>(fMin, b));
+ a = std::min<float>(fMax, std::max<float>(fMin, a));
+ return *this;
+ }
+
+ LDRColorA ToLDRColorA() const
+ {
+ return LDRColorA((uint8_t) (r + 0.01f), (uint8_t) (g + 0.01f), (uint8_t) (b + 0.01f), (uint8_t) (a + 0.01f));
+ }
+};
+
+inline LDRColorA LDRColorA::operator = (_In_ const HDRColorA& c)
+{
+ LDRColorA ret;
+ HDRColorA tmp(c);
+ tmp = tmp.Clamp(0.0f, 1.0f) * 255.0f;
+ ret.r = uint8_t(tmp.r + 0.001f);
+ ret.g = uint8_t(tmp.g + 0.001f);
+ ret.b = uint8_t(tmp.b + 0.001f);
+ ret.a = uint8_t(tmp.a + 0.001f);
+ return ret;
+}
+
+struct LDREndPntPair
+{
+ LDRColorA A;
+ LDRColorA B;
+};
+
+struct HDREndPntPair
+{
+ HDRColorA A;
+ HDRColorA B;
+};
+
+inline HDRColorA* HDRColorALerp(_Out_ HDRColorA *pOut, _In_ const HDRColorA *pC1, _In_ const HDRColorA *pC2, _In_ float s)
+{
+ pOut->r = pC1->r + s * (pC2->r - pC1->r);
+ pOut->g = pC1->g + s * (pC2->g - pC1->g);
+ pOut->b = pC1->b + s * (pC2->b - pC1->b);
+ pOut->a = pC1->a + s * (pC2->a - pC1->a);
+ return pOut;
+}
+
+#pragma pack(push,1)
+// BC1/DXT1 compression (4 bits per texel)
+struct D3DX_BC1
+{
+ uint16_t rgb[2]; // 565 colors
+ uint32_t bitmap; // 2bpp rgb bitmap
+};
+
+// BC2/DXT2/3 compression (8 bits per texel)
+struct D3DX_BC2
+{
+ uint32_t bitmap[2]; // 4bpp alpha bitmap
+ D3DX_BC1 bc1; // BC1 rgb data
+};
+
+// BC3/DXT4/5 compression (8 bits per texel)
+struct D3DX_BC3
+{
+ uint8_t alpha[2]; // alpha values
+ uint8_t bitmap[6]; // 3bpp alpha bitmap
+ D3DX_BC1 bc1; // BC1 rgb data
+};
+#pragma pack(pop)
+
+class INTColor
+{
+public:
+ int r, g, b;
+ int pad;
+
+public:
+ INTColor() = default;
+ INTColor(int nr, int ng, int nb) {r = nr; g = ng; b = nb;}
+ INTColor(const INTColor& c) {r = c.r; g = c.g; b = c.b;}
+
+ INTColor operator - ( _In_ const INTColor& c ) const
+ {
+ return INTColor(r - c.r, g - c.g, b - c.b);
+ }
+
+ INTColor& operator += ( _In_ const INTColor& c )
+ {
+ r += c.r;
+ g += c.g;
+ b += c.b;
+ return *this;
+ }
+
+ INTColor& operator -= ( _In_ const INTColor& c )
+ {
+ r -= c.r;
+ g -= c.g;
+ b -= c.b;
+ return *this;
+ }
+
+ INTColor& operator &= ( _In_ const INTColor& c )
+ {
+ r &= c.r;
+ g &= c.g;
+ b &= c.b;
+ return *this;
+ }
+
+ int& operator [] ( _In_ uint8_t i )
+ {
+ assert(i < sizeof(INTColor) / sizeof(int));
+ _Analysis_assume_(i < sizeof(INTColor) / sizeof(int));
+ return ((int*) this)[i];
+ }
+
+ void Set(_In_ const HDRColorA& c, _In_ bool bSigned)
+ {
+ PackedVector::XMHALF4 aF16;
+
+ XMVECTOR v = XMLoadFloat4( (const XMFLOAT4*)& c );
+ XMStoreHalf4( &aF16, v );
+
+ r = F16ToINT(aF16.x, bSigned);
+ g = F16ToINT(aF16.y, bSigned);
+ b = F16ToINT(aF16.z, bSigned);
+ }
+
+ INTColor& Clamp(_In_ int iMin, _In_ int iMax)
+ {
+ r = std::min<int>(iMax, std::max<int>(iMin, r));
+ g = std::min<int>(iMax, std::max<int>(iMin, g));
+ b = std::min<int>(iMax, std::max<int>(iMin, b));
+ return *this;
+ }
+
+ INTColor& SignExtend(_In_ const LDRColorA& Prec)
+ {
+ r = SIGN_EXTEND(r, Prec.r);
+ g = SIGN_EXTEND(g, Prec.g);
+ b = SIGN_EXTEND(b, Prec.b);
+ return *this;
+ }
+
+ void ToF16(_Out_writes_(3) PackedVector::HALF aF16[3], _In_ bool bSigned) const
+ {
+ aF16[0] = INT2F16(r, bSigned);
+ aF16[1] = INT2F16(g, bSigned);
+ aF16[2] = INT2F16(b, bSigned);
+ }
+
+private:
+ static int F16ToINT(_In_ const PackedVector::HALF& f, _In_ bool bSigned)
+ {
+ uint16_t input = *((const uint16_t*) &f);
+ int out, s;
+ if(bSigned)
+ {
+ s = input & F16S_MASK;
+ input &= F16EM_MASK;
+ if(input > F16MAX) out = F16MAX;
+ else out = input;
+ out = s ? -out : out;
+ }
+ else
+ {
+ if(input & F16S_MASK) out = 0;
+ else out = input;
+ }
+ return out;
+ }
+
+ static PackedVector::HALF INT2F16(_In_ int input, _In_ bool bSigned)
+ {
+ PackedVector::HALF h;
+ uint16_t out;
+ if(bSigned)
+ {
+ int s = 0;
+ if(input < 0)
+ {
+ s = F16S_MASK;
+ input = -input;
+ }
+ out = uint16_t(s | input);
+ }
+ else
+ {
+ assert(input >= 0 && input <= F16MAX);
+ out = (uint16_t) input;
+ }
+
+ *((uint16_t*) &h) = out;
+ return h;
+ }
+};
+
+static_assert( sizeof(INTColor) == 16, "Unexpected packing");
+
+struct INTEndPntPair
+{
+ INTColor A;
+ INTColor B;
+};
+
+template< size_t SizeInBytes >
+class CBits
+{
+public:
+ uint8_t GetBit(_Inout_ size_t& uStartBit) const
+ {
+ assert(uStartBit < 128);
+ _Analysis_assume_(uStartBit < 128);
+ size_t uIndex = uStartBit >> 3;
+ uint8_t ret = (m_uBits[uIndex] >> (uStartBit - (uIndex << 3))) & 0x01;
+ uStartBit++;
+ return ret;
+ }
+
+ uint8_t GetBits(_Inout_ size_t& uStartBit, _In_ size_t uNumBits) const
+ {
+ if(uNumBits == 0) return 0;
+ assert(uStartBit + uNumBits <= 128 && uNumBits <= 8);
+ _Analysis_assume_(uStartBit + uNumBits <= 128 && uNumBits <= 8);
+ uint8_t ret;
+ size_t uIndex = uStartBit >> 3;
+ size_t uBase = uStartBit - (uIndex << 3);
+ if(uBase + uNumBits > 8)
+ {
+ size_t uFirstIndexBits = 8 - uBase;
+ size_t uNextIndexBits = uNumBits - uFirstIndexBits;
+ ret = (m_uBits[uIndex] >> uBase) | ((m_uBits[uIndex+1] & ((1 << uNextIndexBits) - 1)) << uFirstIndexBits);
+ }
+ else
+ {
+ ret = (m_uBits[uIndex] >> uBase) & ((1 << uNumBits) - 1);
+ }
+ assert(ret < (1 << uNumBits));
+ uStartBit += uNumBits;
+ return ret;
+ }
+
+ void SetBit(_Inout_ size_t& uStartBit, _In_ uint8_t uValue)
+ {
+ assert(uStartBit < 128 && uValue < 2);
+ _Analysis_assume_(uStartBit < 128 && uValue < 2);
+ size_t uIndex = uStartBit >> 3;
+ size_t uBase = uStartBit - (uIndex << 3);
+ m_uBits[uIndex] &= ~(1 << uBase);
+ m_uBits[uIndex] |= uValue << uBase;
+ uStartBit++;
+ }
+
+ void SetBits(_Inout_ size_t& uStartBit, _In_ size_t uNumBits, _In_ uint8_t uValue)
+ {
+ if(uNumBits == 0)
+ return;
+ assert(uStartBit + uNumBits <= 128 && uNumBits <= 8);
+ _Analysis_assume_(uStartBit + uNumBits <= 128 && uNumBits <= 8);
+ assert(uValue < (1 << uNumBits));
+ size_t uIndex = uStartBit >> 3;
+ size_t uBase = uStartBit - (uIndex << 3);
+ if(uBase + uNumBits > 8)
+ {
+ size_t uFirstIndexBits = 8 - uBase;
+ size_t uNextIndexBits = uNumBits - uFirstIndexBits;
+ m_uBits[uIndex] &= ~(((1 << uFirstIndexBits) - 1) << uBase);
+ m_uBits[uIndex] |= uValue << uBase;
+ m_uBits[uIndex+1] &= ~((1 << uNextIndexBits) - 1);
+ m_uBits[uIndex+1] |= uValue >> uFirstIndexBits;
+ }
+ else
+ {
+ m_uBits[uIndex] &= ~(((1 << uNumBits) - 1) << uBase);
+ m_uBits[uIndex] |= uValue << uBase;
+ }
+ uStartBit += uNumBits;
+ }
+
+private:
+ uint8_t m_uBits[ SizeInBytes ];
+};
+
+// BC6H compression (16 bits per texel)
+class D3DX_BC6H : private CBits< 16 >
+{
+public:
+ void Decode(_In_ bool bSigned, _Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut) const;
+ void Encode(_In_ bool bSigned, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pIn);
+
+private:
+#pragma warning(push)
+#pragma warning(disable : 4480)
+ enum EField : uint8_t
+ {
+ NA, // N/A
+ M, // Mode
+ D, // Shape
+ RW,
+ RX,
+ RY,
+ RZ,
+ GW,
+ GX,
+ GY,
+ GZ,
+ BW,
+ BX,
+ BY,
+ BZ,
+ };
+#pragma warning(pop)
+
+ struct ModeDescriptor
+ {
+ EField m_eField;
+ uint8_t m_uBit;
+ };
+
+ struct ModeInfo
+ {
+ uint8_t uMode;
+ uint8_t uPartitions;
+ bool bTransformed;
+ uint8_t uIndexPrec;
+ LDRColorA RGBAPrec[BC6H_MAX_REGIONS][2];
+ };
+
+#pragma warning(push)
+#pragma warning(disable : 4512)
+ struct EncodeParams
+ {
+ float fBestErr;
+ const bool bSigned;
+ uint8_t uMode;
+ uint8_t uShape;
+ const HDRColorA* const aHDRPixels;
+ INTEndPntPair aUnqEndPts[BC6H_MAX_SHAPES][BC6H_MAX_REGIONS];
+ INTColor aIPixels[NUM_PIXELS_PER_BLOCK];
+
+ EncodeParams(const HDRColorA* const aOriginal, bool bSignedFormat) :
+ aHDRPixels(aOriginal), fBestErr(FLT_MAX), bSigned(bSignedFormat)
+ {
+ for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i)
+ {
+ aIPixels[i].Set(aOriginal[i], bSigned);
+ }
+ }
+ };
+#pragma warning(pop)
+
+ static int Quantize(_In_ int iValue, _In_ int prec, _In_ bool bSigned);
+ static int Unquantize(_In_ int comp, _In_ uint8_t uBitsPerComp, _In_ bool bSigned);
+ static int FinishUnquantize(_In_ int comp, _In_ bool bSigned);
+
+ static bool EndPointsFit(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[]);
+
+ void GeneratePaletteQuantized(_In_ const EncodeParams* pEP, _In_ const INTEndPntPair& endPts,
+ _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]) const;
+ float MapColorsQuantized(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ const INTEndPntPair &endPts) const;
+ float PerturbOne(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ uint8_t ch,
+ _In_ const INTEndPntPair& oldEndPts, _Out_ INTEndPntPair& newEndPts, _In_ float fOldErr, _In_ int do_b) const;
+ void OptimizeOne(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ float aOrgErr,
+ _In_ const INTEndPntPair &aOrgEndPts, _Out_ INTEndPntPair &aOptEndPts) const;
+ void OptimizeEndPoints(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const float aOrgErr[],
+ _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aOrgEndPts[],
+ _Out_writes_all_(BC6H_MAX_REGIONS) INTEndPntPair aOptEndPts[]) const;
+ static void SwapIndices(_In_ const EncodeParams* pEP, _Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aEndPts[],
+ _In_reads_(NUM_PIXELS_PER_BLOCK) size_t aIndices[]);
+ void AssignIndices(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[],
+ _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices[],
+ _Out_writes_(BC6H_MAX_REGIONS) float aTotErr[]) const;
+ void QuantizeEndPts(_In_ const EncodeParams* pEP, _Out_writes_(BC6H_MAX_REGIONS) INTEndPntPair* qQntEndPts) const;
+ void EmitBlock(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[],
+ _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndices[]);
+ void Refine(_Inout_ EncodeParams* pEP);
+
+ static void GeneratePaletteUnquantized(_In_ const EncodeParams* pEP, _In_ size_t uRegion, _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]);
+ float MapColors(_In_ const EncodeParams* pEP, _In_ size_t uRegion, _In_ size_t np, _In_reads_(np) const size_t* auIndex) const;
+ float RoughMSE(_Inout_ EncodeParams* pEP) const;
+
+private:
+ const static ModeDescriptor ms_aDesc[][82];
+ const static ModeInfo ms_aInfo[];
+ const static int ms_aModeToInfo[];
+};
+
+// BC67 compression (16b bits per texel)
+class D3DX_BC7 : private CBits< 16 >
+{
+public:
+ void Decode(_Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut) const;
+ void Encode(bool skip3subsets, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pIn);
+
+private:
+ struct ModeInfo
+ {
+ uint8_t uPartitions;
+ uint8_t uPartitionBits;
+ uint8_t uPBits;
+ uint8_t uRotationBits;
+ uint8_t uIndexModeBits;
+ uint8_t uIndexPrec;
+ uint8_t uIndexPrec2;
+ LDRColorA RGBAPrec;
+ LDRColorA RGBAPrecWithP;
+ };
+
+#pragma warning(push)
+#pragma warning(disable : 4512)
+ struct EncodeParams
+ {
+ uint8_t uMode;
+ LDREndPntPair aEndPts[BC7_MAX_SHAPES][BC7_MAX_REGIONS];
+ LDRColorA aLDRPixels[NUM_PIXELS_PER_BLOCK];
+ const HDRColorA* const aHDRPixels;
+
+ EncodeParams(const HDRColorA* const aOriginal) : aHDRPixels(aOriginal) {}
+ };
+#pragma warning(pop)
+
+ static uint8_t Quantize(_In_ uint8_t comp, _In_ uint8_t uPrec)
+ {
+ assert(0 < uPrec && uPrec <= 8);
+ uint8_t rnd = (uint8_t) std::min<uint16_t>(255, uint16_t(comp) + (1 << (7 - uPrec)));
+ return rnd >> (8 - uPrec);
+ }
+
+ static LDRColorA Quantize(_In_ const LDRColorA& c, _In_ const LDRColorA& RGBAPrec)
+ {
+ LDRColorA q;
+ q.r = Quantize(c.r, RGBAPrec.r);
+ q.g = Quantize(c.g, RGBAPrec.g);
+ q.b = Quantize(c.b, RGBAPrec.b);
+ if(RGBAPrec.a)
+ q.a = Quantize(c.a, RGBAPrec.a);
+ else
+ q.a = 255;
+ return q;
+ }
+
+ static uint8_t Unquantize(_In_ uint8_t comp, _In_ size_t uPrec)
+ {
+ assert(0 < uPrec && uPrec <= 8);
+ comp = comp << (8 - uPrec);
+ return comp | (comp >> uPrec);
+ }
+
+ static LDRColorA Unquantize(_In_ const LDRColorA& c, _In_ const LDRColorA& RGBAPrec)
+ {
+ LDRColorA q;
+ q.r = Unquantize(c.r, RGBAPrec.r);
+ q.g = Unquantize(c.g, RGBAPrec.g);
+ q.b = Unquantize(c.b, RGBAPrec.b);
+ q.a = RGBAPrec.a > 0 ? Unquantize(c.a, RGBAPrec.a) : 255;
+ return q;
+ }
+
+ void GeneratePaletteQuantized(_In_ const EncodeParams* pEP, _In_ size_t uIndexMode, _In_ const LDREndPntPair& endpts,
+ _Out_writes_(BC7_MAX_INDICES) LDRColorA aPalette[]) const;
+ float PerturbOne(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode,
+ _In_ size_t ch, _In_ const LDREndPntPair &old_endpts,
+ _Out_ LDREndPntPair &new_endpts, _In_ float old_err, _In_ uint8_t do_b) const;
+ void Exhaustive(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode,
+ _In_ size_t ch, _Inout_ float& fOrgErr, _Inout_ LDREndPntPair& optEndPt) const;
+ void OptimizeOne(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode,
+ _In_ float orig_err, _In_ const LDREndPntPair &orig_endpts, _Out_ LDREndPntPair &opt_endpts) const;
+ void OptimizeEndPoints(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode,
+ _In_reads_(BC7_MAX_REGIONS) const float orig_err[],
+ _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair orig_endpts[],
+ _Out_writes_(BC7_MAX_REGIONS) LDREndPntPair opt_endpts[]) const;
+ void AssignIndices(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode,
+ _In_reads_(BC7_MAX_REGIONS) LDREndPntPair endpts[],
+ _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices[], _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices2[],
+ _Out_writes_(BC7_MAX_REGIONS) float afTotErr[]) const;
+ void EmitBlock(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode,
+ _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair aEndPts[],
+ _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex[],
+ _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex2[]);
+ float Refine(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode);
+
+ float MapColors(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode,
+ _In_ const LDREndPntPair& endPts, _In_ float fMinErr) const;
+ static float RoughMSE(_Inout_ EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode);
+
+private:
+ const static ModeInfo ms_aInfo[];
+};
+
+//-------------------------------------------------------------------------------------
+#pragma warning(push)
+#pragma warning(disable : 4127)
+template <bool bRange> void OptimizeAlpha(float *pX, float *pY, const float *pPoints, size_t cSteps)
+{
+ static const float pC6[] = { 5.0f/5.0f, 4.0f/5.0f, 3.0f/5.0f, 2.0f/5.0f, 1.0f/5.0f, 0.0f/5.0f };
+ static const float pD6[] = { 0.0f/5.0f, 1.0f/5.0f, 2.0f/5.0f, 3.0f/5.0f, 4.0f/5.0f, 5.0f/5.0f };
+ static const float pC8[] = { 7.0f/7.0f, 6.0f/7.0f, 5.0f/7.0f, 4.0f/7.0f, 3.0f/7.0f, 2.0f/7.0f, 1.0f/7.0f, 0.0f/7.0f };
+ static const float pD8[] = { 0.0f/7.0f, 1.0f/7.0f, 2.0f/7.0f, 3.0f/7.0f, 4.0f/7.0f, 5.0f/7.0f, 6.0f/7.0f, 7.0f/7.0f };
+
+ const float *pC = (6 == cSteps) ? pC6 : pC8;
+ const float *pD = (6 == cSteps) ? pD6 : pD8;
+
+ float MAX_VALUE = 1.0f;
+ float MIN_VALUE;
+ if (bRange)
+ {
+ MIN_VALUE = -1.0f;
+ }
+ else
+ {
+ MIN_VALUE = 0.0f;
+ }
+
+ // Find Min and Max points, as starting point
+ float fX = MAX_VALUE;
+ float fY = MIN_VALUE;
+
+ if(8 == cSteps)
+ {
+ for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
+ {
+ if(pPoints[iPoint] < fX)
+ fX = pPoints[iPoint];
+
+ if(pPoints[iPoint] > fY)
+ fY = pPoints[iPoint];
+ }
+ }
+ else
+ {
+ for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
+ {
+ if(pPoints[iPoint] < fX && pPoints[iPoint] > MIN_VALUE)
+ fX = pPoints[iPoint];
+
+ if(pPoints[iPoint] > fY && pPoints[iPoint] < MAX_VALUE)
+ fY = pPoints[iPoint];
+ }
+
+ if (fX == fY)
+ {
+ fY = MAX_VALUE;
+ }
+ }
+
+ // Use Newton's Method to find local minima of sum-of-squares error.
+ float fSteps = (float) (cSteps - 1);
+
+ for(size_t iIteration = 0; iIteration < 8; iIteration++)
+ {
+ float fScale;
+
+ if((fY - fX) < (1.0f / 256.0f))
+ break;
+
+ fScale = fSteps / (fY - fX);
+
+ // Calculate new steps
+ float pSteps[8];
+
+ for(size_t iStep = 0; iStep < cSteps; iStep++)
+ pSteps[iStep] = pC[iStep] * fX + pD[iStep] * fY;
+
+ if(6 == cSteps)
+ {
+ pSteps[6] = MIN_VALUE;
+ pSteps[7] = MAX_VALUE;
+ }
+
+ // Evaluate function, and derivatives
+ float dX = 0.0f;
+ float dY = 0.0f;
+ float d2X = 0.0f;
+ float d2Y = 0.0f;
+
+ for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++)
+ {
+ float fDot = (pPoints[iPoint] - fX) * fScale;
+
+ size_t iStep;
+
+ if(fDot <= 0.0f)
+ iStep = ((6 == cSteps) && (pPoints[iPoint] <= fX * 0.5f)) ? 6 : 0;
+ else if(fDot >= fSteps)
+ iStep = ((6 == cSteps) && (pPoints[iPoint] >= (fY + 1.0f) * 0.5f)) ? 7 : (cSteps - 1);
+ else
+ iStep = static_cast<int32_t>(fDot + 0.5f);
+
+
+ if(iStep < cSteps)
+ {
+ // D3DX had this computation backwards (pPoints[iPoint] - pSteps[iStep])
+ // this fix improves RMS of the alpha component
+ float fDiff = pSteps[iStep] - pPoints[iPoint];
+
+ dX += pC[iStep] * fDiff;
+ d2X += pC[iStep] * pC[iStep];
+
+ dY += pD[iStep] * fDiff;
+ d2Y += pD[iStep] * pD[iStep];
+ }
+ }
+
+ // Move endpoints
+ if(d2X > 0.0f)
+ fX -= dX / d2X;
+
+ if(d2Y > 0.0f)
+ fY -= dY / d2Y;
+
+ if(fX > fY)
+ {
+ float f = fX; fX = fY; fY = f;
+ }
+
+ if((dX * dX < (1.0f / 64.0f)) && (dY * dY < (1.0f / 64.0f)))
+ break;
+ }
+
+ *pX = (fX < MIN_VALUE) ? MIN_VALUE : (fX > MAX_VALUE) ? MAX_VALUE : fX;
+ *pY = (fY < MIN_VALUE) ? MIN_VALUE : (fY > MAX_VALUE) ? MAX_VALUE : fY;
+}
+#pragma warning(pop)
+
+
+//-------------------------------------------------------------------------------------
+// Functions
+//-------------------------------------------------------------------------------------
+
+typedef void (*BC_DECODE)(XMVECTOR *pColor, const uint8_t *pBC);
+typedef void (*BC_ENCODE)(uint8_t *pDXT, const XMVECTOR *pColor, DWORD flags);
+
+void D3DXDecodeBC1(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC);
+void D3DXDecodeBC2(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+void D3DXDecodeBC3(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+void D3DXDecodeBC4U(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC);
+void D3DXDecodeBC4S(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC);
+void D3DXDecodeBC5U(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+void D3DXDecodeBC5S(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+void D3DXDecodeBC6HU(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+void D3DXDecodeBC6HS(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+void D3DXDecodeBC7(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC);
+
+void D3DXEncodeBC1(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ float alphaRef, _In_ DWORD flags);
+ // BC1 requires one additional parameter, so it doesn't match signature of BC_ENCODE above
+
+void D3DXEncodeBC2(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC3(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC4U(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC4S(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC5U(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC5S(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC6HU(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC6HS(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+void D3DXEncodeBC7(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags);
+
+}; // namespace
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BCDirectCompute.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BCDirectCompute.h
new file mode 100644
index 0000000..8bbfa75
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/BCDirectCompute.h
@@ -0,0 +1,67 @@
+//-------------------------------------------------------------------------------------
+// BCDirectCompute.h
+//
+// Direct3D 11 Compute Shader BC Compressor
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+namespace DirectX
+{
+
+class GPUCompressBC
+{
+public:
+ GPUCompressBC();
+
+ HRESULT Initialize( _In_ ID3D11Device* pDevice );
+
+ HRESULT Prepare( _In_ size_t width, _In_ size_t height, _In_ DXGI_FORMAT format, _In_ float alphaWeight = 1.f, _In_ bool skip3subsets = true );
+
+ HRESULT Compress( _In_ const Image& srcImage, _In_ const Image& destImage );
+
+ DXGI_FORMAT GetSourceFormat() const { return m_srcformat; }
+
+private:
+ DXGI_FORMAT m_bcformat;
+ DXGI_FORMAT m_srcformat;
+ float m_alphaWeight;
+ bool m_skip3Subsets;
+ size_t m_width;
+ size_t m_height;
+
+ Microsoft::WRL::ComPtr<ID3D11Device> m_device;
+ Microsoft::WRL::ComPtr<ID3D11DeviceContext> m_context;
+
+ Microsoft::WRL::ComPtr<ID3D11Buffer> m_err1;
+ Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> m_err1UAV;
+ Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_err1SRV;
+
+ Microsoft::WRL::ComPtr<ID3D11Buffer> m_err2;
+ Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> m_err2UAV;
+ Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_err2SRV;
+
+ Microsoft::WRL::ComPtr<ID3D11Buffer> m_output;
+ Microsoft::WRL::ComPtr<ID3D11Buffer> m_outputCPU;
+ Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> m_outputUAV;
+ Microsoft::WRL::ComPtr<ID3D11Buffer> m_constBuffer;
+
+ // Compute shader library
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC6H_tryModeG10CS;
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC6H_tryModeLE10CS;
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC6H_encodeBlockCS;
+
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC7_tryMode456CS;
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC7_tryMode137CS;
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC7_tryMode02CS;
+ Microsoft::WRL::ComPtr<ID3D11ComputeShader> m_BC7_encodeBlockCS;
+};
+
+}; // namespace \ No newline at end of file
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DDS.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DDS.h
new file mode 100644
index 0000000..66bd734
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DDS.h
@@ -0,0 +1,243 @@
+//--------------------------------------------------------------------------------------
+// dds.h
+//
+// This header defines constants and structures that are useful when parsing
+// DDS files. DDS files were originally designed to use several structures
+// and constants that are native to DirectDraw and are defined in ddraw.h,
+// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar
+// (compatible) constants and structures so that one can use DDS files
+// without needing to include ddraw.h.
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+//--------------------------------------------------------------------------------------
+
+#pragma once
+
+#if defined(_XBOX_ONE) && defined(_TITLE)
+#include <d3d11_x.h>
+#else
+#include <dxgiformat.h>
+#endif
+
+#include <stdint.h>
+
+namespace DirectX
+{
+
+#pragma pack(push,1)
+
+const uint32_t DDS_MAGIC = 0x20534444; // "DDS "
+
+struct DDS_PIXELFORMAT
+{
+ uint32_t dwSize;
+ uint32_t dwFlags;
+ uint32_t dwFourCC;
+ uint32_t dwRGBBitCount;
+ uint32_t dwRBitMask;
+ uint32_t dwGBitMask;
+ uint32_t dwBBitMask;
+ uint32_t dwABitMask;
+};
+
+#define DDS_FOURCC 0x00000004 // DDPF_FOURCC
+#define DDS_RGB 0x00000040 // DDPF_RGB
+#define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS
+#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE
+#define DDS_LUMINANCEA 0x00020001 // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
+#define DDS_ALPHA 0x00000002 // DDPF_ALPHA
+#define DDS_PAL8 0x00000020 // DDPF_PALETTEINDEXED8
+#define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV
+
+#ifndef MAKEFOURCC
+ #define MAKEFOURCC(ch0, ch1, ch2, ch3) \
+ ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \
+ ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 ))
+#endif /* defined(MAKEFOURCC) */
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_YUY2 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0x00, 0x00, 0x00 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 =
+ { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0x0000, 0x0000, 0x0000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0x0000, 0x0000, 0xff00 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0x00, 0x00, 0x00, 0xff };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V8U8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0x0000, 0x0000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 =
+ { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
+
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V16U16 =
+ { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 };
+
+// D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue
+
+// This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat)
+extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 =
+ { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 };
+
+#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
+#define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT
+#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH
+#define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH
+#define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE
+
+#define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
+#define DDS_WIDTH 0x00000004 // DDSD_WIDTH
+
+#define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
+#define DDS_SURFACE_FLAGS_MIPMAP 0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
+#define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
+
+#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
+#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
+#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
+#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
+#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
+#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
+
+#define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
+ DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
+ DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ )
+
+#define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
+
+#define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
+
+// Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION
+enum DDS_RESOURCE_DIMENSION
+{
+ DDS_DIMENSION_TEXTURE1D = 2,
+ DDS_DIMENSION_TEXTURE2D = 3,
+ DDS_DIMENSION_TEXTURE3D = 4,
+};
+
+// Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG
+enum DDS_RESOURCE_MISC_FLAG
+{
+ DDS_RESOURCE_MISC_TEXTURECUBE = 0x4L,
+};
+
+enum DDS_MISC_FLAGS2
+{
+ DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L,
+};
+
+enum DDS_ALPHA_MODE
+{
+ DDS_ALPHA_MODE_UNKNOWN = 0,
+ DDS_ALPHA_MODE_STRAIGHT = 1,
+ DDS_ALPHA_MODE_PREMULTIPLIED = 2,
+ DDS_ALPHA_MODE_OPAQUE = 3,
+ DDS_ALPHA_MODE_CUSTOM = 4,
+};
+
+struct DDS_HEADER
+{
+ uint32_t dwSize;
+ uint32_t dwFlags;
+ uint32_t dwHeight;
+ uint32_t dwWidth;
+ uint32_t dwPitchOrLinearSize;
+ uint32_t dwDepth; // only if DDS_HEADER_FLAGS_VOLUME is set in dwFlags
+ uint32_t dwMipMapCount;
+ uint32_t dwReserved1[11];
+ DDS_PIXELFORMAT ddspf;
+ uint32_t dwCaps;
+ uint32_t dwCaps2;
+ uint32_t dwCaps3;
+ uint32_t dwCaps4;
+ uint32_t dwReserved2;
+};
+
+struct DDS_HEADER_DXT10
+{
+ DXGI_FORMAT dxgiFormat;
+ uint32_t resourceDimension;
+ uint32_t miscFlag; // see DDS_RESOURCE_MISC_FLAG
+ uint32_t arraySize;
+ uint32_t miscFlags2; // see DDS_MISC_FLAGS2
+};
+
+#pragma pack(pop)
+
+static_assert( sizeof(DDS_HEADER) == 124, "DDS Header size mismatch" );
+static_assert( sizeof(DDS_HEADER_DXT10) == 20, "DDS DX10 Extended Header size mismatch");
+
+}; // namespace
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.h
new file mode 100644
index 0000000..e2b848b
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.h
@@ -0,0 +1,636 @@
+//-------------------------------------------------------------------------------------
+// DirectXTex.h
+//
+// DirectX Texture Library
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) && (_WIN32_WINNT <= _WIN32_WINNT_WIN8)
+#error WIC is not supported on Windows Phone 8.0
+#endif
+
+#include <stdint.h>
+
+#include <algorithm>
+#include <functional>
+
+#if defined(_XBOX_ONE) && defined(_TITLE)
+#include <d3d11_x.h>
+#define DCOMMON_H_INCLUDED
+#else
+#include <d3d11_1.h>
+#endif
+
+#include <ocidl.h>
+
+#define DIRECTX_TEX_VERSION 134
+
+struct IWICImagingFactory;
+struct IWICMetadataQueryReader;
+
+
+namespace DirectX
+{
+
+ //---------------------------------------------------------------------------------
+ // DXGI Format Utilities
+ bool __cdecl IsValid( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsCompressed( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsPacked( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsVideo( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsPlanar( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsPalettized( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsDepthStencil(_In_ DXGI_FORMAT fmt );
+ bool __cdecl IsSRGB( _In_ DXGI_FORMAT fmt );
+ bool __cdecl IsTypeless( _In_ DXGI_FORMAT fmt, _In_ bool partialTypeless = true );
+
+ bool __cdecl HasAlpha( _In_ DXGI_FORMAT fmt );
+
+ size_t __cdecl BitsPerPixel( _In_ DXGI_FORMAT fmt );
+
+ size_t __cdecl BitsPerColor( _In_ DXGI_FORMAT fmt );
+
+ enum CP_FLAGS
+ {
+ CP_FLAGS_NONE = 0x0, // Normal operation
+ CP_FLAGS_LEGACY_DWORD = 0x1, // Assume pitch is DWORD aligned instead of BYTE aligned
+ CP_FLAGS_PARAGRAPH = 0x2, // Assume pitch is 16-byte aligned instead of BYTE aligned
+ CP_FLAGS_YMM = 0x4, // Assume pitch is 32-byte aligned instead of BYTE aligned
+ CP_FLAGS_ZMM = 0x8, // Assume pitch is 64-byte aligned instead of BYTE aligned
+ CP_FLAGS_PAGE4K = 0x200, // Assume pitch is 4096-byte aligned instead of BYTE aligned
+ CP_FLAGS_24BPP = 0x10000, // Override with a legacy 24 bits-per-pixel format size
+ CP_FLAGS_16BPP = 0x20000, // Override with a legacy 16 bits-per-pixel format size
+ CP_FLAGS_8BPP = 0x40000, // Override with a legacy 8 bits-per-pixel format size
+ };
+
+ void __cdecl ComputePitch( _In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height,
+ _Out_ size_t& rowPitch, _Out_ size_t& slicePitch, _In_ DWORD flags = CP_FLAGS_NONE );
+
+ size_t __cdecl ComputeScanlines( _In_ DXGI_FORMAT fmt, _In_ size_t height );
+
+ DXGI_FORMAT __cdecl MakeSRGB( _In_ DXGI_FORMAT fmt );
+ DXGI_FORMAT __cdecl MakeTypeless( _In_ DXGI_FORMAT fmt );
+ DXGI_FORMAT __cdecl MakeTypelessUNORM( _In_ DXGI_FORMAT fmt );
+ DXGI_FORMAT __cdecl MakeTypelessFLOAT( _In_ DXGI_FORMAT fmt );
+
+ //---------------------------------------------------------------------------------
+ // Texture metadata
+ enum TEX_DIMENSION
+ // Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION
+ {
+ TEX_DIMENSION_TEXTURE1D = 2,
+ TEX_DIMENSION_TEXTURE2D = 3,
+ TEX_DIMENSION_TEXTURE3D = 4,
+ };
+
+ enum TEX_MISC_FLAG
+ // Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG
+ {
+ TEX_MISC_TEXTURECUBE = 0x4L,
+ };
+
+ enum TEX_MISC_FLAG2
+ {
+ TEX_MISC2_ALPHA_MODE_MASK = 0x7L,
+ };
+
+ enum TEX_ALPHA_MODE
+ // Matches DDS_ALPHA_MODE, encoded in MISC_FLAGS2
+ {
+ TEX_ALPHA_MODE_UNKNOWN = 0,
+ TEX_ALPHA_MODE_STRAIGHT = 1,
+ TEX_ALPHA_MODE_PREMULTIPLIED = 2,
+ TEX_ALPHA_MODE_OPAQUE = 3,
+ TEX_ALPHA_MODE_CUSTOM = 4,
+ };
+
+ struct TexMetadata
+ {
+ size_t width;
+ size_t height; // Should be 1 for 1D textures
+ size_t depth; // Should be 1 for 1D or 2D textures
+ size_t arraySize; // For cubemap, this is a multiple of 6
+ size_t mipLevels;
+ uint32_t miscFlags;
+ uint32_t miscFlags2;
+ DXGI_FORMAT format;
+ TEX_DIMENSION dimension;
+
+ size_t __cdecl ComputeIndex( _In_ size_t mip, _In_ size_t item, _In_ size_t slice ) const;
+ // Returns size_t(-1) to indicate an out-of-range error
+
+ bool __cdecl IsCubemap() const { return (miscFlags & TEX_MISC_TEXTURECUBE) != 0; }
+ // Helper for miscFlags
+
+ bool __cdecl IsPMAlpha() const { return ((miscFlags2 & TEX_MISC2_ALPHA_MODE_MASK) == TEX_ALPHA_MODE_PREMULTIPLIED) != 0; }
+ void __cdecl SetAlphaMode( TEX_ALPHA_MODE mode ) { miscFlags2 = (miscFlags2 & ~TEX_MISC2_ALPHA_MODE_MASK) | static_cast<uint32_t>(mode); }
+ // Helpers for miscFlags2
+
+ bool __cdecl IsVolumemap() const { return (dimension == TEX_DIMENSION_TEXTURE3D); }
+ // Helper for dimension
+ };
+
+ enum DDS_FLAGS
+ {
+ DDS_FLAGS_NONE = 0x0,
+
+ DDS_FLAGS_LEGACY_DWORD = 0x1,
+ // Assume pitch is DWORD aligned instead of BYTE aligned (used by some legacy DDS files)
+
+ DDS_FLAGS_NO_LEGACY_EXPANSION = 0x2,
+ // Do not implicitly convert legacy formats that result in larger pixel sizes (24 bpp, 3:3:2, A8L8, A4L4, P8, A8P8)
+
+ DDS_FLAGS_NO_R10B10G10A2_FIXUP = 0x4,
+ // Do not use work-around for long-standing D3DX DDS file format issue which reversed the 10:10:10:2 color order masks
+
+ DDS_FLAGS_FORCE_RGB = 0x8,
+ // Convert DXGI 1.1 BGR formats to DXGI_FORMAT_R8G8B8A8_UNORM to avoid use of optional WDDM 1.1 formats
+
+ DDS_FLAGS_NO_16BPP = 0x10,
+ // Conversions avoid use of 565, 5551, and 4444 formats and instead expand to 8888 to avoid use of optional WDDM 1.2 formats
+
+ DDS_FLAGS_EXPAND_LUMINANCE = 0x20,
+ // When loading legacy luminance formats expand replicating the color channels rather than leaving them packed (L8, L16, A8L8)
+
+ DDS_FLAGS_FORCE_DX10_EXT = 0x10000,
+ // Always use the 'DX10' header extension for DDS writer (i.e. don't try to write DX9 compatible DDS files)
+
+ DDS_FLAGS_FORCE_DX10_EXT_MISC2 = 0x20000,
+ // DDS_FLAGS_FORCE_DX10_EXT including miscFlags2 information (result may not be compatible with D3DX10 or D3DX11)
+ };
+
+ enum WIC_FLAGS
+ {
+ WIC_FLAGS_NONE = 0x0,
+
+ WIC_FLAGS_FORCE_RGB = 0x1,
+ // Loads DXGI 1.1 BGR formats as DXGI_FORMAT_R8G8B8A8_UNORM to avoid use of optional WDDM 1.1 formats
+
+ WIC_FLAGS_NO_X2_BIAS = 0x2,
+ // Loads DXGI 1.1 X2 10:10:10:2 format as DXGI_FORMAT_R10G10B10A2_UNORM
+
+ WIC_FLAGS_NO_16BPP = 0x4,
+ // Loads 565, 5551, and 4444 formats as 8888 to avoid use of optional WDDM 1.2 formats
+
+ WIC_FLAGS_ALLOW_MONO = 0x8,
+ // Loads 1-bit monochrome (black & white) as R1_UNORM rather than 8-bit grayscale
+
+ WIC_FLAGS_ALL_FRAMES = 0x10,
+ // Loads all images in a multi-frame file, converting/resizing to match the first frame as needed, defaults to 0th frame otherwise
+
+ WIC_FLAGS_IGNORE_SRGB = 0x20,
+ // Ignores sRGB metadata if present in the file
+
+ WIC_FLAGS_DITHER = 0x10000,
+ // Use ordered 4x4 dithering for any required conversions
+
+ WIC_FLAGS_DITHER_DIFFUSION = 0x20000,
+ // Use error-diffusion dithering for any required conversions
+
+ WIC_FLAGS_FILTER_POINT = 0x100000,
+ WIC_FLAGS_FILTER_LINEAR = 0x200000,
+ WIC_FLAGS_FILTER_CUBIC = 0x300000,
+ WIC_FLAGS_FILTER_FANT = 0x400000, // Combination of Linear and Box filter
+ // Filtering mode to use for any required image resizing (only needed when loading arrays of differently sized images; defaults to Fant)
+ };
+
+ HRESULT __cdecl GetMetadataFromDDSMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags,
+ _Out_ TexMetadata& metadata );
+ HRESULT __cdecl GetMetadataFromDDSFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags,
+ _Out_ TexMetadata& metadata );
+
+ HRESULT __cdecl GetMetadataFromTGAMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size,
+ _Out_ TexMetadata& metadata );
+ HRESULT __cdecl GetMetadataFromTGAFile( _In_z_ LPCWSTR szFile,
+ _Out_ TexMetadata& metadata );
+
+ HRESULT __cdecl GetMetadataFromWICMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags,
+ _Out_ TexMetadata& metadata,
+ _In_opt_ std::function<void __cdecl(IWICMetadataQueryReader*)> getMQR = nullptr);
+
+ HRESULT __cdecl GetMetadataFromWICFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags,
+ _Out_ TexMetadata& metadata,
+ _In_opt_ std::function<void __cdecl(IWICMetadataQueryReader*)> getMQR = nullptr);
+
+ //---------------------------------------------------------------------------------
+ // Bitmap image container
+ struct Image
+ {
+ size_t width;
+ size_t height;
+ DXGI_FORMAT format;
+ size_t rowPitch;
+ size_t slicePitch;
+ uint8_t* pixels;
+ };
+
+ class ScratchImage
+ {
+ public:
+ ScratchImage()
+ : _nimages(0), _size(0), _image(nullptr), _memory(nullptr) {}
+ ScratchImage(ScratchImage&& moveFrom)
+ : _nimages(0), _size(0), _image(nullptr), _memory(nullptr) { *this = std::move(moveFrom); }
+ ~ScratchImage() { Release(); }
+
+ ScratchImage& __cdecl operator= (ScratchImage&& moveFrom);
+
+ HRESULT __cdecl Initialize( _In_ const TexMetadata& mdata, _In_ DWORD flags = CP_FLAGS_NONE );
+
+ HRESULT __cdecl Initialize1D( _In_ DXGI_FORMAT fmt, _In_ size_t length, _In_ size_t arraySize, _In_ size_t mipLevels, _In_ DWORD flags = CP_FLAGS_NONE );
+ HRESULT __cdecl Initialize2D( _In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height, _In_ size_t arraySize, _In_ size_t mipLevels, _In_ DWORD flags = CP_FLAGS_NONE );
+ HRESULT __cdecl Initialize3D( _In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height, _In_ size_t depth, _In_ size_t mipLevels, _In_ DWORD flags = CP_FLAGS_NONE );
+ HRESULT __cdecl InitializeCube( _In_ DXGI_FORMAT fmt, _In_ size_t width, _In_ size_t height, _In_ size_t nCubes, _In_ size_t mipLevels, _In_ DWORD flags = CP_FLAGS_NONE );
+
+ HRESULT __cdecl InitializeFromImage( _In_ const Image& srcImage, _In_ bool allow1D = false, _In_ DWORD flags = CP_FLAGS_NONE );
+ HRESULT __cdecl InitializeArrayFromImages( _In_reads_(nImages) const Image* images, _In_ size_t nImages, _In_ bool allow1D = false, _In_ DWORD flags = CP_FLAGS_NONE );
+ HRESULT __cdecl InitializeCubeFromImages( _In_reads_(nImages) const Image* images, _In_ size_t nImages, _In_ DWORD flags = CP_FLAGS_NONE );
+ HRESULT __cdecl Initialize3DFromImages( _In_reads_(depth) const Image* images, _In_ size_t depth, _In_ DWORD flags = CP_FLAGS_NONE );
+
+ void __cdecl Release();
+
+ bool __cdecl OverrideFormat( _In_ DXGI_FORMAT f );
+
+ const TexMetadata& __cdecl GetMetadata() const { return _metadata; }
+ const Image* __cdecl GetImage(_In_ size_t mip, _In_ size_t item, _In_ size_t slice) const;
+
+ const Image* __cdecl GetImages() const { return _image; }
+ size_t __cdecl GetImageCount() const { return _nimages; }
+
+ uint8_t* __cdecl GetPixels() const { return _memory; }
+ size_t __cdecl GetPixelsSize() const { return _size; }
+
+ bool __cdecl IsAlphaAllOpaque() const;
+
+ private:
+ size_t _nimages;
+ size_t _size;
+ TexMetadata _metadata;
+ Image* _image;
+ uint8_t* _memory;
+
+ // Hide copy constructor and assignment operator
+ ScratchImage( const ScratchImage& );
+ ScratchImage& operator=( const ScratchImage& );
+ };
+
+ //---------------------------------------------------------------------------------
+ // Memory blob (allocated buffer pointer is always 16-byte aligned)
+ class Blob
+ {
+ public:
+ Blob() : _buffer(nullptr), _size(0) {}
+ Blob(Blob&& moveFrom) : _buffer(nullptr), _size(0) { *this = std::move(moveFrom); }
+ ~Blob() { Release(); }
+
+ Blob& __cdecl operator= (Blob&& moveFrom);
+
+ HRESULT __cdecl Initialize( _In_ size_t size );
+
+ void __cdecl Release();
+
+ void *__cdecl GetBufferPointer() const { return _buffer; }
+ size_t __cdecl GetBufferSize() const { return _size; }
+
+ private:
+ void* _buffer;
+ size_t _size;
+
+ // Hide copy constructor and assignment operator
+ Blob( const Blob& );
+ Blob& operator=( const Blob& );
+ };
+
+ //---------------------------------------------------------------------------------
+ // Image I/O
+
+ // DDS operations
+ HRESULT __cdecl LoadFromDDSMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags,
+ _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image );
+ HRESULT __cdecl LoadFromDDSFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags,
+ _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image );
+
+ HRESULT __cdecl SaveToDDSMemory( _In_ const Image& image, _In_ DWORD flags,
+ _Out_ Blob& blob );
+ HRESULT __cdecl SaveToDDSMemory( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags,
+ _Out_ Blob& blob );
+
+ HRESULT __cdecl SaveToDDSFile( _In_ const Image& image, _In_ DWORD flags, _In_z_ LPCWSTR szFile );
+ HRESULT __cdecl SaveToDDSFile( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags, _In_z_ LPCWSTR szFile );
+
+ // TGA operations
+ HRESULT __cdecl LoadFromTGAMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size,
+ _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image );
+ HRESULT __cdecl LoadFromTGAFile( _In_z_ LPCWSTR szFile,
+ _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image );
+
+ HRESULT __cdecl SaveToTGAMemory( _In_ const Image& image, _Out_ Blob& blob );
+ HRESULT __cdecl SaveToTGAFile( _In_ const Image& image, _In_z_ LPCWSTR szFile );
+
+ // WIC operations
+ HRESULT __cdecl LoadFromWICMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags,
+ _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image,
+ _In_opt_ std::function<void __cdecl(IWICMetadataQueryReader*)> getMQR = nullptr);
+ HRESULT __cdecl LoadFromWICFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags,
+ _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image,
+ _In_opt_ std::function<void __cdecl(IWICMetadataQueryReader*)> getMQR = nullptr);
+
+ HRESULT __cdecl SaveToWICMemory( _In_ const Image& image, _In_ DWORD flags, _In_ REFGUID guidContainerFormat,
+ _Out_ Blob& blob, _In_opt_ const GUID* targetFormat = nullptr,
+ _In_opt_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr );
+ HRESULT __cdecl SaveToWICMemory( _In_count_(nimages) const Image* images, _In_ size_t nimages, _In_ DWORD flags, _In_ REFGUID guidContainerFormat,
+ _Out_ Blob& blob, _In_opt_ const GUID* targetFormat = nullptr,
+ _In_opt_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr );
+
+ HRESULT __cdecl SaveToWICFile( _In_ const Image& image, _In_ DWORD flags, _In_ REFGUID guidContainerFormat,
+ _In_z_ LPCWSTR szFile, _In_opt_ const GUID* targetFormat = nullptr,
+ _In_opt_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr );
+ HRESULT __cdecl SaveToWICFile( _In_count_(nimages) const Image* images, _In_ size_t nimages, _In_ DWORD flags, _In_ REFGUID guidContainerFormat,
+ _In_z_ LPCWSTR szFile, _In_opt_ const GUID* targetFormat = nullptr,
+ _In_opt_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr );
+
+ //---------------------------------------------------------------------------------
+ // Texture conversion, resizing, mipmap generation, and block compression
+
+ enum TEX_FR_FLAGS
+ {
+ TEX_FR_ROTATE0 = 0x0,
+ TEX_FR_ROTATE90 = 0x1,
+ TEX_FR_ROTATE180 = 0x2,
+ TEX_FR_ROTATE270 = 0x3,
+ TEX_FR_FLIP_HORIZONTAL = 0x08,
+ TEX_FR_FLIP_VERTICAL = 0x10,
+ };
+
+ HRESULT __cdecl FlipRotate( _In_ const Image& srcImage, _In_ DWORD flags, _Out_ ScratchImage& image );
+ HRESULT __cdecl FlipRotate( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DWORD flags, _Out_ ScratchImage& result );
+ // Flip and/or rotate image
+
+ enum TEX_FILTER_FLAGS
+ {
+ TEX_FILTER_DEFAULT = 0,
+
+ TEX_FILTER_WRAP_U = 0x1,
+ TEX_FILTER_WRAP_V = 0x2,
+ TEX_FILTER_WRAP_W = 0x4,
+ TEX_FILTER_WRAP = ( TEX_FILTER_WRAP_U | TEX_FILTER_WRAP_V | TEX_FILTER_WRAP_W ),
+ TEX_FILTER_MIRROR_U = 0x10,
+ TEX_FILTER_MIRROR_V = 0x20,
+ TEX_FILTER_MIRROR_W = 0x40,
+ TEX_FILTER_MIRROR = ( TEX_FILTER_MIRROR_U | TEX_FILTER_MIRROR_V | TEX_FILTER_MIRROR_W ),
+ // Wrap vs. Mirror vs. Clamp filtering options
+
+ TEX_FILTER_SEPARATE_ALPHA = 0x100,
+ // Resize color and alpha channel independently
+
+ TEX_FILTER_RGB_COPY_RED = 0x1000,
+ TEX_FILTER_RGB_COPY_GREEN = 0x2000,
+ TEX_FILTER_RGB_COPY_BLUE = 0x4000,
+ // When converting RGB to R, defaults to using grayscale. These flags indicate copying a specific channel instead
+ // When converting RGB to RG, defaults to copying RED | GREEN. These flags control which channels are selected instead.
+
+ TEX_FILTER_DITHER = 0x10000,
+ // Use ordered 4x4 dithering for any required conversions
+ TEX_FILTER_DITHER_DIFFUSION = 0x20000,
+ // Use error-diffusion dithering for any required conversions
+
+ TEX_FILTER_POINT = 0x100000,
+ TEX_FILTER_LINEAR = 0x200000,
+ TEX_FILTER_CUBIC = 0x300000,
+ TEX_FILTER_BOX = 0x400000,
+ TEX_FILTER_FANT = 0x400000, // Equiv to Box filtering for mipmap generation
+ TEX_FILTER_TRIANGLE = 0x500000,
+ // Filtering mode to use for any required image resizing
+
+ TEX_FILTER_SRGB_IN = 0x1000000,
+ TEX_FILTER_SRGB_OUT = 0x2000000,
+ TEX_FILTER_SRGB = ( TEX_FILTER_SRGB_IN | TEX_FILTER_SRGB_OUT ),
+ // sRGB <-> RGB for use in conversion operations
+ // if the input format type is IsSRGB(), then SRGB_IN is on by default
+ // if the output format type is IsSRGB(), then SRGB_OUT is on by default
+
+ TEX_FILTER_FORCE_NON_WIC = 0x10000000,
+ // Forces use of the non-WIC path when both are an option
+
+ TEX_FILTER_FORCE_WIC = 0x20000000,
+ // Forces use of the WIC path even when logic would have picked a non-WIC path when both are an option
+ };
+
+ HRESULT __cdecl Resize( _In_ const Image& srcImage, _In_ size_t width, _In_ size_t height, _In_ DWORD filter,
+ _Out_ ScratchImage& image );
+ HRESULT __cdecl Resize( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ size_t width, _In_ size_t height, _In_ DWORD filter, _Out_ ScratchImage& result );
+ // Resize the image to width x height. Defaults to Fant filtering.
+ // Note for a complex resize, the result will always have mipLevels == 1
+
+ HRESULT __cdecl Convert( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD filter, _In_ float threshold,
+ _Out_ ScratchImage& image );
+ HRESULT __cdecl Convert( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DXGI_FORMAT format, _In_ DWORD filter, _In_ float threshold, _Out_ ScratchImage& result );
+ // Convert the image to a new format
+
+ HRESULT __cdecl ConvertToSinglePlane( _In_ const Image& srcImage, _Out_ ScratchImage& image );
+ HRESULT __cdecl ConvertToSinglePlane( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _Out_ ScratchImage& image );
+ // Converts the image from a planar format to an equivalent non-planar format
+
+ HRESULT __cdecl GenerateMipMaps( _In_ const Image& baseImage, _In_ DWORD filter, _In_ size_t levels,
+ _Inout_ ScratchImage& mipChain, _In_ bool allow1D = false );
+ HRESULT __cdecl GenerateMipMaps( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DWORD filter, _In_ size_t levels, _Inout_ ScratchImage& mipChain );
+ // levels of '0' indicates a full mipchain, otherwise is generates that number of total levels (including the source base image)
+ // Defaults to Fant filtering which is equivalent to a box filter
+
+ HRESULT __cdecl GenerateMipMaps3D( _In_reads_(depth) const Image* baseImages, _In_ size_t depth, _In_ DWORD filter, _In_ size_t levels,
+ _Out_ ScratchImage& mipChain );
+ HRESULT __cdecl GenerateMipMaps3D( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DWORD filter, _In_ size_t levels, _Out_ ScratchImage& mipChain );
+ // levels of '0' indicates a full mipchain, otherwise is generates that number of total levels (including the source base image)
+ // Defaults to Fant filtering which is equivalent to a box filter
+
+ enum TEX_PMALPHA_FLAGS
+ {
+ TEX_PMALPHA_DEFAULT = 0,
+
+ TEX_PMALPHA_IGNORE_SRGB = 0x1,
+ // ignores sRGB colorspace conversions
+
+ TEX_PMALPHA_SRGB_IN = 0x1000000,
+ TEX_PMALPHA_SRGB_OUT = 0x2000000,
+ TEX_PMALPHA_SRGB = ( TEX_PMALPHA_SRGB_IN | TEX_PMALPHA_SRGB_OUT ),
+ // if the input format type is IsSRGB(), then SRGB_IN is on by default
+ // if the output format type is IsSRGB(), then SRGB_OUT is on by default
+ };
+
+ HRESULT __cdecl PremultiplyAlpha( _In_ const Image& srcImage, _In_ DWORD flags, _Out_ ScratchImage& image );
+ HRESULT __cdecl PremultiplyAlpha( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags, _Out_ ScratchImage& result );
+ // Converts to a premultiplied alpha version of the texture
+
+ enum TEX_COMPRESS_FLAGS
+ {
+ TEX_COMPRESS_DEFAULT = 0,
+
+ TEX_COMPRESS_RGB_DITHER = 0x10000,
+ // Enables dithering RGB colors for BC1-3 compression
+
+ TEX_COMPRESS_A_DITHER = 0x20000,
+ // Enables dithering alpha for BC1-3 compression
+
+ TEX_COMPRESS_DITHER = 0x30000,
+ // Enables both RGB and alpha dithering for BC1-3 compression
+
+ TEX_COMPRESS_UNIFORM = 0x40000,
+ // Uniform color weighting for BC1-3 compression; by default uses perceptual weighting
+
+ TEX_COMPRESS_BC7_USE_3SUBSETS = 0x80000,
+ // Enables exhaustive search for BC7 compress for mode 0 and 2; by default skips trying these modes
+
+ TEX_COMPRESS_SRGB_IN = 0x1000000,
+ TEX_COMPRESS_SRGB_OUT = 0x2000000,
+ TEX_COMPRESS_SRGB = ( TEX_COMPRESS_SRGB_IN | TEX_COMPRESS_SRGB_OUT ),
+ // if the input format type is IsSRGB(), then SRGB_IN is on by default
+ // if the output format type is IsSRGB(), then SRGB_OUT is on by default
+
+ TEX_COMPRESS_PARALLEL = 0x10000000,
+ // Compress is free to use multithreading to improve performance (by default it does not use multithreading)
+ };
+
+ HRESULT __cdecl Compress( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaRef,
+ _Out_ ScratchImage& cImage );
+ HRESULT __cdecl Compress( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaRef, _Out_ ScratchImage& cImages );
+ // Note that alphaRef is only used by BC1. 0.5f is a typical value to use
+
+ HRESULT __cdecl Compress( _In_ ID3D11Device* pDevice, _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD compress,
+ _In_ float alphaWeight, _Out_ ScratchImage& image );
+ HRESULT __cdecl Compress( _In_ ID3D11Device* pDevice, _In_ const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaWeight, _Out_ ScratchImage& cImages );
+ // DirectCompute-based compression (alphaWeight is only used by BC7. 1.0 is the typical value to use)
+
+ HRESULT __cdecl Decompress( _In_ const Image& cImage, _In_ DXGI_FORMAT format, _Out_ ScratchImage& image );
+ HRESULT __cdecl Decompress( _In_reads_(nimages) const Image* cImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DXGI_FORMAT format, _Out_ ScratchImage& images );
+
+ //---------------------------------------------------------------------------------
+ // Normal map operations
+
+ enum CNMAP_FLAGS
+ {
+ CNMAP_DEFAULT = 0,
+
+ CNMAP_CHANNEL_RED = 0x1,
+ CNMAP_CHANNEL_GREEN = 0x2,
+ CNMAP_CHANNEL_BLUE = 0x3,
+ CNMAP_CHANNEL_ALPHA = 0x4,
+ CNMAP_CHANNEL_LUMINANCE = 0x5,
+ // Channel selection when evaluting color value for height
+ // Luminance is a combination of red, green, and blue
+
+ CNMAP_MIRROR_U = 0x1000,
+ CNMAP_MIRROR_V = 0x2000,
+ CNMAP_MIRROR = 0x3000,
+ // Use mirror semantics for scanline references (defaults to wrap)
+
+ CNMAP_INVERT_SIGN = 0x4000,
+ // Inverts normal sign
+
+ CNMAP_COMPUTE_OCCLUSION = 0x8000,
+ // Computes a crude occlusion term stored in the alpha channel
+ };
+
+ HRESULT __cdecl ComputeNormalMap( _In_ const Image& srcImage, _In_ DWORD flags, _In_ float amplitude,
+ _In_ DXGI_FORMAT format, _Out_ ScratchImage& normalMap );
+ HRESULT __cdecl ComputeNormalMap( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DWORD flags, _In_ float amplitude, _In_ DXGI_FORMAT format, _Out_ ScratchImage& normalMaps );
+
+ //---------------------------------------------------------------------------------
+ // Misc image operations
+
+ struct Rect
+ {
+ size_t x;
+ size_t y;
+ size_t w;
+ size_t h;
+
+ Rect() = default;
+ Rect( size_t _x, size_t _y, size_t _w, size_t _h ) : x(_x), y(_y), w(_w), h(_h) {}
+ };
+
+ HRESULT __cdecl CopyRectangle( _In_ const Image& srcImage, _In_ const Rect& srcRect, _In_ const Image& dstImage,
+ _In_ DWORD filter, _In_ size_t xOffset, _In_ size_t yOffset );
+
+ enum CMSE_FLAGS
+ {
+ CMSE_DEFAULT = 0,
+
+ CMSE_IMAGE1_SRGB = 0x1,
+ CMSE_IMAGE2_SRGB = 0x2,
+ // Indicates that image needs gamma correction before comparision
+
+ CMSE_IGNORE_RED = 0x10,
+ CMSE_IGNORE_GREEN = 0x20,
+ CMSE_IGNORE_BLUE = 0x40,
+ CMSE_IGNORE_ALPHA = 0x80,
+ // Ignore the channel when computing MSE
+
+ CMSE_IMAGE1_X2_BIAS = 0x100,
+ CMSE_IMAGE2_X2_BIAS = 0x200,
+ // Indicates that image should be scaled and biased before comparison (i.e. UNORM -> SNORM)
+ };
+
+ HRESULT __cdecl ComputeMSE( _In_ const Image& image1, _In_ const Image& image2, _Out_ float& mse, _Out_writes_opt_(4) float* mseV, _In_ DWORD flags = 0 );
+
+ //---------------------------------------------------------------------------------
+ // WIC utility code
+
+ enum WICCodecs
+ {
+ WIC_CODEC_BMP = 1, // Windows Bitmap (.bmp)
+ WIC_CODEC_JPEG, // Joint Photographic Experts Group (.jpg, .jpeg)
+ WIC_CODEC_PNG, // Portable Network Graphics (.png)
+ WIC_CODEC_TIFF, // Tagged Image File Format (.tif, .tiff)
+ WIC_CODEC_GIF, // Graphics Interchange Format (.gif)
+ WIC_CODEC_WMP, // Windows Media Photo / HD Photo / JPEG XR (.hdp, .jxr, .wdp)
+ WIC_CODEC_ICO, // Windows Icon (.ico)
+ };
+
+ REFGUID __cdecl GetWICCodec(_In_ WICCodecs codec);
+
+ IWICImagingFactory* __cdecl GetWICFactory( bool& iswic2 );
+ void __cdecl SetWICFactory( _In_opt_ IWICImagingFactory* pWIC);
+
+ //---------------------------------------------------------------------------------
+ // Direct3D 11 functions
+ bool __cdecl IsSupportedTexture( _In_ ID3D11Device* pDevice, _In_ const TexMetadata& metadata );
+
+ HRESULT __cdecl CreateTexture( _In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _Outptr_ ID3D11Resource** ppResource );
+
+ HRESULT __cdecl CreateShaderResourceView( _In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _Outptr_ ID3D11ShaderResourceView** ppSRV );
+
+ HRESULT __cdecl CreateTextureEx( _In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ bool forceSRGB,
+ _Outptr_ ID3D11Resource** ppResource );
+
+ HRESULT __cdecl CreateShaderResourceViewEx( _In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ D3D11_USAGE usage, _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, _In_ bool forceSRGB,
+ _Outptr_ ID3D11ShaderResourceView** ppSRV );
+
+ HRESULT __cdecl CaptureTexture( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _Out_ ScratchImage& result );
+
+#include "DirectXTex.inl"
+
+}; // namespace
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.inl b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.inl
new file mode 100644
index 0000000..605c2c8
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTex.inl
@@ -0,0 +1,130 @@
+//-------------------------------------------------------------------------------------
+// DirectXTex.inl
+//
+// DirectX Texture Library
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+//=====================================================================================
+// DXGI Format Utilities
+//=====================================================================================
+
+_Use_decl_annotations_
+inline bool __cdecl IsValid( DXGI_FORMAT fmt )
+{
+ return ( static_cast<size_t>(fmt) >= 1 && static_cast<size_t>(fmt) <= 190 );
+}
+
+_Use_decl_annotations_
+inline bool __cdecl IsCompressed(DXGI_FORMAT fmt)
+{
+ switch ( fmt )
+ {
+ case DXGI_FORMAT_BC1_TYPELESS:
+ case DXGI_FORMAT_BC1_UNORM:
+ case DXGI_FORMAT_BC1_UNORM_SRGB:
+ case DXGI_FORMAT_BC2_TYPELESS:
+ case DXGI_FORMAT_BC2_UNORM:
+ case DXGI_FORMAT_BC2_UNORM_SRGB:
+ case DXGI_FORMAT_BC3_TYPELESS:
+ case DXGI_FORMAT_BC3_UNORM:
+ case DXGI_FORMAT_BC3_UNORM_SRGB:
+ case DXGI_FORMAT_BC4_TYPELESS:
+ case DXGI_FORMAT_BC4_UNORM:
+ case DXGI_FORMAT_BC4_SNORM:
+ case DXGI_FORMAT_BC5_TYPELESS:
+ case DXGI_FORMAT_BC5_UNORM:
+ case DXGI_FORMAT_BC5_SNORM:
+ case DXGI_FORMAT_BC6H_TYPELESS:
+ case DXGI_FORMAT_BC6H_UF16:
+ case DXGI_FORMAT_BC6H_SF16:
+ case DXGI_FORMAT_BC7_TYPELESS:
+ case DXGI_FORMAT_BC7_UNORM:
+ case DXGI_FORMAT_BC7_UNORM_SRGB:
+ return true;
+
+ default:
+ return false;
+ }
+}
+
+_Use_decl_annotations_
+inline bool __cdecl IsPalettized(DXGI_FORMAT fmt)
+{
+ switch( fmt )
+ {
+ case DXGI_FORMAT_AI44:
+ case DXGI_FORMAT_IA44:
+ case DXGI_FORMAT_P8:
+ case DXGI_FORMAT_A8P8:
+ return true;
+
+ default:
+ return false;
+ }
+}
+
+_Use_decl_annotations_
+inline bool __cdecl IsSRGB(DXGI_FORMAT fmt)
+{
+ switch( fmt )
+ {
+ case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
+ case DXGI_FORMAT_BC1_UNORM_SRGB:
+ case DXGI_FORMAT_BC2_UNORM_SRGB:
+ case DXGI_FORMAT_BC3_UNORM_SRGB:
+ case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
+ case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
+ case DXGI_FORMAT_BC7_UNORM_SRGB:
+ return true;
+
+ default:
+ return false;
+ }
+}
+
+
+//=====================================================================================
+// Image I/O
+//=====================================================================================
+_Use_decl_annotations_
+inline HRESULT __cdecl SaveToDDSMemory(const Image& image, DWORD flags, Blob& blob)
+{
+ TexMetadata mdata;
+ memset( &mdata, 0, sizeof(mdata) );
+ mdata.width = image.width;
+ mdata.height = image.height;
+ mdata.depth = 1;
+ mdata.arraySize = 1;
+ mdata.mipLevels = 1;
+ mdata.format = image.format;
+ mdata.dimension = TEX_DIMENSION_TEXTURE2D;
+
+ return SaveToDDSMemory( &image, 1, mdata, flags, blob );
+}
+
+_Use_decl_annotations_
+inline HRESULT __cdecl SaveToDDSFile(const Image& image, DWORD flags, LPCWSTR szFile)
+{
+ TexMetadata mdata;
+ memset( &mdata, 0, sizeof(mdata) );
+ mdata.width = image.width;
+ mdata.height = image.height;
+ mdata.depth = 1;
+ mdata.arraySize = 1;
+ mdata.mipLevels = 1;
+ mdata.format = image.format;
+ mdata.dimension = TEX_DIMENSION_TEXTURE2D;
+
+ return SaveToDDSFile( &image, 1, mdata, flags, szFile );
+}
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTexP.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTexP.h
new file mode 100644
index 0000000..269c11d
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/DirectXTexP.h
@@ -0,0 +1,230 @@
+//-------------------------------------------------------------------------------------
+// DirectXTexp.h
+//
+// DirectX Texture Library - Private header
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//
+// http://go.microsoft.com/fwlink/?LinkId=248926
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+#pragma warning(push)
+#pragma warning(disable : 4005)
+#define WIN32_LEAN_AND_MEAN
+#define NOMINMAX
+#define NODRAWTEXT
+#define NOGDI
+#define NOBITMAP
+#define NOMCX
+#define NOSERVICE
+#define NOHELP
+#pragma warning(pop)
+
+#ifndef _WIN32_WINNT_WIN10
+#define _WIN32_WINNT_WIN10 0x0A00
+#endif
+
+#include <windows.h>
+#include <directxmath.h>
+#include <directxpackedvector.h>
+#include <assert.h>
+
+#include <malloc.h>
+#include <memory>
+
+#include <vector>
+
+#include <stdlib.h>
+#include <search.h>
+
+#include <ole2.h>
+
+#include "directxtex.h"
+
+#include <wincodec.h>
+
+#include <wrl\client.h>
+
+#include "scoped.h"
+
+#define TEX_FILTER_MASK 0xF00000
+
+#define XBOX_DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT DXGI_FORMAT(116)
+#define XBOX_DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT DXGI_FORMAT(117)
+#define XBOX_DXGI_FORMAT_D16_UNORM_S8_UINT DXGI_FORMAT(118)
+#define XBOX_DXGI_FORMAT_R16_UNORM_X8_TYPELESS DXGI_FORMAT(119)
+#define XBOX_DXGI_FORMAT_X16_TYPELESS_G8_UINT DXGI_FORMAT(120)
+
+#define WIN10_DXGI_FORMAT_P208 DXGI_FORMAT(130)
+#define WIN10_DXGI_FORMAT_V208 DXGI_FORMAT(131)
+#define WIN10_DXGI_FORMAT_V408 DXGI_FORMAT(132)
+
+#ifndef XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM
+#define XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM DXGI_FORMAT(189)
+#endif
+
+#define XBOX_DXGI_FORMAT_R4G4_UNORM DXGI_FORMAT(190)
+
+
+namespace DirectX
+{
+ //---------------------------------------------------------------------------------
+ // WIC helper functions
+ DXGI_FORMAT __cdecl _WICToDXGI( _In_ const GUID& guid );
+ bool __cdecl _DXGIToWIC( _In_ DXGI_FORMAT format, _Out_ GUID& guid, _In_ bool ignoreRGBvsBGR = false );
+
+ DWORD __cdecl _CheckWICColorSpace( _In_ const GUID& sourceGUID, _In_ const GUID& targetGUID );
+
+ inline WICBitmapDitherType __cdecl _GetWICDither( _In_ DWORD flags )
+ {
+ static_assert( TEX_FILTER_DITHER == 0x10000, "TEX_FILTER_DITHER* flag values don't match mask" );
+
+ static_assert( TEX_FILTER_DITHER == WIC_FLAGS_DITHER, "TEX_FILTER_DITHER* should match WIC_FLAGS_DITHER*" );
+ static_assert( TEX_FILTER_DITHER_DIFFUSION == WIC_FLAGS_DITHER_DIFFUSION, "TEX_FILTER_DITHER* should match WIC_FLAGS_DITHER*" );
+
+ switch( flags & 0xF0000 )
+ {
+ case TEX_FILTER_DITHER:
+ return WICBitmapDitherTypeOrdered4x4;
+
+ case TEX_FILTER_DITHER_DIFFUSION:
+ return WICBitmapDitherTypeErrorDiffusion;
+
+ default:
+ return WICBitmapDitherTypeNone;
+ }
+ }
+
+ inline WICBitmapInterpolationMode __cdecl _GetWICInterp( _In_ DWORD flags )
+ {
+ static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" );
+
+ static_assert( TEX_FILTER_POINT == WIC_FLAGS_FILTER_POINT, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" );
+ static_assert( TEX_FILTER_LINEAR == WIC_FLAGS_FILTER_LINEAR, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" );
+ static_assert( TEX_FILTER_CUBIC == WIC_FLAGS_FILTER_CUBIC, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" );
+ static_assert( TEX_FILTER_FANT == WIC_FLAGS_FILTER_FANT, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" );
+
+ switch( flags & TEX_FILTER_MASK )
+ {
+ case TEX_FILTER_POINT:
+ return WICBitmapInterpolationModeNearestNeighbor;
+
+ case TEX_FILTER_LINEAR:
+ return WICBitmapInterpolationModeLinear;
+
+ case TEX_FILTER_CUBIC:
+ return WICBitmapInterpolationModeCubic;
+
+ case TEX_FILTER_FANT:
+ default:
+ return WICBitmapInterpolationModeFant;
+ }
+ }
+
+ //---------------------------------------------------------------------------------
+ // Image helper functions
+ void __cdecl _DetermineImageArray( _In_ const TexMetadata& metadata, _In_ DWORD cpFlags,
+ _Out_ size_t& nImages, _Out_ size_t& pixelSize );
+
+ _Success_(return != false)
+ bool __cdecl _SetupImageArray( _In_reads_bytes_(pixelSize) uint8_t *pMemory, _In_ size_t pixelSize,
+ _In_ const TexMetadata& metadata, _In_ DWORD cpFlags,
+ _Out_writes_(nImages) Image* images, _In_ size_t nImages );
+
+ //---------------------------------------------------------------------------------
+ // Conversion helper functions
+
+ enum TEXP_SCANLINE_FLAGS
+ {
+ TEXP_SCANLINE_NONE = 0,
+ TEXP_SCANLINE_SETALPHA = 0x1, // Set alpha channel to known opaque value
+ TEXP_SCANLINE_LEGACY = 0x2, // Enables specific legacy format conversion cases
+ };
+
+ enum CONVERT_FLAGS
+ {
+ CONVF_FLOAT = 0x1,
+ CONVF_UNORM = 0x2,
+ CONVF_UINT = 0x4,
+ CONVF_SNORM = 0x8,
+ CONVF_SINT = 0x10,
+ CONVF_DEPTH = 0x20,
+ CONVF_STENCIL = 0x40,
+ CONVF_SHAREDEXP = 0x80,
+ CONVF_BGR = 0x100,
+ CONVF_XR = 0x200,
+ CONVF_PACKED = 0x400,
+ CONVF_BC = 0x800,
+ CONVF_YUV = 0x1000,
+ CONVF_R = 0x10000,
+ CONVF_G = 0x20000,
+ CONVF_B = 0x40000,
+ CONVF_A = 0x80000,
+ CONVF_RGB_MASK = 0x70000,
+ CONVF_RGBA_MASK = 0xF0000,
+ };
+
+ DWORD __cdecl _GetConvertFlags( _In_ DXGI_FORMAT format );
+
+ void __cdecl _CopyScanline( _When_(pDestination == pSource, _Inout_updates_bytes_(outSize))
+ _When_(pDestination != pSource, _Out_writes_bytes_(outSize))
+ LPVOID pDestination, _In_ size_t outSize,
+ _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize,
+ _In_ DXGI_FORMAT format, _In_ DWORD flags );
+
+ void __cdecl _SwizzleScanline( _When_(pDestination == pSource, _In_)
+ _When_(pDestination != pSource, _Out_writes_bytes_(outSize))
+ LPVOID pDestination, _In_ size_t outSize,
+ _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize,
+ _In_ DXGI_FORMAT format, _In_ DWORD flags );
+
+ _Success_(return != false)
+ bool __cdecl _ExpandScanline( _Out_writes_bytes_(outSize) LPVOID pDestination, _In_ size_t outSize,
+ _In_ DXGI_FORMAT outFormat,
+ _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize,
+ _In_ DXGI_FORMAT inFormat, _In_ DWORD flags );
+
+ _Success_(return != false)
+ bool __cdecl _LoadScanline( _Out_writes_(count) XMVECTOR* pDestination, _In_ size_t count,
+ _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DXGI_FORMAT format );
+
+ _Success_(return != false)
+ bool __cdecl _LoadScanlineLinear( _Out_writes_(count) XMVECTOR* pDestination, _In_ size_t count,
+ _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DXGI_FORMAT format, _In_ DWORD flags );
+
+ _Success_(return != false)
+ bool __cdecl _StoreScanline( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format,
+ _In_reads_(count) const XMVECTOR* pSource, _In_ size_t count, _In_ float threshold = 0 );
+
+ _Success_(return != false)
+ bool __cdecl _StoreScanlineLinear( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format,
+ _Inout_updates_all_(count) XMVECTOR* pSource, _In_ size_t count, _In_ DWORD flags, _In_ float threshold = 0 );
+
+ _Success_(return != false)
+ bool __cdecl _StoreScanlineDither( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format,
+ _Inout_updates_all_(count) XMVECTOR* pSource, _In_ size_t count, _In_ float threshold, size_t y, size_t z,
+ _Inout_updates_all_opt_(count+2) XMVECTOR* pDiffusionErrors );
+
+ HRESULT __cdecl _ConvertToR32G32B32A32( _In_ const Image& srcImage, _Inout_ ScratchImage& image );
+
+ HRESULT __cdecl _ConvertFromR32G32B32A32( _In_ const Image& srcImage, _In_ const Image& destImage );
+ HRESULT __cdecl _ConvertFromR32G32B32A32( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _Inout_ ScratchImage& image );
+ HRESULT __cdecl _ConvertFromR32G32B32A32( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata,
+ _In_ DXGI_FORMAT format, _Out_ ScratchImage& result );
+
+ void __cdecl _ConvertScanline( _Inout_updates_all_(count) XMVECTOR* pBuffer, _In_ size_t count,
+ _In_ DXGI_FORMAT outFormat, _In_ DXGI_FORMAT inFormat, _In_ DWORD flags );
+
+ //---------------------------------------------------------------------------------
+ // DDS helper functions
+ HRESULT __cdecl _EncodeDDSHeader( _In_ const TexMetadata& metadata, DWORD flags,
+ _Out_writes_bytes_to_opt_(maxsize, required) LPVOID pDestination, _In_ size_t maxsize, _Out_ size_t& required );
+
+}; // namespace
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/Filters.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/Filters.h
new file mode 100644
index 0000000..c65eb77
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/Filters.h
@@ -0,0 +1,422 @@
+//-------------------------------------------------------------------------------------
+// filters.h
+//
+// Utility header with helpers for implementing image filters
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+#include <directxmath.h>
+#include <directxpackedvector.h>
+
+#include <memory>
+
+#include "scoped.h"
+
+namespace DirectX
+{
+
+//-------------------------------------------------------------------------------------
+// Box filtering helpers
+//-------------------------------------------------------------------------------------
+
+XMGLOBALCONST XMVECTORF32 g_boxScale = { 0.25f, 0.25f, 0.25f, 0.25f };
+XMGLOBALCONST XMVECTORF32 g_boxScale3D = { 0.125f, 0.125f, 0.125f, 0.125f };
+
+#define AVERAGE4( res, p0, p1, p2, p3 ) \
+{ \
+ XMVECTOR v = XMVectorAdd( (p0), (p1) ); \
+ v = XMVectorAdd( v, (p2) ); \
+ v = XMVectorAdd( v, (p3) ); \
+ res = XMVectorMultiply( v, g_boxScale ); \
+}
+
+#define AVERAGE8( res, p0, p1, p2, p3, p4, p5, p6, p7) \
+{ \
+ XMVECTOR v = XMVectorAdd( (p0), (p1) ); \
+ v = XMVectorAdd( v, (p2) ); \
+ v = XMVectorAdd( v, (p3) ); \
+ v = XMVectorAdd( v, (p4) ); \
+ v = XMVectorAdd( v, (p5) ); \
+ v = XMVectorAdd( v, (p6) ); \
+ v = XMVectorAdd( v, (p7) ); \
+ res = XMVectorMultiply( v, g_boxScale3D ); \
+}
+
+
+//-------------------------------------------------------------------------------------
+// Linear filtering helpers
+//-------------------------------------------------------------------------------------
+
+struct LinearFilter
+{
+ size_t u0;
+ float weight0;
+ size_t u1;
+ float weight1;
+};
+
+inline void _CreateLinearFilter( _In_ size_t source, _In_ size_t dest, _In_ bool wrap, _Out_writes_(dest) LinearFilter* lf )
+{
+ assert( source > 0 );
+ assert( dest > 0 );
+ assert( lf != 0 );
+
+ float scale = float(source) / float(dest);
+
+ // Mirror is the same case as clamp for linear
+
+ for( size_t u = 0; u < dest; ++u )
+ {
+ float srcB = ( float(u) + 0.5f ) * scale + 0.5f;
+
+ ptrdiff_t isrcB = ptrdiff_t(srcB);
+ ptrdiff_t isrcA = isrcB - 1;
+
+ if ( isrcA < 0 )
+ {
+ isrcA = ( wrap ) ? ( source - 1) : 0;
+ }
+
+ if ( size_t(isrcB) >= source )
+ {
+ isrcB = ( wrap ) ? 0 : ( source - 1);
+ }
+
+ float weight = 1.0f + float(isrcB) - srcB;
+
+ auto& entry = lf[ u ];
+ entry.u0 = size_t(isrcA);
+ entry.weight0 = weight;
+
+ entry.u1 = size_t(isrcB);
+ entry.weight1 = 1.0f - weight;
+ }
+}
+
+#define BILINEAR_INTERPOLATE( res, x, y, r0, r1 ) \
+ res = ( y.weight0 * ( (r0)[ x.u0 ] * x.weight0 + (r0)[ x.u1 ] * x.weight1 ) ) \
+ + ( y.weight1 * ( (r1)[ x.u0 ] * x.weight0 + (r1)[ x.u1 ] * x.weight1 ) )
+
+#define TRILINEAR_INTERPOLATE( res, x, y, z, r0, r1, r2, r3 ) \
+ res = ( z.weight0 * ( ( y.weight0 * ( (r0)[ x.u0 ] * x.weight0 + (r0)[ x.u1 ] * x.weight1 ) ) \
+ + ( y.weight1 * ( (r1)[ x.u0 ] * x.weight0 + (r1)[ x.u1 ] * x.weight1 ) ) ) ) \
+ + ( z.weight1 * ( ( y.weight0 * ( (r2)[ x.u0 ] * x.weight0 + (r2)[ x.u1 ] * x.weight1 ) ) \
+ + ( y.weight1 * ( (r3)[ x.u0 ] * x.weight0 + (r3)[ x.u1 ] * x.weight1 ) ) ) )
+
+
+//-------------------------------------------------------------------------------------
+// Cubic filtering helpers
+//-------------------------------------------------------------------------------------
+
+XMGLOBALCONST XMVECTORF32 g_cubicThird = { 1.f/3.f, 1.f/3.f, 1.f/3.f, 1.f/3.f };
+XMGLOBALCONST XMVECTORF32 g_cubicSixth = { 1.f/6.f, 1.f/6.f, 1.f/6.f, 1.f/6.f };
+XMGLOBALCONST XMVECTORF32 g_cubicHalf = { 1.f/2.f, 1.f/2.f, 1.f/2.f, 1.f/2.f };
+
+inline ptrdiff_t bounduvw( ptrdiff_t u, ptrdiff_t maxu, bool wrap, bool mirror )
+{
+ if ( wrap )
+ {
+ if ( u < 0 )
+ {
+ u = maxu + u + 1;
+ }
+ else if ( u > maxu )
+ {
+ u = u - maxu - 1;
+ }
+ }
+ else if ( mirror )
+ {
+ if ( u < 0 )
+ {
+ u = ( -u ) - 1;
+ }
+ else if ( u > maxu )
+ {
+ u = maxu - (u - maxu - 1);
+ }
+ }
+
+ // Handles clamp, but also a safety factor for degenerate images for wrap/mirror
+ u = std::min<ptrdiff_t>( u, maxu );
+ u = std::max<ptrdiff_t>( u, 0 );
+
+ return u;
+}
+
+struct CubicFilter
+{
+ size_t u0;
+ size_t u1;
+ size_t u2;
+ size_t u3;
+ float x;
+};
+
+inline void _CreateCubicFilter( _In_ size_t source, _In_ size_t dest, _In_ bool wrap, _In_ bool mirror, _Out_writes_(dest) CubicFilter* cf )
+{
+ assert( source > 0 );
+ assert( dest > 0 );
+ assert( cf != 0 );
+
+ float scale = float(source) / float(dest);
+
+ for( size_t u = 0; u < dest; ++u )
+ {
+ float srcB = ( float(u) + 0.5f ) * scale - 0.5f;
+
+ ptrdiff_t isrcB = bounduvw( ptrdiff_t(srcB), source - 1, wrap, mirror );
+ ptrdiff_t isrcA = bounduvw( isrcB - 1, source - 1, wrap, mirror );
+ ptrdiff_t isrcC = bounduvw( isrcB + 1, source - 1, wrap, mirror );
+ ptrdiff_t isrcD = bounduvw( isrcB + 2, source - 1, wrap, mirror );
+
+ auto& entry = cf[ u ];
+ entry.u0 = size_t(isrcA);
+ entry.u1 = size_t(isrcB);
+ entry.u2 = size_t(isrcC);
+ entry.u3 = size_t(isrcD);
+
+ float x = srcB - float(isrcB);
+ entry.x = x;
+ }
+}
+
+#define CUBIC_INTERPOLATE( res, dx, p0, p1, p2, p3 ) \
+{ \
+ XMVECTOR a0 = (p1); \
+ XMVECTOR d0 = (p0) - a0; \
+ XMVECTOR d2 = (p2) - a0; \
+ XMVECTOR d3 = (p3) - a0; \
+ XMVECTOR a1 = d2 - g_cubicThird*d0 - g_cubicSixth*d3; \
+ XMVECTOR a2 = g_cubicHalf*d0 + g_cubicHalf*d2; \
+ XMVECTOR a3 = g_cubicSixth*d3 - g_cubicSixth*d0 - g_cubicHalf*d2; \
+ XMVECTOR vdx = XMVectorReplicate( dx ); \
+ XMVECTOR vdx2 = vdx * vdx; \
+ XMVECTOR vdx3 = vdx2 * vdx; \
+ res = a0 + a1*vdx + a2*vdx2 + a3*vdx3; \
+}
+
+
+//-------------------------------------------------------------------------------------
+// Triangle filtering helpers
+//-------------------------------------------------------------------------------------
+
+namespace TriangleFilter
+{
+ struct FilterTo
+ {
+ size_t u;
+ float weight;
+ };
+
+ struct FilterFrom
+ {
+ size_t count;
+ size_t sizeInBytes;
+ FilterTo to[1]; // variable-sized array
+ };
+
+ struct Filter
+ {
+ size_t sizeInBytes;
+ size_t totalSize;
+ FilterFrom from[1]; // variable-sized array
+ };
+
+ struct TriangleRow
+ {
+ size_t remaining;
+ TriangleRow* next;
+ ScopedAlignedArrayXMVECTOR scanline;
+
+ TriangleRow() : remaining(0), next(nullptr) {}
+ };
+
+ static const size_t TF_FILTER_SIZE = sizeof(Filter) - sizeof(FilterFrom);
+ static const size_t TF_FROM_SIZE = sizeof(FilterFrom) - sizeof(FilterTo);
+ static const size_t TF_TO_SIZE = sizeof(FilterTo);
+
+ static const float TF_EPSILON = 0.00001f;
+
+ inline HRESULT _Create( _In_ size_t source, _In_ size_t dest, _In_ bool wrap, _Inout_ std::unique_ptr<Filter>& tf )
+ {
+ assert( source > 0 );
+ assert( dest > 0 );
+
+ float scale = float(dest) / float(source);
+ float scaleInv = 0.5f / scale;
+
+ // Determine storage required for filter and allocate memory if needed
+ size_t totalSize = TF_FILTER_SIZE + TF_FROM_SIZE + TF_TO_SIZE;
+ float repeat = (wrap) ? 1.f : 0.f;
+
+ for( size_t u = 0; u < source; ++u )
+ {
+ float src = float(u) - 0.5f;
+ float destMin = src * scale;
+ float destMax = destMin + scale;
+
+ totalSize += TF_FROM_SIZE + TF_TO_SIZE + size_t( destMax - destMin + repeat + 1.f ) * TF_TO_SIZE * 2;
+ }
+
+ uint8_t* pFilter = nullptr;
+
+ if ( tf )
+ {
+ // See if existing filter memory block is large enough to reuse
+ if ( tf->totalSize >= totalSize )
+ {
+ pFilter = reinterpret_cast<uint8_t*>( tf.get() );
+ }
+ else
+ {
+ // Need to reallocate filter memory block
+ tf.reset( nullptr );
+ }
+ }
+
+ if ( !tf )
+ {
+ // Allocate filter memory block
+ pFilter = new (std::nothrow) uint8_t[ totalSize ];
+ if ( !pFilter )
+ return E_OUTOFMEMORY;
+
+ tf.reset( reinterpret_cast<Filter*>( pFilter ) );
+ tf->totalSize = totalSize;
+ }
+
+ assert( pFilter != 0 );
+
+ // Filter setup
+ size_t sizeInBytes = TF_FILTER_SIZE;
+ size_t accumU = 0;
+ float accumWeight = 0.f;
+
+ for( size_t u = 0; u < source; ++u )
+ {
+ // Setup from entry
+ size_t sizeFrom = sizeInBytes;
+ auto pFrom = reinterpret_cast<FilterFrom*>( pFilter + sizeInBytes );
+ sizeInBytes += TF_FROM_SIZE;
+
+ if ( sizeInBytes > totalSize )
+ return E_FAIL;
+
+ size_t toCount = 0;
+
+ // Perform two passes to capture the influences from both sides
+ for( size_t j = 0; j < 2; ++j )
+ {
+ float src = float( u + j ) - 0.5f;
+
+ float destMin = src * scale;
+ float destMax = destMin + scale;
+
+ if ( !wrap )
+ {
+ // Clamp
+ if ( destMin < 0.f )
+ destMin = 0.f;
+ if ( destMax > float(dest) )
+ destMax = float(dest);
+ }
+
+ for( auto k = static_cast<ptrdiff_t>( floorf( destMin ) ); float(k) < destMax; ++k )
+ {
+ float d0 = float(k);
+ float d1 = d0 + 1.f;
+
+ size_t u0;
+ if ( k < 0 )
+ {
+ // Handle wrap
+ u0 = size_t( k + ptrdiff_t(dest) );
+ }
+ else if ( k >= ptrdiff_t(dest) )
+ {
+ // Handle wrap
+ u0 = size_t( k - ptrdiff_t(dest) );
+ }
+ else
+ {
+ u0 = size_t( k );
+ }
+
+ // Save previous accumulated weight (if any)
+ if ( u0 != accumU )
+ {
+ if ( accumWeight > TF_EPSILON )
+ {
+ auto pTo = reinterpret_cast<FilterTo*>( pFilter + sizeInBytes );
+ sizeInBytes += TF_TO_SIZE;
+ ++toCount;
+
+ if ( sizeInBytes > totalSize )
+ return E_FAIL;
+
+ pTo->u = accumU;
+ pTo->weight = accumWeight;
+ }
+
+ accumWeight = 0.f;
+ accumU = u0;
+ }
+
+ // Clip destination
+ if ( d0 < destMin )
+ d0 = destMin;
+ if ( d1 > destMax )
+ d1 = destMax;
+
+ // Calculate average weight over destination pixel
+
+ float weight;
+ if ( !wrap && src < 0.f )
+ weight = 1.f;
+ else if ( !wrap && ( ( src + 1.f ) >= float(source) ) )
+ weight = 0.f;
+ else
+ weight = (d0 + d1) * scaleInv - src;
+
+ accumWeight += (d1 - d0) * ( j ? (1.f - weight) : weight );
+ }
+ }
+
+ // Store accumulated weight
+ if ( accumWeight > TF_EPSILON )
+ {
+ auto pTo = reinterpret_cast<FilterTo*>( pFilter + sizeInBytes );
+ sizeInBytes += TF_TO_SIZE;
+ ++toCount;
+
+ if ( sizeInBytes > totalSize )
+ return E_FAIL;
+
+ pTo->u = accumU;
+ pTo->weight = accumWeight;
+ }
+
+ accumWeight = 0.f;
+
+ // Finalize from entry
+ pFrom->count = toCount;
+ pFrom->sizeInBytes = sizeInBytes - sizeFrom;
+ }
+
+ tf->sizeInBytes = sizeInBytes;
+
+ return S_OK;
+ }
+
+}; // namespace
+
+}; // namespace \ No newline at end of file
diff --git a/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/scoped.h b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/scoped.h
new file mode 100644
index 0000000..d6329b1
--- /dev/null
+++ b/NvCloth/samples/external/DirectXTex/10.5.2016.2/include/scoped.h
@@ -0,0 +1,32 @@
+//-------------------------------------------------------------------------------------
+// scoped.h
+//
+// Utility header with helper classes for exception-safe handling of resources
+//
+// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
+// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
+// PARTICULAR PURPOSE.
+//
+// Copyright (c) Microsoft Corporation. All rights reserved.
+//-------------------------------------------------------------------------------------
+
+#pragma once
+
+#include <assert.h>
+#include <memory>
+#include <malloc.h>
+
+//---------------------------------------------------------------------------------
+struct aligned_deleter { void operator()(void* p) { _aligned_free(p); } };
+
+typedef std::unique_ptr<float[], aligned_deleter> ScopedAlignedArrayFloat;
+
+typedef std::unique_ptr<DirectX::XMVECTOR[], aligned_deleter> ScopedAlignedArrayXMVECTOR;
+
+//---------------------------------------------------------------------------------
+struct handle_closer { void operator()(HANDLE h) { assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h); } };
+
+typedef public std::unique_ptr<void, handle_closer> ScopedHandle;
+
+inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; }
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaContextManager.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaContextManager.h
new file mode 100644
index 0000000..aca1112
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaContextManager.h
@@ -0,0 +1,425 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+
+
+#ifndef PXCUDACONTEXTMANAGER_PXCUDACONTEXTMANAGER_H
+#define PXCUDACONTEXTMANAGER_PXCUDACONTEXTMANAGER_H
+
+#include "foundation/PxPreprocessor.h"
+
+#if PX_SUPPORT_GPU_PHYSX
+
+#include "foundation/PxSimpleTypes.h"
+#include "foundation/PxErrorCallback.h"
+#include "foundation/PxFlags.h"
+#include "task/PxTaskDefine.h"
+#include "cudamanager/PxCudaMemoryManager.h"
+
+/* Forward decl to avoid inclusion of cuda.h */
+typedef struct CUctx_st *CUcontext;
+typedef struct CUgraphicsResource_st *CUgraphicsResource;
+typedef int CUdevice;
+
+namespace physx
+{
+
+class PxGpuDispatcher;
+
+
+/** \brief Possible graphic/CUDA interoperability modes for context */
+struct PxCudaInteropMode
+{
+ /**
+ * \brief Possible graphic/CUDA interoperability modes for context
+ */
+ enum Enum
+ {
+ NO_INTEROP = 0,
+ D3D10_INTEROP,
+ D3D11_INTEROP,
+ OGL_INTEROP,
+
+ COUNT
+ };
+};
+
+struct PxCudaInteropRegisterFlag
+{
+ enum Enum
+ {
+ eNONE = 0x00,
+ eREAD_ONLY = 0x01,
+ eWRITE_DISCARD = 0x02,
+ eSURFACE_LDST = 0x04,
+ eTEXTURE_GATHER = 0x08
+ };
+};
+
+/**
+\brief collection of set bits defined in NxCudaInteropRegisterFlag.
+
+@see NxCudaInteropRegisterFlag
+*/
+typedef PxFlags<PxCudaInteropRegisterFlag::Enum, uint32_t> PxCudaInteropRegisterFlags;
+PX_FLAGS_OPERATORS(PxCudaInteropRegisterFlag::Enum, uint32_t)
+
+//! \brief Descriptor used to create a PxCudaContextManager
+class PxCudaContextManagerDesc
+{
+public:
+ /**
+ * \brief The CUDA context to manage
+ *
+ * If left NULL, the PxCudaContextManager will create a new context. If
+ * graphicsDevice is also not NULL, this new CUDA context will be bound to
+ * that graphics device, enabling the use of CUDA/Graphics interop features.
+ *
+ * If ctx is not NULL, the specified context must be applied to the thread
+ * that is allocating the PxCudaContextManager at creation time (aka, it
+ * cannot be popped). The PxCudaContextManager will take ownership of the
+ * context until the manager is released. All access to the context must be
+ * gated by lock acquisition.
+ *
+ * If the user provides a context for the PxCudaContextManager, the context
+ * _must_ have either been created on the GPU ordinal returned by
+ * PxGetSuggestedCudaDeviceOrdinal() or on your graphics device.
+ *
+ * It is perfectly acceptable to allocate device or host pinned memory from
+ * the context outside the scope of the PxCudaMemoryManager, so long as you
+ * manage its eventual cleanup.
+ */
+ CUcontext *ctx;
+
+ /**
+ * \brief D3D device pointer or OpenGl context handle
+ *
+ * Only applicable when ctx is NULL, thus forcing a new context to be
+ * created. In that case, the created context will be bound to this
+ * graphics device.
+ */
+ void *graphicsDevice;
+
+#if PX_SUPPORT_GPU_PHYSX
+ /**
+ * \brief Application-specific GUID
+ *
+ * If your application employs PhysX modules that use CUDA you need to use a GUID
+ * so that patches for new architectures can be released for your game.You can obtain a GUID for your
+ * application from Nvidia.
+ */
+ const char* appGUID;
+#endif
+ /**
+ * \brief The CUDA/Graphics interop mode of this context
+ *
+ * If ctx is NULL, this value describes the nature of the graphicsDevice
+ * pointer provided by the user. Else it describes the nature of the
+ * context provided by the user.
+ */
+ PxCudaInteropMode::Enum interopMode;
+
+
+ /**
+ * \brief Size of persistent memory
+ *
+ * This memory is allocated up front and stays allocated until the
+ * PxCudaContextManager is released. Size is in bytes, has to be power of two
+ * and bigger than the page size. Set to 0 to only use dynamic pages.
+ *
+ * Note: On Vista O/S and above, there is a per-memory allocation overhead
+ * to every CUDA work submission, so we recommend that you carefully tune
+ * this initial base memory size to closely approximate the amount of
+ * memory your application will consume.
+
+ Note: This is currently not used by PxSceneFlag::eENABLE_GPU_DYNAMICS. Memory allocation properties are configured
+ for GPU rigid bodies using PxSceneDesc::gpuDynamicsConfig.
+ */
+ uint32_t memoryBaseSize[PxCudaBufferMemorySpace::COUNT];
+
+ /**
+ * \brief Size of memory pages
+ *
+ * The memory manager will dynamically grow and shrink in blocks multiple of
+ * this page size. Size has to be power of two and bigger than 0.
+
+ Note: This is currently not used by PxSceneFlag::eENABLE_GPU_DYNAMICS. Memory allocation properties are configured
+ for GPU rigid bodies using PxSceneDesc::gpuDynamicsConfig.
+ */
+ uint32_t memoryPageSize[PxCudaBufferMemorySpace::COUNT];
+
+ /**
+ * \brief Maximum size of memory that the memory manager will allocate
+
+ Note: This is currently not used by PxSceneFlag::eENABLE_GPU_DYNAMICS. Memory allocation properties are configured
+ for GPU rigid bodies using PxSceneDesc::gpuDynamicsConfig.
+ */
+ uint32_t maxMemorySize[PxCudaBufferMemorySpace::COUNT];
+
+ PX_INLINE PxCudaContextManagerDesc()
+ {
+ ctx = NULL;
+ interopMode = PxCudaInteropMode::NO_INTEROP;
+ graphicsDevice = 0;
+#if PX_SUPPORT_GPU_PHYSX
+ appGUID = NULL;
+#endif
+ for(uint32_t i = 0; i < PxCudaBufferMemorySpace::COUNT; i++)
+ {
+ memoryBaseSize[i] = 0;
+ memoryPageSize[i] = 2 * 1024*1024;
+ maxMemorySize[i] = UINT32_MAX;
+ }
+ }
+};
+
+
+/**
+ * \brief Manages memory, thread locks, and task scheduling for a CUDA context
+ *
+ * A PxCudaContextManager manages access to a single CUDA context, allowing it to
+ * be shared between multiple scenes. Memory allocations are dynamic: starting
+ * with an initial heap size and growing on demand by a configurable page size.
+ * The context must be acquired from the manager before using any CUDA APIs.
+ *
+ * The PxCudaContextManager is based on the CUDA driver API and explictly does not
+ * support the CUDA runtime API (aka, CUDART).
+ *
+ * To enable CUDA use by an APEX scene, a PxCudaContextManager must be created
+ * (supplying your own CUDA context, or allowing a new context to be allocated
+ * for you), the PxGpuDispatcher for that context is retrieved via the
+ * getGpuDispatcher() method, and this is assigned to the TaskManager that is
+ * given to the scene via its NxApexSceneDesc.
+ */
+class PxCudaContextManager
+{
+public:
+ /**
+ * \brief Acquire the CUDA context for the current thread
+ *
+ * Acquisitions are allowed to be recursive within a single thread.
+ * You can acquire the context multiple times so long as you release
+ * it the same count.
+ *
+ * The context must be acquired before using most CUDA functions.
+ *
+ * It is not necessary to acquire the CUDA context inside GpuTask
+ * launch functions, because the PxGpuDispatcher will have already
+ * acquired the context for its worker thread. However it is not
+ * harmfull to (re)acquire the context in code that is shared between
+ * GpuTasks and non-task functions.
+ */
+ virtual void acquireContext() = 0;
+
+ /**
+ * \brief Release the CUDA context from the current thread
+ *
+ * The CUDA context should be released as soon as practically
+ * possible, to allow other CPU threads (including the
+ * PxGpuDispatcher) to work efficiently.
+ */
+ virtual void releaseContext() = 0;
+
+ /**
+ * \brief Return the CUcontext
+ */
+ virtual CUcontext getContext() = 0;
+
+ /**
+ * \brief Return the PxCudaMemoryManager instance associated with this
+ * CUDA context
+ * Note: This is currently not used by PxSceneFlag::eENABLE_GPU_DYNAMICS. Memory allocation properties are configured
+ * for GPU rigid bodies using PxSceneDesc::gpuDynamicsConfig.
+ */
+ virtual PxCudaMemoryManager *getMemoryManager() = 0;
+
+ /**
+ * \brief Return the PxGpuDispatcher instance associated with this
+ * CUDA context
+ */
+ virtual class physx::PxGpuDispatcher *getGpuDispatcher() = 0;
+
+ /**
+ * \brief Context manager has a valid CUDA context
+ *
+ * This method should be called after creating a PxCudaContextManager,
+ * especially if the manager was responsible for allocating its own
+ * CUDA context (desc.ctx == NULL). If it returns false, there is
+ * no point in assigning this manager's PxGpuDispatcher to a
+ * TaskManager as it will be unable to execute GpuTasks.
+ */
+ virtual bool contextIsValid() const = 0;
+
+ /* Query CUDA context and device properties, without acquiring context */
+
+ virtual bool supportsArchSM10() const = 0; //!< G80
+ virtual bool supportsArchSM11() const = 0; //!< G92
+ virtual bool supportsArchSM12() const = 0; //!< GT200
+ virtual bool supportsArchSM13() const = 0; //!< GT260
+ virtual bool supportsArchSM20() const = 0; //!< GF100
+ virtual bool supportsArchSM30() const = 0; //!< GK100
+ virtual bool supportsArchSM35() const = 0; //!< GK110
+ virtual bool supportsArchSM50() const = 0; //!< GM100
+ virtual bool supportsArchSM52() const = 0; //!< GM200
+ virtual bool supportsArchSM60() const = 0; //!< GP100
+ virtual bool isIntegrated() const = 0; //!< true if GPU is an integrated (MCP) part
+ virtual bool canMapHostMemory() const = 0; //!< true if GPU map host memory to GPU (0-copy)
+ virtual int getDriverVersion() const = 0; //!< returns cached value of cuGetDriverVersion()
+ virtual size_t getDeviceTotalMemBytes() const = 0; //!< returns cached value of device memory size
+ virtual int getMultiprocessorCount() const = 0; //!< returns cache value of SM unit count
+ virtual unsigned int getClockRate() const = 0; //!< returns cached value of SM clock frequency
+ virtual int getSharedMemPerBlock() const = 0; //!< returns total amount of shared memory available per block in bytes
+ virtual int getSharedMemPerMultiprocessor() const = 0; //!< returns total amount of shared memory available per multiprocessor in bytes
+ virtual unsigned int getMaxThreadsPerBlock() const = 0; //!< returns the maximum number of threads per block
+ virtual const char *getDeviceName() const = 0; //!< returns device name retrieved from driver
+ virtual CUdevice getDevice() const = 0; //!< returns device handle retrieved from driver
+ virtual PxCudaInteropMode::Enum getInteropMode() const = 0; //!< interop mode the context was created with
+
+ virtual void setUsingConcurrentStreams(bool) = 0; //!< turn on/off using concurrent streams for GPU work
+ virtual bool getUsingConcurrentStreams() const = 0; //!< true if GPU work can run in concurrent streams
+ /* End query methods that don't require context to be acquired */
+
+ /**
+ * \brief Register a rendering resource with CUDA
+ *
+ * This function is called to register render resources (allocated
+ * from OpenGL) with CUDA so that the memory may be shared
+ * between the two systems. This is only required for render
+ * resources that are designed for interop use. In APEX, each
+ * render resource descriptor that could support interop has a
+ * 'registerInCUDA' boolean variable.
+ *
+ * The function must be called again any time your graphics device
+ * is reset, to re-register the resource.
+ *
+ * Returns true if the registration succeeded. A registered
+ * resource must be unregistered before it can be released.
+ *
+ * \param resource [OUT] the handle to the resource that can be used with CUDA
+ * \param buffer [IN] GLuint buffer index to be mapped to cuda
+ * \param flags [IN] cuda interop registration flags
+ */
+ virtual bool registerResourceInCudaGL(CUgraphicsResource &resource, uint32_t buffer, PxCudaInteropRegisterFlags flags = PxCudaInteropRegisterFlags()) = 0;
+
+ /**
+ * \brief Register a rendering resource with CUDA
+ *
+ * This function is called to register render resources (allocated
+ * from Direct3D) with CUDA so that the memory may be shared
+ * between the two systems. This is only required for render
+ * resources that are designed for interop use. In APEX, each
+ * render resource descriptor that could support interop has a
+ * 'registerInCUDA' boolean variable.
+ *
+ * The function must be called again any time your graphics device
+ * is reset, to re-register the resource.
+ *
+ * Returns true if the registration succeeded. A registered
+ * resource must be unregistered before it can be released.
+ *
+ * \param resource [OUT] the handle to the resource that can be used with CUDA
+ * \param resourcePointer [IN] A pointer to either IDirect3DResource9, or ID3D10Device, or ID3D11Resource to be registered.
+ * \param flags [IN] cuda interop registration flags
+ */
+ virtual bool registerResourceInCudaD3D(CUgraphicsResource &resource, void *resourcePointer, PxCudaInteropRegisterFlags flags = PxCudaInteropRegisterFlags()) = 0;
+
+ /**
+ * \brief Unregister a rendering resource with CUDA
+ *
+ * If a render resource was successfully registered with CUDA using
+ * the registerResourceInCuda***() methods, this function must be called
+ * to unregister the resource before the it can be released.
+ */
+ virtual bool unregisterResourceInCuda(CUgraphicsResource resource) = 0;
+
+ /**
+ * \brief Determine if the user has configured a dedicated PhysX GPU in the NV Control Panel
+ * \note If using CUDA Interop, this will always return false
+ * \returns 1 if there is a dedicated GPU
+ * 0 if there is NOT a dedicated GPU
+ * -1 if the routine is not implemented
+ */
+ virtual int usingDedicatedGPU() const = 0;
+
+ /**
+ * \brief Release the PxCudaContextManager
+ *
+ * When the manager instance is released, it also releases its
+ * PxGpuDispatcher instance and PxCudaMemoryManager. Before the memory
+ * manager is released, it frees all allocated memory pages. If the
+ * PxCudaContextManager created the CUDA context it was responsible
+ * for, it also frees that context.
+ *
+ * Do not release the PxCudaContextManager if there are any scenes
+ * using its PxGpuDispatcher. Those scenes must be released first
+ * since there is no safe way to remove a PxGpuDispatcher from a
+ * TaskManager once the TaskManager has been given to a scene.
+ *
+ */
+ virtual void release() = 0;
+
+protected:
+
+ /**
+ * \brief protected destructor, use release() method
+ */
+ virtual ~PxCudaContextManager() {}
+};
+
+/**
+ * \brief Convenience class for holding CUDA lock within a scope
+ */
+class PxScopedCudaLock
+{
+public:
+ /**
+ * \brief ScopedCudaLock constructor
+ */
+ PxScopedCudaLock(PxCudaContextManager& ctx) : mCtx(&ctx)
+ {
+ mCtx->acquireContext();
+ }
+
+ /**
+ * \brief ScopedCudaLock destructor
+ */
+ ~PxScopedCudaLock()
+ {
+ mCtx->releaseContext();
+ }
+
+protected:
+
+ /**
+ * \brief CUDA context manager pointer (initialized in the constructor)
+ */
+ PxCudaContextManager* mCtx;
+};
+
+} // end physx namespace
+
+#endif // PX_SUPPORT_GPU_PHYSX
+#endif // PXCUDACONTEXTMANAGER_PXCUDACONTEXTMANAGER_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaMemoryManager.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaMemoryManager.h
new file mode 100644
index 0000000..c89b20d
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxCudaMemoryManager.h
@@ -0,0 +1,281 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+
+#ifndef PXCUDACONTEXTMANAGER_PXCUDAMEMORYMANAGER_H
+#define PXCUDACONTEXTMANAGER_PXCUDAMEMORYMANAGER_H
+
+#include "foundation/PxPreprocessor.h"
+
+#if PX_SUPPORT_GPU_PHYSX
+
+#include "task/PxTaskDefine.h"
+
+// some macros to keep the source code more readable
+#define PX_ALLOC_INFO(name, ID) __FILE__, __LINE__, name, physx::PxAllocId::ID
+#define PX_ALLOC_INFO_PARAMS_DECL(p0, p1, p2, p3) const char* file = p0, int line = p1, const char* allocName = p2, physx::PxAllocId::Enum allocId = physx::PxAllocId::p3
+#define PX_ALLOC_INFO_PARAMS_DEF() const char* file, int line, const char* allocName, physx::PxAllocId::Enum allocId
+#define PX_ALLOC_INFO_PARAMS_INPUT() file, line, allocName, allocId
+#define PX_ALLOC_INFO_PARAMS_INPUT_INFO(info) info.getFileName(), info.getLine(), info.getAllocName(), info.getAllocId()
+
+#ifndef NULL // don't want to include <string.h>
+#define NULL 0
+#endif
+
+namespace physx
+{
+
+PX_PUSH_PACK_DEFAULT
+
+/** \brief ID of the Feature which owns/allocated memory from the heap
+ *
+ * Maximum of 64k IDs allowed.
+ */
+struct PxAllocId
+{
+ /**
+ * \brief ID of the Feature which owns/allocated memory from the heap
+ */
+ enum Enum
+ {
+ UNASSIGNED, //!< default
+ APEX, //!< APEX stuff not further classified
+ PARTICLES, //!< all particle related
+ GPU_UTIL, //!< e.g. RadixSort (used in SPH and deformable self collision)
+ CLOTH, //!< all cloth related
+ NUM_IDS //!< number of IDs, be aware that ApexHeapStats contains PxAllocIdStats[NUM_IDS]
+ };
+};
+
+/// \brief memory type managed by a heap
+struct PxCudaBufferMemorySpace
+{
+ /**
+ * \brief memory type managed by a heap
+ */
+ enum Enum
+ {
+ T_GPU,
+ T_PINNED_HOST,
+ T_WRITE_COMBINED,
+ T_HOST,
+ COUNT
+ };
+};
+
+/// \brief class to track allocation statistics, see PxgMirrored
+class PxAllocInfo
+{
+public:
+ /**
+ * \brief AllocInfo default constructor
+ */
+ PxAllocInfo() {}
+
+ /**
+ * \brief AllocInfo constructor that initializes all of the members
+ */
+ PxAllocInfo(const char* file, int line, const char* allocName, PxAllocId::Enum allocId)
+ : mFileName(file)
+ , mLine(line)
+ , mAllocName(allocName)
+ , mAllocId(allocId)
+ {}
+
+ /// \brief get the allocation file name
+ inline const char* getFileName() const
+ {
+ return mFileName;
+ }
+
+ /// \brief get the allocation line
+ inline int getLine() const
+ {
+ return mLine;
+ }
+
+ /// \brief get the allocation name
+ inline const char* getAllocName() const
+ {
+ return mAllocName;
+ }
+
+ /// \brief get the allocation ID
+ inline PxAllocId::Enum getAllocId() const
+ {
+ return mAllocId;
+ }
+
+private:
+ const char* mFileName;
+ int mLine;
+ const char* mAllocName;
+ PxAllocId::Enum mAllocId;
+};
+
+/// \brief statistics collected per AllocationId by HeapManager.
+struct PxAllocIdStats
+{
+ size_t size; //!< currently allocated memory by this ID
+ size_t maxSize; //!< max allocated memory by this ID
+ size_t elements; //!< number of current allocations by this ID
+ size_t maxElements; //!< max number of allocations by this ID
+};
+
+class PxCudaMemoryManager;
+typedef size_t PxCudaBufferPtr;
+
+/// \brief Hint flag to tell how the buffer will be used
+struct PxCudaBufferFlags
+{
+/// \brief Enumerations for the hint flag to tell how the buffer will be used
+ enum Enum
+ {
+ F_READ = (1 << 0),
+ F_WRITE = (1 << 1),
+ F_READ_WRITE = F_READ | F_WRITE
+ };
+};
+
+
+/// \brief Memory statistics struct returned by CudaMemMgr::getStats()
+struct PxCudaMemoryManagerStats
+{
+
+ size_t heapSize; //!< Size of all pages allocated for this memory type (allocated + free).
+ size_t totalAllocated; //!< Size occupied by the current allocations.
+ size_t maxAllocated; //!< High water mark of allocations since the SDK was created.
+ PxAllocIdStats allocIdStats[PxAllocId::NUM_IDS]; //!< Stats for each allocation ID, see PxAllocIdStats
+};
+
+
+/// \brief Buffer type: made of hint flags and the memory space (Device Memory, Pinned Host Memory, ...)
+struct PxCudaBufferType
+{
+ /// \brief PxCudaBufferType copy constructor
+ PX_INLINE PxCudaBufferType(const PxCudaBufferType& t)
+ : memorySpace(t.memorySpace)
+ , flags(t.flags)
+ {}
+
+ /// \brief PxCudaBufferType constructor to explicitely assign members
+ PX_INLINE PxCudaBufferType(PxCudaBufferMemorySpace::Enum _memSpace, PxCudaBufferFlags::Enum _flags)
+ : memorySpace(_memSpace)
+ , flags(_flags)
+ {}
+
+ PxCudaBufferMemorySpace::Enum memorySpace; //!< specifies which memory space for the buffer
+ PxCudaBufferFlags::Enum flags; //!< specifies the usage flags for the buffer
+};
+
+
+/// \brief Buffer which keeps informations about allocated piece of memory.
+class PxCudaBuffer
+{
+public:
+ /// Retrieves the manager over which the buffer was allocated.
+ virtual PxCudaMemoryManager* getCudaMemoryManager() const = 0;
+
+ /// Releases the buffer and the memory it used, returns true if successful.
+ virtual bool free() = 0;
+
+ /// Realloc memory. Use to shrink or resize the allocated chunk of memory of this buffer.
+ /// Returns true if successful. Fails if the operation would change the address and need a memcopy.
+ /// In that case the user has to allocate, copy and free the memory with separate steps.
+ /// Realloc to size 0 always returns false and doesn't change the state.
+ virtual bool realloc(size_t size, PX_ALLOC_INFO_PARAMS_DECL(NULL, 0, NULL, UNASSIGNED)) = 0;
+
+ /// Returns the type of the allocated memory.
+ virtual const PxCudaBufferType& getType() const = 0;
+
+ /// Returns the pointer to the allocated memory.
+ virtual PxCudaBufferPtr getPtr() const = 0;
+
+ /// Returns the size of the allocated memory.
+ virtual size_t getSize() const = 0;
+
+protected:
+ /// \brief protected destructor
+ virtual ~PxCudaBuffer() {}
+};
+
+
+/// \brief Allocator class for different kinds of CUDA related memory.
+class PxCudaMemoryManager
+{
+public:
+ /// Allocate memory of given type and size. Returns a CudaBuffer if successful. Returns NULL if failed.
+ virtual PxCudaBuffer* alloc(const PxCudaBufferType& type, size_t size, PX_ALLOC_INFO_PARAMS_DECL(NULL, 0, NULL, UNASSIGNED)) = 0;
+
+ /// Basic heap allocator without PxCudaBuffer
+ virtual PxCudaBufferPtr alloc(PxCudaBufferMemorySpace::Enum memorySpace, size_t size, PX_ALLOC_INFO_PARAMS_DECL(NULL, 0, NULL, UNASSIGNED)) = 0;
+
+ /// Basic heap deallocator without PxCudaBuffer
+ virtual bool free(PxCudaBufferMemorySpace::Enum memorySpace, PxCudaBufferPtr addr) = 0;
+
+ /// Basic heap realloc without PxCudaBuffer
+ virtual bool realloc(PxCudaBufferMemorySpace::Enum memorySpace, PxCudaBufferPtr addr, size_t size, PX_ALLOC_INFO_PARAMS_DECL(NULL, 0, NULL, UNASSIGNED)) = 0;
+
+ /// Retrieve stats for the memory of given type. See PxCudaMemoryManagerStats.
+ virtual void getStats(const PxCudaBufferType& type, PxCudaMemoryManagerStats& outStats) = 0;
+
+ /// Ensure that a given amount of free memory is available. Triggers CUDA allocations in size of (2^n * pageSize) if necessary.
+ /// Returns false if page allocations failed.
+ virtual bool reserve(const PxCudaBufferType& type, size_t size) = 0;
+
+ /// Set the page size. The managed memory grows by blocks 2^n * pageSize. Page allocations trigger CUDA driver allocations,
+ /// so the page size should be reasonably big. Returns false if input size was invalid, i.e. not power of two.
+ /// Default is 2 MB.
+ virtual bool setPageSize(const PxCudaBufferType& type, size_t size) = 0;
+
+ /// Set the upper limit until which pages of a given memory type can be allocated.
+ /// Reducing the max when it is already hit does not shrink the memory until it is deallocated by releasing the buffers which own the memory.
+ virtual bool setMaxMemorySize(const PxCudaBufferType& type, size_t size) = 0;
+
+ /// Returns the base size. The base memory block stays persistently allocated over the SDKs life time.
+ virtual size_t getBaseSize(const PxCudaBufferType& type) = 0;
+
+ /// Returns the currently set page size. The memory grows and shrinks in blocks of size (2^n pageSize)
+ virtual size_t getPageSize(const PxCudaBufferType& type) = 0;
+
+ /// Returns the upper limit until which the manager is allowed to allocate additional pages from the CUDA driver.
+ virtual size_t getMaxMemorySize(const PxCudaBufferType& type) = 0;
+
+ /// Get device mapped pinned host mem ptr. Operation only valid for memory space PxCudaBufferMemorySpace::T_PINNED_HOST.
+ virtual PxCudaBufferPtr getMappedPinnedPtr(PxCudaBufferPtr hostPtr) = 0;
+
+protected:
+ /// \brief protected destructor
+ virtual ~PxCudaMemoryManager() {}
+};
+
+PX_POP_PACK
+
+
+} // end physx namespace
+
+#endif // PX_SUPPORT_GPU_PHYSX
+#endif // PXCUDACONTEXTMANAGER_PXCUDAMEMORYMANAGER_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDesc.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDesc.h
new file mode 100644
index 0000000..c6c240f
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDesc.h
@@ -0,0 +1,86 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+
+#ifndef PXCUDACONTEXTMANAGER_PXGPUCOPYDESC_H
+#define PXCUDACONTEXTMANAGER_PXGPUCOPYDESC_H
+
+#include "foundation/PxPreprocessor.h"
+
+#if PX_SUPPORT_GPU_PHYSX
+
+#include "task/PxTaskDefine.h"
+
+namespace physx
+{
+
+PX_PUSH_PACK_DEFAULT
+
+/**
+ * \brief Input descriptor for the GpuDispatcher's built-in copy kernel
+ *
+ * All host memory involved in copy transactions must be page-locked.
+ * If more than one descriptor is passed to the copy kernel in one launch,
+ * the descriptors themselves must be in page-locked memory.
+ */
+struct PxGpuCopyDesc
+{
+ /**
+ * \brief Input descriptor for the GpuDispatcher's built-in copy kernel
+ */
+ enum CopyType
+ {
+ HostToDevice,
+ DeviceToHost,
+ DeviceToDevice,
+ DeviceMemset32
+ };
+
+ size_t dest; //!< the destination
+ size_t source; //!< the source (32bit value when type == DeviceMemset)
+ size_t bytes; //!< the size in bytes
+ CopyType type; //!< the memory transaction type
+
+ /**
+ * \brief Copy is optimally performed as 64bit words, requires 64bit alignment. But it can
+ * gracefully degrade to 32bit copies if necessary
+ */
+ PX_INLINE bool isValid()
+ {
+ bool ok = true;
+ ok &= ((dest & 0x3) == 0);
+ ok &= ((type == DeviceMemset32) || (source & 0x3) == 0);
+ ok &= ((bytes & 0x3) == 0);
+ return ok;
+ }
+};
+
+PX_POP_PACK
+
+} // end physx namespace
+
+#endif // PX_SUPPORT_GPU_PHYSX
+#endif // PXCUDACONTEXTMANAGER_PXGPUCOPYDESC_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDescQueue.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDescQueue.h
new file mode 100644
index 0000000..4b6d58e
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/cudamanager/PxGpuCopyDescQueue.h
@@ -0,0 +1,149 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+
+#ifndef PXCUDACONTEXTMANAGER_PXGPUCOPYDESCQUEUE_H
+#define PXCUDACONTEXTMANAGER_PXGPUCOPYDESCQUEUE_H
+
+#include "foundation/PxPreprocessor.h"
+
+#if PX_SUPPORT_GPU_PHYSX
+
+#include "foundation/PxAssert.h"
+#include "task/PxTaskDefine.h"
+#include "task/PxGpuDispatcher.h"
+#include "cudamanager/PxGpuCopyDesc.h"
+#include "cudamanager/PxCudaContextManager.h"
+
+/* forward decl to avoid including <cuda.h> */
+typedef struct CUstream_st* CUstream;
+
+namespace physx
+{
+
+PX_PUSH_PACK_DEFAULT
+
+/// \brief Container class for queueing PxGpuCopyDesc instances in pinned (non-pageable) CPU memory
+class PxGpuCopyDescQueue
+{
+public:
+ /// \brief PxGpuCopyDescQueue constructor
+ PxGpuCopyDescQueue(PxGpuDispatcher& d)
+ : mDispatcher(d)
+ , mBuffer(0)
+ , mStream(0)
+ , mReserved(0)
+ , mOccupancy(0)
+ , mFlushed(0)
+ {
+ }
+
+ /// \brief PxGpuCopyDescQueue destructor
+ ~PxGpuCopyDescQueue()
+ {
+ if (mBuffer)
+ {
+ mDispatcher.getCudaContextManager()->getMemoryManager()->free(PxCudaBufferMemorySpace::T_PINNED_HOST, (size_t) mBuffer);
+ }
+ }
+
+ /// \brief Reset the enqueued copy descriptor list
+ ///
+ /// Must be called at least once before any copies are enqueued, and each time the launched
+ /// copies are known to have been completed. The recommended use case is to call this at the
+ /// start of each simulation step.
+ void reset(CUstream stream, uint32_t reserveSize)
+ {
+ if (reserveSize > mReserved)
+ {
+ if (mBuffer)
+ {
+ mDispatcher.getCudaContextManager()->getMemoryManager()->free(
+ PxCudaBufferMemorySpace::T_PINNED_HOST,
+ (size_t) mBuffer);
+ mReserved = 0;
+ }
+ mBuffer = (PxGpuCopyDesc*) mDispatcher.getCudaContextManager()->getMemoryManager()->alloc(
+ PxCudaBufferMemorySpace::T_PINNED_HOST,
+ reserveSize * sizeof(PxGpuCopyDesc),
+ PX_ALLOC_INFO("PxGpuCopyDescQueue", GPU_UTIL));
+ if (mBuffer)
+ {
+ mReserved = reserveSize;
+ }
+ }
+
+ mOccupancy = 0;
+ mFlushed = 0;
+ mStream = stream;
+ }
+
+ /// \brief Enqueue the specified copy descriptor, or launch immediately if no room is available
+ void enqueue(PxGpuCopyDesc& desc)
+ {
+ PX_ASSERT(desc.isValid());
+ if (desc.bytes == 0)
+ {
+ return;
+ }
+
+ if (mOccupancy < mReserved)
+ {
+ mBuffer[ mOccupancy++ ] = desc;
+ }
+ else
+ {
+ mDispatcher.launchCopyKernel(&desc, 1, mStream);
+ }
+ }
+
+ /// \brief Launch all copies queued since the last flush or reset
+ void flushEnqueued()
+ {
+ if (mOccupancy > mFlushed)
+ {
+ mDispatcher.launchCopyKernel(mBuffer + mFlushed, mOccupancy - mFlushed, mStream);
+ mFlushed = mOccupancy;
+ }
+ }
+
+private:
+ PxGpuDispatcher& mDispatcher;
+ PxGpuCopyDesc* mBuffer;
+ CUstream mStream;
+ uint32_t mReserved;
+ uint32_t mOccupancy;
+ uint32_t mFlushed;
+
+ void operator=(const PxGpuCopyDescQueue&); // prevent a warning...
+};
+
+PX_POP_PACK
+
+} // end physx namespace
+
+#endif // PX_SUPPORT_GPU_PHYSX
+#endif // PXCUDACONTEXTMANAGER_PXGPUCOPYDESCQUEUE_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/Px.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/Px.h
new file mode 100644
index 0000000..1b6b3f6
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/Px.h
@@ -0,0 +1,92 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PX_H
+#define PXFOUNDATION_PX_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxSimpleTypes.h"
+
+/** files to always include */
+#include <string.h>
+#include <stdlib.h>
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+typedef uint32_t PxU32;
+
+class PxAllocatorCallback;
+class PxErrorCallback;
+struct PxErrorCode;
+class PxAssertHandler;
+
+class PxInputStream;
+class PxInputData;
+class PxOutputStream;
+
+class PxVec2;
+class PxVec3;
+class PxVec4;
+class PxMat33;
+class PxMat44;
+class PxPlane;
+class PxQuat;
+class PxTransform;
+class PxBounds3;
+
+/** enum for empty constructor tag*/
+enum PxEMPTY
+{
+ PxEmpty
+};
+
+/** enum for zero constructor tag for vectors and matrices */
+enum PxZERO
+{
+ PxZero
+};
+
+/** enum for identity constructor flag for quaternions, transforms, and matrices */
+enum PxIDENTITY
+{
+ PxIdentity
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PX_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAllocatorCallback.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAllocatorCallback.h
new file mode 100644
index 0000000..7545b60
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAllocatorCallback.h
@@ -0,0 +1,95 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXALLOCATORCALLBACK_H
+#define PXFOUNDATION_PXALLOCATORCALLBACK_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/Px.h"
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Abstract base class for an application defined memory allocator that can be used by the Nv library.
+
+\note The SDK state should not be modified from within any allocation/free function.
+
+<b>Threading:</b> All methods of this class should be thread safe as it can be called from the user thread
+or the physics processing thread(s).
+*/
+
+class PxAllocatorCallback
+{
+ public:
+ /**
+ \brief destructor
+ */
+ virtual ~PxAllocatorCallback()
+ {
+ }
+
+ /**
+ \brief Allocates size bytes of memory, which must be 16-byte aligned.
+
+ This method should never return NULL. If you run out of memory, then
+ you should terminate the app or take some other appropriate action.
+
+ <b>Threading:</b> This function should be thread safe as it can be called in the context of the user thread
+ and physics processing thread(s).
+
+ \param size Number of bytes to allocate.
+ \param typeName Name of the datatype that is being allocated
+ \param filename The source file which allocated the memory
+ \param line The source line which allocated the memory
+ \return The allocated block of memory.
+ */
+ virtual void* allocate(size_t size, const char* typeName, const char* filename, int line) = 0;
+
+ /**
+ \brief Frees memory previously allocated by allocate().
+
+ <b>Threading:</b> This function should be thread safe as it can be called in the context of the user thread
+ and physics processing thread(s).
+
+ \param ptr Memory to free.
+ */
+ virtual void deallocate(void* ptr) = 0;
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXALLOCATORCALLBACK_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAssert.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAssert.h
new file mode 100644
index 0000000..c422c27
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxAssert.h
@@ -0,0 +1,95 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXASSERT_H
+#define PXFOUNDATION_PXASSERT_H
+
+/** \addtogroup foundation
+@{ */
+
+#include "foundation/Px.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/* Base class to handle assert failures */
+class PxAssertHandler
+{
+ public:
+ virtual ~PxAssertHandler()
+ {
+ }
+ virtual void operator()(const char* exp, const char* file, int line, bool& ignore) = 0;
+};
+
+PX_FOUNDATION_API PxAssertHandler& PxGetAssertHandler();
+PX_FOUNDATION_API void PxSetAssertHandler(PxAssertHandler& handler);
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+#if !PX_ENABLE_ASSERTS
+#define PX_ASSERT(exp) ((void)0)
+#define PX_ALWAYS_ASSERT_MESSAGE(exp) ((void)0)
+#define PX_ASSERT_WITH_MESSAGE(condition, message) ((void)0)
+#else
+#if PX_VC
+#define PX_CODE_ANALYSIS_ASSUME(exp) \
+ __analysis_assume(!!(exp)) // This macro will be used to get rid of analysis warning messages if a PX_ASSERT is used
+// to "guard" illegal mem access, for example.
+#else
+#define PX_CODE_ANALYSIS_ASSUME(exp)
+#endif
+#define PX_ASSERT(exp) \
+ { \
+ static bool _ignore = false; \
+ ((void)((!!(exp)) || (!_ignore && (physx::PxGetAssertHandler()(#exp, __FILE__, __LINE__, _ignore), false)))); \
+ PX_CODE_ANALYSIS_ASSUME(exp); \
+ }
+#define PX_ALWAYS_ASSERT_MESSAGE(exp) \
+ { \
+ static bool _ignore = false; \
+ if(!_ignore) \
+ physx::PxGetAssertHandler()(exp, __FILE__, __LINE__, _ignore); \
+ }
+#define PX_ASSERT_WITH_MESSAGE(exp, message) \
+ { \
+ static bool _ignore = false; \
+ ((void)((!!(exp)) || (!_ignore && (physx::PxGetAssertHandler()(message, __FILE__, __LINE__, _ignore), false)))); \
+ PX_CODE_ANALYSIS_ASSUME(exp); \
+ }
+#endif
+
+#define PX_ALWAYS_ASSERT() PX_ASSERT(0)
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXASSERT_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBitAndData.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBitAndData.h
new file mode 100644
index 0000000..685c1a2
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBitAndData.h
@@ -0,0 +1,87 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXBITANDDATA_H
+#define PXFOUNDATION_PXBITANDDATA_H
+
+#include "foundation/Px.h"
+
+/** \addtogroup foundation
+ @{
+*/
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+template <typename storageType, storageType bitMask>
+class PxBitAndDataT
+{
+ public:
+ PX_FORCE_INLINE PxBitAndDataT(const PxEMPTY)
+ {
+ }
+ PX_FORCE_INLINE PxBitAndDataT() : mData(0)
+ {
+ }
+ PX_FORCE_INLINE PxBitAndDataT(storageType data, bool bit = false)
+ {
+ mData = bit ? storageType(data | bitMask) : data;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE operator storageType() const
+ {
+ return storageType(mData & ~bitMask);
+ }
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void setBit()
+ {
+ mData |= bitMask;
+ }
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void clearBit()
+ {
+ mData &= ~bitMask;
+ }
+ PX_CUDA_CALLABLE PX_FORCE_INLINE storageType isBitSet() const
+ {
+ return storageType(mData & bitMask);
+ }
+
+ protected:
+ storageType mData;
+};
+typedef PxBitAndDataT<unsigned char, 0x80> PxBitAndByte;
+typedef PxBitAndDataT<unsigned short, 0x8000> PxBitAndWord;
+typedef PxBitAndDataT<unsigned int, 0x80000000> PxBitAndDword;
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // PXFOUNDATION_PXBITANDDATA_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBounds3.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBounds3.h
new file mode 100644
index 0000000..38d7282
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxBounds3.h
@@ -0,0 +1,480 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXBOUNDS3_H
+#define PXFOUNDATION_PXBOUNDS3_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxTransform.h"
+#include "foundation/PxMat33.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+// maximum extents defined such that floating point exceptions are avoided for standard use cases
+#define PX_MAX_BOUNDS_EXTENTS (PX_MAX_REAL * 0.25f)
+
+/**
+\brief Class representing 3D range or axis aligned bounding box.
+
+Stored as minimum and maximum extent corners. Alternate representation
+would be center and dimensions.
+May be empty or nonempty. For nonempty bounds, minimum <= maximum has to hold for all axes.
+Empty bounds have to be represented as minimum = PX_MAX_BOUNDS_EXTENTS and maximum = -PX_MAX_BOUNDS_EXTENTS for all
+axes.
+All other representations are invalid and the behavior is undefined.
+*/
+class PxBounds3
+{
+ public:
+ /**
+ \brief Default constructor, not performing any initialization for performance reason.
+ \remark Use empty() function below to construct empty bounds.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3()
+ {
+ }
+
+ /**
+ \brief Construct from two bounding points
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3(const PxVec3& minimum, const PxVec3& maximum);
+
+ /**
+ \brief Return empty bounds.
+ */
+ static PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 empty();
+
+ /**
+ \brief returns the AABB containing v0 and v1.
+ \param v0 first point included in the AABB.
+ \param v1 second point included in the AABB.
+ */
+ static PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 boundsOfPoints(const PxVec3& v0, const PxVec3& v1);
+
+ /**
+ \brief returns the AABB from center and extents vectors.
+ \param center Center vector
+ \param extent Extents vector
+ */
+ static PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 centerExtents(const PxVec3& center, const PxVec3& extent);
+
+ /**
+ \brief Construct from center, extent, and (not necessarily orthogonal) basis
+ */
+ static PX_CUDA_CALLABLE PX_INLINE PxBounds3
+ basisExtent(const PxVec3& center, const PxMat33& basis, const PxVec3& extent);
+
+ /**
+ \brief Construct from pose and extent
+ */
+ static PX_CUDA_CALLABLE PX_INLINE PxBounds3 poseExtent(const PxTransform& pose, const PxVec3& extent);
+
+ /**
+ \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB).
+
+ This version is safe to call for empty bounds.
+
+ \param[in] matrix Transform to apply, can contain scaling as well
+ \param[in] bounds The bounds to transform.
+ */
+ static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformSafe(const PxMat33& matrix, const PxBounds3& bounds);
+
+ /**
+ \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB).
+
+ Calling this method for empty bounds leads to undefined behavior. Use #transformSafe() instead.
+
+ \param[in] matrix Transform to apply, can contain scaling as well
+ \param[in] bounds The bounds to transform.
+ */
+ static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformFast(const PxMat33& matrix, const PxBounds3& bounds);
+
+ /**
+ \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB).
+
+ This version is safe to call for empty bounds.
+
+ \param[in] transform Transform to apply, can contain scaling as well
+ \param[in] bounds The bounds to transform.
+ */
+ static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformSafe(const PxTransform& transform, const PxBounds3& bounds);
+
+ /**
+ \brief gets the transformed bounds of the passed AABB (resulting in a bigger AABB).
+
+ Calling this method for empty bounds leads to undefined behavior. Use #transformSafe() instead.
+
+ \param[in] transform Transform to apply, can contain scaling as well
+ \param[in] bounds The bounds to transform.
+ */
+ static PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformFast(const PxTransform& transform, const PxBounds3& bounds);
+
+ /**
+ \brief Sets empty to true
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void setEmpty();
+
+ /**
+ \brief Sets the bounds to maximum size [-PX_MAX_BOUNDS_EXTENTS, PX_MAX_BOUNDS_EXTENTS].
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void setMaximal();
+
+ /**
+ \brief expands the volume to include v
+ \param v Point to expand to.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void include(const PxVec3& v);
+
+ /**
+ \brief expands the volume to include b.
+ \param b Bounds to perform union with.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void include(const PxBounds3& b);
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isEmpty() const;
+
+ /**
+ \brief indicates whether the intersection of this and b is empty or not.
+ \param b Bounds to test for intersection.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool intersects(const PxBounds3& b) const;
+
+ /**
+ \brief computes the 1D-intersection between two AABBs, on a given axis.
+ \param a the other AABB
+ \param axis the axis (0, 1, 2)
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool intersects1D(const PxBounds3& a, uint32_t axis) const;
+
+ /**
+ \brief indicates if these bounds contain v.
+ \param v Point to test against bounds.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool contains(const PxVec3& v) const;
+
+ /**
+ \brief checks a box is inside another box.
+ \param box the other AABB
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isInside(const PxBounds3& box) const;
+
+ /**
+ \brief returns the center of this axis aligned box.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getCenter() const;
+
+ /**
+ \brief get component of the box's center along a given axis
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float getCenter(uint32_t axis) const;
+
+ /**
+ \brief get component of the box's extents along a given axis
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float getExtents(uint32_t axis) const;
+
+ /**
+ \brief returns the dimensions (width/height/depth) of this axis aligned box.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getDimensions() const;
+
+ /**
+ \brief returns the extents, which are half of the width/height/depth.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getExtents() const;
+
+ /**
+ \brief scales the AABB.
+
+ This version is safe to call for empty bounds.
+
+ \param scale Factor to scale AABB by.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void scaleSafe(float scale);
+
+ /**
+ \brief scales the AABB.
+
+ Calling this method for empty bounds leads to undefined behavior. Use #scaleSafe() instead.
+
+ \param scale Factor to scale AABB by.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void scaleFast(float scale);
+
+ /**
+ fattens the AABB in all 3 dimensions by the given distance.
+
+ This version is safe to call for empty bounds.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void fattenSafe(float distance);
+
+ /**
+ fattens the AABB in all 3 dimensions by the given distance.
+
+ Calling this method for empty bounds leads to undefined behavior. Use #fattenSafe() instead.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void fattenFast(float distance);
+
+ /**
+ checks that the AABB values are not NaN
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const;
+
+ /**
+ checks that the AABB values describe a valid configuration.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isValid() const;
+
+ PxVec3 minimum, maximum;
+};
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3::PxBounds3(const PxVec3& minimum_, const PxVec3& maximum_)
+: minimum(minimum_), maximum(maximum_)
+{
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 PxBounds3::empty()
+{
+ return PxBounds3(PxVec3(PX_MAX_BOUNDS_EXTENTS), PxVec3(-PX_MAX_BOUNDS_EXTENTS));
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isFinite() const
+{
+ return minimum.isFinite() && maximum.isFinite();
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 PxBounds3::boundsOfPoints(const PxVec3& v0, const PxVec3& v1)
+{
+ return PxBounds3(v0.minimum(v1), v0.maximum(v1));
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxBounds3 PxBounds3::centerExtents(const PxVec3& center, const PxVec3& extent)
+{
+ return PxBounds3(center - extent, center + extent);
+}
+
+PX_CUDA_CALLABLE PX_INLINE PxBounds3
+PxBounds3::basisExtent(const PxVec3& center, const PxMat33& basis, const PxVec3& extent)
+{
+ // extended basis vectors
+ PxVec3 c0 = basis.column0 * extent.x;
+ PxVec3 c1 = basis.column1 * extent.y;
+ PxVec3 c2 = basis.column2 * extent.z;
+
+ PxVec3 w;
+ // find combination of base vectors that produces max. distance for each component = sum of abs()
+ w.x = PxAbs(c0.x) + PxAbs(c1.x) + PxAbs(c2.x);
+ w.y = PxAbs(c0.y) + PxAbs(c1.y) + PxAbs(c2.y);
+ w.z = PxAbs(c0.z) + PxAbs(c1.z) + PxAbs(c2.z);
+
+ return PxBounds3(center - w, center + w);
+}
+
+PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::poseExtent(const PxTransform& pose, const PxVec3& extent)
+{
+ return basisExtent(pose.p, PxMat33(pose.q), extent);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::setEmpty()
+{
+ minimum = PxVec3(PX_MAX_BOUNDS_EXTENTS);
+ maximum = PxVec3(-PX_MAX_BOUNDS_EXTENTS);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::setMaximal()
+{
+ minimum = PxVec3(-PX_MAX_BOUNDS_EXTENTS);
+ maximum = PxVec3(PX_MAX_BOUNDS_EXTENTS);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::include(const PxVec3& v)
+{
+ PX_ASSERT(isValid());
+ minimum = minimum.minimum(v);
+ maximum = maximum.maximum(v);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::include(const PxBounds3& b)
+{
+ PX_ASSERT(isValid());
+ minimum = minimum.minimum(b.minimum);
+ maximum = maximum.maximum(b.maximum);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isEmpty() const
+{
+ PX_ASSERT(isValid());
+ return minimum.x > maximum.x;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::intersects(const PxBounds3& b) const
+{
+ PX_ASSERT(isValid() && b.isValid());
+ return !(b.minimum.x > maximum.x || minimum.x > b.maximum.x || b.minimum.y > maximum.y || minimum.y > b.maximum.y ||
+ b.minimum.z > maximum.z || minimum.z > b.maximum.z);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::intersects1D(const PxBounds3& a, uint32_t axis) const
+{
+ PX_ASSERT(isValid() && a.isValid());
+ return maximum[axis] >= a.minimum[axis] && a.maximum[axis] >= minimum[axis];
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::contains(const PxVec3& v) const
+{
+ PX_ASSERT(isValid());
+
+ return !(v.x < minimum.x || v.x > maximum.x || v.y < minimum.y || v.y > maximum.y || v.z < minimum.z ||
+ v.z > maximum.z);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isInside(const PxBounds3& box) const
+{
+ PX_ASSERT(isValid() && box.isValid());
+ if(box.minimum.x > minimum.x)
+ return false;
+ if(box.minimum.y > minimum.y)
+ return false;
+ if(box.minimum.z > minimum.z)
+ return false;
+ if(box.maximum.x < maximum.x)
+ return false;
+ if(box.maximum.y < maximum.y)
+ return false;
+ if(box.maximum.z < maximum.z)
+ return false;
+ return true;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::getCenter() const
+{
+ PX_ASSERT(isValid());
+ return (minimum + maximum) * 0.5f;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxBounds3::getCenter(uint32_t axis) const
+{
+ PX_ASSERT(isValid());
+ return (minimum[axis] + maximum[axis]) * 0.5f;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxBounds3::getExtents(uint32_t axis) const
+{
+ PX_ASSERT(isValid());
+ return (maximum[axis] - minimum[axis]) * 0.5f;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::getDimensions() const
+{
+ PX_ASSERT(isValid());
+ return maximum - minimum;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 PxBounds3::getExtents() const
+{
+ PX_ASSERT(isValid());
+ return getDimensions() * 0.5f;
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::scaleSafe(float scale)
+{
+ PX_ASSERT(isValid());
+ if(!isEmpty())
+ scaleFast(scale);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::scaleFast(float scale)
+{
+ PX_ASSERT(isValid());
+ *this = centerExtents(getCenter(), getExtents() * scale);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::fattenSafe(float distance)
+{
+ PX_ASSERT(isValid());
+ if(!isEmpty())
+ fattenFast(distance);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE void PxBounds3::fattenFast(float distance)
+{
+ PX_ASSERT(isValid());
+ minimum.x -= distance;
+ minimum.y -= distance;
+ minimum.z -= distance;
+
+ maximum.x += distance;
+ maximum.y += distance;
+ maximum.z += distance;
+}
+
+PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformSafe(const PxMat33& matrix, const PxBounds3& bounds)
+{
+ PX_ASSERT(bounds.isValid());
+ return !bounds.isEmpty() ? transformFast(matrix, bounds) : bounds;
+}
+
+PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformFast(const PxMat33& matrix, const PxBounds3& bounds)
+{
+ PX_ASSERT(bounds.isValid());
+ return PxBounds3::basisExtent(matrix * bounds.getCenter(), matrix, bounds.getExtents());
+}
+
+PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformSafe(const PxTransform& transform, const PxBounds3& bounds)
+{
+ PX_ASSERT(bounds.isValid());
+ return !bounds.isEmpty() ? transformFast(transform, bounds) : bounds;
+}
+
+PX_CUDA_CALLABLE PX_INLINE PxBounds3 PxBounds3::transformFast(const PxTransform& transform, const PxBounds3& bounds)
+{
+ PX_ASSERT(bounds.isValid());
+ return PxBounds3::basisExtent(transform.transform(bounds.getCenter()), PxMat33(transform.q), bounds.getExtents());
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxBounds3::isValid() const
+{
+ return (isFinite() && (((minimum.x <= maximum.x) && (minimum.y <= maximum.y) && (minimum.z <= maximum.z)) ||
+ ((minimum.x == PX_MAX_BOUNDS_EXTENTS) && (minimum.y == PX_MAX_BOUNDS_EXTENTS) &&
+ (minimum.z == PX_MAX_BOUNDS_EXTENTS) && (maximum.x == -PX_MAX_BOUNDS_EXTENTS) &&
+ (maximum.y == -PX_MAX_BOUNDS_EXTENTS) && (maximum.z == -PX_MAX_BOUNDS_EXTENTS))));
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXBOUNDS3_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrorCallback.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrorCallback.h
new file mode 100644
index 0000000..8b63374
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrorCallback.h
@@ -0,0 +1,73 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXERRORCALLBACK_H
+#define PXFOUNDATION_PXERRORCALLBACK_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxErrors.h"
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief User defined interface class. Used by the library to emit debug information.
+
+\note The SDK state should not be modified from within any error reporting functions.
+
+<b>Threading:</b> The SDK sequences its calls to the output stream using a mutex, so the class need not
+be implemented in a thread-safe manner if the SDK is the only client.
+*/
+class PxErrorCallback
+{
+ public:
+ virtual ~PxErrorCallback()
+ {
+ }
+
+ /**
+ \brief Reports an error code.
+ \param code Error code, see #PxErrorCode
+ \param message Message to display.
+ \param file File error occured in.
+ \param line Line number error occured on.
+ */
+ virtual void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) = 0;
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXERRORCALLBACK_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrors.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrors.h
new file mode 100644
index 0000000..fb341bb
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxErrors.h
@@ -0,0 +1,93 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXERRORS_H
+#define PXFOUNDATION_PXERRORS_H
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/Px.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Error codes
+
+These error codes are passed to #PxErrorCallback
+
+@see PxErrorCallback
+*/
+
+struct PxErrorCode
+{
+ enum Enum
+ {
+ eNO_ERROR = 0,
+
+ //! \brief An informational message.
+ eDEBUG_INFO = 1,
+
+ //! \brief a warning message for the user to help with debugging
+ eDEBUG_WARNING = 2,
+
+ //! \brief method called with invalid parameter(s)
+ eINVALID_PARAMETER = 4,
+
+ //! \brief method was called at a time when an operation is not possible
+ eINVALID_OPERATION = 8,
+
+ //! \brief method failed to allocate some memory
+ eOUT_OF_MEMORY = 16,
+
+ /** \brief The library failed for some reason.
+ Possibly you have passed invalid values like NaNs, which are not checked for.
+ */
+ eINTERNAL_ERROR = 32,
+
+ //! \brief An unrecoverable error, execution should be halted and log output flushed
+ eABORT = 64,
+
+ //! \brief The SDK has determined that an operation may result in poor performance.
+ ePERF_WARNING = 128,
+
+ //! \brief A bit mask for including all errors
+ eMASK_ALL = -1
+ };
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXERRORS_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFlags.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFlags.h
new file mode 100644
index 0000000..1aec096
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFlags.h
@@ -0,0 +1,375 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXFLAGS_H
+#define PXFOUNDATION_PXFLAGS_H
+
+/** \addtogroup foundation
+ @{
+*/
+
+#include "foundation/Px.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+/**
+\brief Container for bitfield flag variables associated with a specific enum type.
+
+This allows for type safe manipulation for bitfields.
+
+<h3>Example</h3>
+ // enum that defines each bit...
+ struct MyEnum
+ {
+ enum Enum
+ {
+ eMAN = 1,
+ eBEAR = 2,
+ ePIG = 4,
+ };
+ };
+
+ // implements some convenient global operators.
+ PX_FLAGS_OPERATORS(MyEnum::Enum, uint8_t);
+
+ PxFlags<MyEnum::Enum, uint8_t> myFlags;
+ myFlags |= MyEnum::eMAN;
+ myFlags |= MyEnum::eBEAR | MyEnum::ePIG;
+ if(myFlags & MyEnum::eBEAR)
+ {
+ doSomething();
+ }
+*/
+
+template <typename enumtype, typename storagetype = uint32_t>
+class PxFlags
+{
+ public:
+ typedef storagetype InternalType;
+
+ PX_CUDA_CALLABLE PX_INLINE explicit PxFlags(const PxEMPTY)
+ {
+ }
+ PX_CUDA_CALLABLE PX_INLINE PxFlags(void);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags(enumtype e);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags(const PxFlags<enumtype, storagetype>& f);
+ PX_CUDA_CALLABLE PX_INLINE explicit PxFlags(storagetype b);
+
+ PX_CUDA_CALLABLE PX_INLINE bool isSet(enumtype e) const;
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& set(enumtype e);
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(enumtype e) const;
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxFlags<enumtype, storagetype>& f) const;
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(bool b) const;
+ PX_CUDA_CALLABLE PX_INLINE bool operator!=(enumtype e) const;
+ PX_CUDA_CALLABLE PX_INLINE bool operator!=(const PxFlags<enumtype, storagetype>& f) const;
+
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator=(const PxFlags<enumtype, storagetype>& f);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator=(enumtype e);
+
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator|=(enumtype e);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator|=(const PxFlags<enumtype, storagetype>& f);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator|(enumtype e) const;
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator|(const PxFlags<enumtype, storagetype>& f) const;
+
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator&=(enumtype e);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator&=(const PxFlags<enumtype, storagetype>& f);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator&(enumtype e) const;
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator&(const PxFlags<enumtype, storagetype>& f) const;
+
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator^=(enumtype e);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype>& operator^=(const PxFlags<enumtype, storagetype>& f);
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator^(enumtype e) const;
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator^(const PxFlags<enumtype, storagetype>& f) const;
+
+ PX_CUDA_CALLABLE PX_INLINE PxFlags<enumtype, storagetype> operator~(void) const;
+
+ PX_CUDA_CALLABLE PX_INLINE operator bool(void) const;
+ PX_CUDA_CALLABLE PX_INLINE operator uint8_t(void) const;
+ PX_CUDA_CALLABLE PX_INLINE operator uint16_t(void) const;
+ PX_CUDA_CALLABLE PX_INLINE operator uint32_t(void) const;
+
+ PX_CUDA_CALLABLE PX_INLINE void clear(enumtype e);
+
+ public:
+ friend PX_INLINE PxFlags<enumtype, storagetype> operator&(enumtype a, PxFlags<enumtype, storagetype>& b)
+ {
+ PxFlags<enumtype, storagetype> out;
+ out.mBits = a & b.mBits;
+ return out;
+ }
+
+ private:
+ storagetype mBits;
+};
+
+#define PX_FLAGS_OPERATORS(enumtype, storagetype) \
+ PX_INLINE PxFlags<enumtype, storagetype> operator|(enumtype a, enumtype b) \
+ { \
+ PxFlags<enumtype, storagetype> r(a); \
+ r |= b; \
+ return r; \
+ } \
+ PX_INLINE PxFlags<enumtype, storagetype> operator&(enumtype a, enumtype b) \
+ { \
+ PxFlags<enumtype, storagetype> r(a); \
+ r &= b; \
+ return r; \
+ } \
+ PX_INLINE PxFlags<enumtype, storagetype> operator~(enumtype a) \
+ { \
+ return ~PxFlags<enumtype, storagetype>(a); \
+ }
+
+#define PX_FLAGS_TYPEDEF(x, y) \
+ typedef PxFlags<x::Enum, y> x##s; \
+ PX_FLAGS_OPERATORS(x::Enum, y)
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::PxFlags(void)
+{
+ mBits = 0;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::PxFlags(enumtype e)
+{
+ mBits = static_cast<storagetype>(e);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::PxFlags(const PxFlags<enumtype, storagetype>& f)
+{
+ mBits = f.mBits;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::PxFlags(storagetype b)
+{
+ mBits = b;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE bool PxFlags<enumtype, storagetype>::isSet(enumtype e) const
+{
+ return (mBits & static_cast<storagetype>(e)) == static_cast<storagetype>(e);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::set(enumtype e)
+{
+ mBits = static_cast<storagetype>(e);
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE bool PxFlags<enumtype, storagetype>::operator==(enumtype e) const
+{
+ return mBits == static_cast<storagetype>(e);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE bool PxFlags<enumtype, storagetype>::operator==(const PxFlags<enumtype, storagetype>& f) const
+{
+ return mBits == f.mBits;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE bool PxFlags<enumtype, storagetype>::operator==(bool b) const
+{
+ return bool(*this) == b;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE bool PxFlags<enumtype, storagetype>::operator!=(enumtype e) const
+{
+ return mBits != static_cast<storagetype>(e);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE bool PxFlags<enumtype, storagetype>::operator!=(const PxFlags<enumtype, storagetype>& f) const
+{
+ return mBits != f.mBits;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::operator=(enumtype e)
+{
+ mBits = static_cast<storagetype>(e);
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::operator=(const PxFlags<enumtype, storagetype>& f)
+{
+ mBits = f.mBits;
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::operator|=(enumtype e)
+{
+ mBits |= static_cast<storagetype>(e);
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::
+operator|=(const PxFlags<enumtype, storagetype>& f)
+{
+ mBits |= f.mBits;
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::operator|(enumtype e) const
+{
+ PxFlags<enumtype, storagetype> out(*this);
+ out |= e;
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::
+operator|(const PxFlags<enumtype, storagetype>& f) const
+{
+ PxFlags<enumtype, storagetype> out(*this);
+ out |= f;
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::operator&=(enumtype e)
+{
+ mBits &= static_cast<storagetype>(e);
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::
+operator&=(const PxFlags<enumtype, storagetype>& f)
+{
+ mBits &= f.mBits;
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::operator&(enumtype e) const
+{
+ PxFlags<enumtype, storagetype> out = *this;
+ out.mBits &= static_cast<storagetype>(e);
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::
+operator&(const PxFlags<enumtype, storagetype>& f) const
+{
+ PxFlags<enumtype, storagetype> out = *this;
+ out.mBits &= f.mBits;
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::operator^=(enumtype e)
+{
+ mBits ^= static_cast<storagetype>(e);
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>& PxFlags<enumtype, storagetype>::
+operator^=(const PxFlags<enumtype, storagetype>& f)
+{
+ mBits ^= f.mBits;
+ return *this;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::operator^(enumtype e) const
+{
+ PxFlags<enumtype, storagetype> out = *this;
+ out.mBits ^= static_cast<storagetype>(e);
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::
+operator^(const PxFlags<enumtype, storagetype>& f) const
+{
+ PxFlags<enumtype, storagetype> out = *this;
+ out.mBits ^= f.mBits;
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype> PxFlags<enumtype, storagetype>::operator~(void) const
+{
+ PxFlags<enumtype, storagetype> out;
+ out.mBits = storagetype(~mBits);
+ return out;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::operator bool(void) const
+{
+ return mBits ? true : false;
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::operator uint8_t(void) const
+{
+ return static_cast<uint8_t>(mBits);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::operator uint16_t(void) const
+{
+ return static_cast<uint16_t>(mBits);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE PxFlags<enumtype, storagetype>::operator uint32_t(void) const
+{
+ return static_cast<uint32_t>(mBits);
+}
+
+template <typename enumtype, typename storagetype>
+PX_INLINE void PxFlags<enumtype, storagetype>::clear(enumtype e)
+{
+ mBits &= ~static_cast<storagetype>(e);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXFLAGS_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundation.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundation.h
new file mode 100644
index 0000000..8642c16
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundation.h
@@ -0,0 +1,147 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PX_FOUNDATION_PX_FOUNDATION_H
+#define PX_FOUNDATION_PX_FOUNDATION_H
+
+/** \addtogroup foundation
+ @{
+*/
+
+#include "foundation/Px.h"
+#include "foundation/PxErrors.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Foundation SDK singleton class.
+
+You need to have an instance of this class to instance the higher level SDKs.
+*/
+class PX_FOUNDATION_API PxFoundation
+{
+ public:
+ /**
+ \brief Destroys the instance it is called on.
+
+ The operation will fail, if there are still modules referencing the foundation object. Release all dependent modules
+ prior
+ to calling this method.
+
+ @see PxCreateFoundation()
+ */
+ virtual void release() = 0;
+
+ /**
+ retrieves error callback
+ */
+ virtual PxErrorCallback& getErrorCallback() = 0;
+
+ /**
+ Sets mask of errors to report.
+ */
+ virtual void setErrorLevel(PxErrorCode::Enum mask = PxErrorCode::eMASK_ALL) = 0;
+
+ /**
+ Retrieves mask of errors to be reported.
+ */
+ virtual PxErrorCode::Enum getErrorLevel() const = 0;
+
+ /**
+ Retrieves the allocator this object was created with.
+ */
+ virtual PxAllocatorCallback& getAllocatorCallback() = 0;
+
+ /**
+ Retrieves if allocation names are being passed to allocator callback.
+ */
+ virtual bool getReportAllocationNames() const = 0;
+
+ /**
+ Set if allocation names are being passed to allocator callback.
+ \details Enabled by default in debug and checked build, disabled by default in profile and release build.
+ */
+ virtual void setReportAllocationNames(bool value) = 0;
+
+ protected:
+ virtual ~PxFoundation()
+ {
+ }
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/**
+\brief Creates an instance of the foundation class
+
+The foundation class is needed to initialize higher level SDKs. There may be only one instance per process.
+Calling this method after an instance has been created already will result in an error message and NULL will be
+returned.
+
+\param version Version number we are expecting (should be PX_FOUNDATION_VERSION)
+\param allocator User supplied interface for allocating memory(see #PxAllocatorCallback)
+\param errorCallback User supplied interface for reporting errors and displaying messages(see #PxErrorCallback)
+\return Foundation instance on success, NULL if operation failed
+
+@see PxFoundation
+*/
+
+PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation* PX_CALL_CONV
+PxCreateFoundation(physx::PxU32 version, physx::PxAllocatorCallback& allocator, physx::PxErrorCallback& errorCallback);
+/**
+\brief Retrieves the Foundation SDK after it has been created.
+
+\note The behavior of this method is undefined if the foundation instance has not been created already.
+
+@see PxCreateFoundation()
+*/
+PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation& PX_CALL_CONV PxGetFoundation();
+
+namespace physx
+{
+class PxProfilerCallback;
+}
+
+/**
+\brief Get the callback that will be used for all profiling.
+*/
+PX_C_EXPORT PX_FOUNDATION_API physx::PxProfilerCallback* PX_CALL_CONV PxGetProfilerCallback();
+
+/**
+\brief Set the callback that will be used for all profiling.
+*/
+PX_C_EXPORT PX_FOUNDATION_API void PX_CALL_CONV PxSetProfilerCallback(physx::PxProfilerCallback* profiler);
+
+/** @} */
+#endif // PX_FOUNDATION_PX_FOUNDATION_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundationVersion.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundationVersion.h
new file mode 100644
index 0000000..6547405
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxFoundationVersion.h
@@ -0,0 +1,65 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PX_FOUNDATION_VERSION_NUMBER_H
+#define PX_FOUNDATION_VERSION_NUMBER_H
+
+/*
+VersionNumbers: The combination of these
+numbers uniquely identifies the API, and should
+be incremented when the SDK API changes. This may
+include changes to file formats.
+
+This header is included in the main SDK header files
+so that the entire SDK and everything that builds on it
+is completely rebuilt when this file changes. Thus,
+this file is not to include a frequently changing
+build number. See BuildNumber.h for that.
+
+Each of these three values should stay below 255 because
+sometimes they are stored in a byte.
+*/
+/** \addtogroup foundation
+ @{
+*/
+
+#define PX_FOUNDATION_VERSION_MAJOR 1
+#define PX_FOUNDATION_VERSION_MINOR 0
+#define PX_FOUNDATION_VERSION_BUGFIX 0
+
+/**
+The constant PX_FOUNDATION_VERSION is used when creating certain PhysX module objects.
+This is to ensure that the application is using the same header version as the library was built with.
+*/
+#define PX_FOUNDATION_VERSION \
+ ((PX_FOUNDATION_VERSION_MAJOR << 24) + (PX_FOUNDATION_VERSION_MINOR << 16) + (PX_FOUNDATION_VERSION_BUGFIX << 8) + 0)
+
+#endif // PX_FOUNDATION_VERSION_NUMBER_H
+
+/** @} */
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIO.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIO.h
new file mode 100644
index 0000000..77ea1b6
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIO.h
@@ -0,0 +1,138 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXIO_H
+#define PXFOUNDATION_PXIO_H
+
+/** \addtogroup common
+ @{
+*/
+
+#include "foundation/PxSimpleTypes.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Input stream class for I/O.
+
+The user needs to supply a PxInputStream implementation to a number of methods to allow the SDK to read data.
+*/
+
+class PxInputStream
+{
+ public:
+ /**
+ \brief read from the stream. The number of bytes read may be less than the number requested.
+
+ \param[in] dest the destination address to which the data will be read
+ \param[in] count the number of bytes requested
+
+ \return the number of bytes read from the stream.
+ */
+
+ virtual uint32_t read(void* dest, uint32_t count) = 0;
+
+ virtual ~PxInputStream()
+ {
+ }
+};
+
+/**
+\brief Input data class for I/O which provides random read access.
+
+The user needs to supply a PxInputData implementation to a number of methods to allow the SDK to read data.
+*/
+
+class PxInputData : public PxInputStream
+{
+ public:
+ /**
+ \brief return the length of the input data
+
+ \return size in bytes of the input data
+ */
+
+ virtual uint32_t getLength() const = 0;
+
+ /**
+ \brief seek to the given offset from the start of the data.
+
+ \param[in] offset the offset to seek to. If greater than the length of the data, this call is equivalent to
+ seek(length);
+ */
+
+ virtual void seek(uint32_t offset) = 0;
+
+ /**
+ \brief return the current offset from the start of the data
+
+ \return the offset to seek to.
+ */
+
+ virtual uint32_t tell() const = 0;
+
+ virtual ~PxInputData()
+ {
+ }
+};
+
+/**
+\brief Output stream class for I/O.
+
+The user needs to supply a PxOutputStream implementation to a number of methods to allow the SDK to write data.
+*/
+
+class PxOutputStream
+{
+ public:
+ /**
+ \brief write to the stream. The number of bytes written may be less than the number sent.
+
+ \param[in] src the destination address from which the data will be written
+ \param[in] count the number of bytes to be written
+
+ \return the number of bytes written to the stream by this call.
+ */
+
+ virtual uint32_t write(const void* src, uint32_t count) = 0;
+
+ virtual ~PxOutputStream()
+ {
+ }
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXIO_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIntrinsics.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIntrinsics.h
new file mode 100644
index 0000000..471f934
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxIntrinsics.h
@@ -0,0 +1,47 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXINTRINSICS_H
+#define PXFOUNDATION_PXINTRINSICS_H
+
+#include "foundation/PxPreprocessor.h"
+
+#if PX_WINDOWS_FAMILY
+#include "foundation/windows/PxWindowsIntrinsics.h"
+#elif(PX_LINUX || PX_ANDROID || PX_APPLE_FAMILY || PX_PS4)
+#include "foundation/unix/PxUnixIntrinsics.h"
+#elif PX_XBOXONE
+#include "foundation/XboxOne/PxXboxOneIntrinsics.h"
+#elif PX_NX
+#include "foundation/nx/PxNXIntrinsics.h"
+#else
+#error "Platform not supported!"
+#endif
+
+#endif // #ifndef PXFOUNDATION_PXINTRINSICS_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat33.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat33.h
new file mode 100644
index 0000000..a3977c5
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat33.h
@@ -0,0 +1,396 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXMAT33_H
+#define PXFOUNDATION_PXMAT33_H
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxVec3.h"
+#include "foundation/PxQuat.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+/*!
+\brief 3x3 matrix class
+
+Some clarifications, as there have been much confusion about matrix formats etc in the past.
+
+Short:
+- Matrix have base vectors in columns (vectors are column matrices, 3x1 matrices).
+- Matrix is physically stored in column major format
+- Matrices are concaternated from left
+
+Long:
+Given three base vectors a, b and c the matrix is stored as
+
+|a.x b.x c.x|
+|a.y b.y c.y|
+|a.z b.z c.z|
+
+Vectors are treated as columns, so the vector v is
+
+|x|
+|y|
+|z|
+
+And matrices are applied _before_ the vector (pre-multiplication)
+v' = M*v
+
+|x'| |a.x b.x c.x| |x| |a.x*x + b.x*y + c.x*z|
+|y'| = |a.y b.y c.y| * |y| = |a.y*x + b.y*y + c.y*z|
+|z'| |a.z b.z c.z| |z| |a.z*x + b.z*y + c.z*z|
+
+
+Physical storage and indexing:
+To be compatible with popular 3d rendering APIs (read D3d and OpenGL)
+the physical indexing is
+
+|0 3 6|
+|1 4 7|
+|2 5 8|
+
+index = column*3 + row
+
+which in C++ translates to M[column][row]
+
+The mathematical indexing is M_row,column and this is what is used for _-notation
+so _12 is 1st row, second column and operator(row, column)!
+
+*/
+class PxMat33
+{
+ public:
+ //! Default constructor
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33()
+ {
+ }
+
+ //! identity constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat33(PxIDENTITY r)
+ : column0(1.0f, 0.0f, 0.0f), column1(0.0f, 1.0f, 0.0f), column2(0.0f, 0.0f, 1.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ //! zero constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat33(PxZERO r) : column0(0.0f), column1(0.0f), column2(0.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ //! Construct from three base vectors
+ PX_CUDA_CALLABLE PxMat33(const PxVec3& col0, const PxVec3& col1, const PxVec3& col2)
+ : column0(col0), column1(col1), column2(col2)
+ {
+ }
+
+ //! constructor from a scalar, which generates a multiple of the identity matrix
+ explicit PX_CUDA_CALLABLE PX_INLINE PxMat33(float r)
+ : column0(r, 0.0f, 0.0f), column1(0.0f, r, 0.0f), column2(0.0f, 0.0f, r)
+ {
+ }
+
+ //! Construct from float[9]
+ explicit PX_CUDA_CALLABLE PX_INLINE PxMat33(float values[])
+ : column0(values[0], values[1], values[2])
+ , column1(values[3], values[4], values[5])
+ , column2(values[6], values[7], values[8])
+ {
+ }
+
+ //! Construct from a quaternion
+ explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33(const PxQuat& q)
+ {
+ const float x = q.x;
+ const float y = q.y;
+ const float z = q.z;
+ const float w = q.w;
+
+ const float x2 = x + x;
+ const float y2 = y + y;
+ const float z2 = z + z;
+
+ const float xx = x2 * x;
+ const float yy = y2 * y;
+ const float zz = z2 * z;
+
+ const float xy = x2 * y;
+ const float xz = x2 * z;
+ const float xw = x2 * w;
+
+ const float yz = y2 * z;
+ const float yw = y2 * w;
+ const float zw = z2 * w;
+
+ column0 = PxVec3(1.0f - yy - zz, xy + zw, xz - yw);
+ column1 = PxVec3(xy - zw, 1.0f - xx - zz, yz + xw);
+ column2 = PxVec3(xz + yw, yz - xw, 1.0f - xx - yy);
+ }
+
+ //! Copy constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat33(const PxMat33& other)
+ : column0(other.column0), column1(other.column1), column2(other.column2)
+ {
+ }
+
+ //! Assignment operator
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33& operator=(const PxMat33& other)
+ {
+ column0 = other.column0;
+ column1 = other.column1;
+ column2 = other.column2;
+ return *this;
+ }
+
+ //! Construct from diagonal, off-diagonals are zero.
+ PX_CUDA_CALLABLE PX_INLINE static const PxMat33 createDiagonal(const PxVec3& d)
+ {
+ return PxMat33(PxVec3(d.x, 0.0f, 0.0f), PxVec3(0.0f, d.y, 0.0f), PxVec3(0.0f, 0.0f, d.z));
+ }
+
+ /**
+ \brief returns true if the two matrices are exactly equal
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxMat33& m) const
+ {
+ return column0 == m.column0 && column1 == m.column1 && column2 == m.column2;
+ }
+
+ //! Get transposed matrix
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const PxMat33 getTranspose() const
+ {
+ const PxVec3 v0(column0.x, column1.x, column2.x);
+ const PxVec3 v1(column0.y, column1.y, column2.y);
+ const PxVec3 v2(column0.z, column1.z, column2.z);
+
+ return PxMat33(v0, v1, v2);
+ }
+
+ //! Get the real inverse
+ PX_CUDA_CALLABLE PX_INLINE const PxMat33 getInverse() const
+ {
+ const float det = getDeterminant();
+ PxMat33 inverse;
+
+ if(det != 0)
+ {
+ const float invDet = 1.0f / det;
+
+ inverse.column0.x = invDet * (column1.y * column2.z - column2.y * column1.z);
+ inverse.column0.y = invDet * -(column0.y * column2.z - column2.y * column0.z);
+ inverse.column0.z = invDet * (column0.y * column1.z - column0.z * column1.y);
+
+ inverse.column1.x = invDet * -(column1.x * column2.z - column1.z * column2.x);
+ inverse.column1.y = invDet * (column0.x * column2.z - column0.z * column2.x);
+ inverse.column1.z = invDet * -(column0.x * column1.z - column0.z * column1.x);
+
+ inverse.column2.x = invDet * (column1.x * column2.y - column1.y * column2.x);
+ inverse.column2.y = invDet * -(column0.x * column2.y - column0.y * column2.x);
+ inverse.column2.z = invDet * (column0.x * column1.y - column1.x * column0.y);
+
+ return inverse;
+ }
+ else
+ {
+ return PxMat33(PxIdentity);
+ }
+ }
+
+ //! Get determinant
+ PX_CUDA_CALLABLE PX_INLINE float getDeterminant() const
+ {
+ return column0.dot(column1.cross(column2));
+ }
+
+ //! Unary minus
+ PX_CUDA_CALLABLE PX_INLINE const PxMat33 operator-() const
+ {
+ return PxMat33(-column0, -column1, -column2);
+ }
+
+ //! Add
+ PX_CUDA_CALLABLE PX_INLINE const PxMat33 operator+(const PxMat33& other) const
+ {
+ return PxMat33(column0 + other.column0, column1 + other.column1, column2 + other.column2);
+ }
+
+ //! Subtract
+ PX_CUDA_CALLABLE PX_INLINE const PxMat33 operator-(const PxMat33& other) const
+ {
+ return PxMat33(column0 - other.column0, column1 - other.column1, column2 - other.column2);
+ }
+
+ //! Scalar multiplication
+ PX_CUDA_CALLABLE PX_INLINE const PxMat33 operator*(float scalar) const
+ {
+ return PxMat33(column0 * scalar, column1 * scalar, column2 * scalar);
+ }
+
+ friend PxMat33 operator*(float, const PxMat33&);
+
+ //! Matrix vector multiplication (returns 'this->transform(vec)')
+ PX_CUDA_CALLABLE PX_INLINE const PxVec3 operator*(const PxVec3& vec) const
+ {
+ return transform(vec);
+ }
+
+ // a <op>= b operators
+
+ //! Matrix multiplication
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const PxMat33 operator*(const PxMat33& other) const
+ {
+ // Rows from this <dot> columns from other
+ // column0 = transform(other.column0) etc
+ return PxMat33(transform(other.column0), transform(other.column1), transform(other.column2));
+ }
+
+ //! Equals-add
+ PX_CUDA_CALLABLE PX_INLINE PxMat33& operator+=(const PxMat33& other)
+ {
+ column0 += other.column0;
+ column1 += other.column1;
+ column2 += other.column2;
+ return *this;
+ }
+
+ //! Equals-sub
+ PX_CUDA_CALLABLE PX_INLINE PxMat33& operator-=(const PxMat33& other)
+ {
+ column0 -= other.column0;
+ column1 -= other.column1;
+ column2 -= other.column2;
+ return *this;
+ }
+
+ //! Equals scalar multiplication
+ PX_CUDA_CALLABLE PX_INLINE PxMat33& operator*=(float scalar)
+ {
+ column0 *= scalar;
+ column1 *= scalar;
+ column2 *= scalar;
+ return *this;
+ }
+
+ //! Equals matrix multiplication
+ PX_CUDA_CALLABLE PX_INLINE PxMat33& operator*=(const PxMat33& other)
+ {
+ *this = *this * other;
+ return *this;
+ }
+
+ //! Element access, mathematical way!
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE float operator()(unsigned int row, unsigned int col) const
+ {
+ return (*this)[col][row];
+ }
+
+ //! Element access, mathematical way!
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE float& operator()(unsigned int row, unsigned int col)
+ {
+ return (*this)[col][row];
+ }
+
+ // Transform etc
+
+ //! Transform vector by matrix, equal to v' = M*v
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3 transform(const PxVec3& other) const
+ {
+ return column0 * other.x + column1 * other.y + column2 * other.z;
+ }
+
+ //! Transform vector by matrix transpose, v' = M^t*v
+ PX_CUDA_CALLABLE PX_INLINE const PxVec3 transformTranspose(const PxVec3& other) const
+ {
+ return PxVec3(column0.dot(other), column1.dot(other), column2.dot(other));
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const float* front() const
+ {
+ return &column0.x;
+ }
+
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3& operator[](unsigned int num)
+ {
+ return (&column0)[num];
+ }
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& operator[](unsigned int num) const
+ {
+ return (&column0)[num];
+ }
+
+ // Data, see above for format!
+
+ PxVec3 column0, column1, column2; // the three base vectors
+};
+
+// implementation from PxQuat.h
+PX_CUDA_CALLABLE PX_INLINE PxQuat::PxQuat(const PxMat33& m)
+{
+ if(m.column2.z < 0)
+ {
+ if(m.column0.x > m.column1.y)
+ {
+ float t = 1 + m.column0.x - m.column1.y - m.column2.z;
+ *this = PxQuat(t, m.column0.y + m.column1.x, m.column2.x + m.column0.z, m.column1.z - m.column2.y) *
+ (0.5f / PxSqrt(t));
+ }
+ else
+ {
+ float t = 1 - m.column0.x + m.column1.y - m.column2.z;
+ *this = PxQuat(m.column0.y + m.column1.x, t, m.column1.z + m.column2.y, m.column2.x - m.column0.z) *
+ (0.5f / PxSqrt(t));
+ }
+ }
+ else
+ {
+ if(m.column0.x < -m.column1.y)
+ {
+ float t = 1 - m.column0.x - m.column1.y + m.column2.z;
+ *this = PxQuat(m.column2.x + m.column0.z, m.column1.z + m.column2.y, t, m.column0.y - m.column1.x) *
+ (0.5f / PxSqrt(t));
+ }
+ else
+ {
+ float t = 1 + m.column0.x + m.column1.y + m.column2.z;
+ *this = PxQuat(m.column1.z - m.column2.y, m.column2.x - m.column0.z, m.column0.y - m.column1.x, t) *
+ (0.5f / PxSqrt(t));
+ }
+ }
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXMAT33_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat44.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat44.h
new file mode 100644
index 0000000..95f4636
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMat44.h
@@ -0,0 +1,376 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXMAT44_H
+#define PXFOUNDATION_PXMAT44_H
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxQuat.h"
+#include "foundation/PxVec4.h"
+#include "foundation/PxMat33.h"
+#include "foundation/PxTransform.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/*!
+\brief 4x4 matrix class
+
+This class is layout-compatible with D3D and OpenGL matrices. More notes on layout are given in the PxMat33
+
+@see PxMat33 PxTransform
+*/
+
+class PxMat44
+{
+ public:
+ //! Default constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat44()
+ {
+ }
+
+ //! identity constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat44(PxIDENTITY r)
+ : column0(1.0f, 0.0f, 0.0f, 0.0f)
+ , column1(0.0f, 1.0f, 0.0f, 0.0f)
+ , column2(0.0f, 0.0f, 1.0f, 0.0f)
+ , column3(0.0f, 0.0f, 0.0f, 1.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ //! zero constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat44(PxZERO r) : column0(PxZero), column1(PxZero), column2(PxZero), column3(PxZero)
+ {
+ PX_UNUSED(r);
+ }
+
+ //! Construct from four 4-vectors
+ PX_CUDA_CALLABLE PxMat44(const PxVec4& col0, const PxVec4& col1, const PxVec4& col2, const PxVec4& col3)
+ : column0(col0), column1(col1), column2(col2), column3(col3)
+ {
+ }
+
+ //! constructor that generates a multiple of the identity matrix
+ explicit PX_CUDA_CALLABLE PX_INLINE PxMat44(float r)
+ : column0(r, 0.0f, 0.0f, 0.0f)
+ , column1(0.0f, r, 0.0f, 0.0f)
+ , column2(0.0f, 0.0f, r, 0.0f)
+ , column3(0.0f, 0.0f, 0.0f, r)
+ {
+ }
+
+ //! Construct from three base vectors and a translation
+ PX_CUDA_CALLABLE PxMat44(const PxVec3& col0, const PxVec3& col1, const PxVec3& col2, const PxVec3& col3)
+ : column0(col0, 0), column1(col1, 0), column2(col2, 0), column3(col3, 1.0f)
+ {
+ }
+
+ //! Construct from float[16]
+ explicit PX_CUDA_CALLABLE PX_INLINE PxMat44(float values[])
+ : column0(values[0], values[1], values[2], values[3])
+ , column1(values[4], values[5], values[6], values[7])
+ , column2(values[8], values[9], values[10], values[11])
+ , column3(values[12], values[13], values[14], values[15])
+ {
+ }
+
+ //! Construct from a quaternion
+ explicit PX_CUDA_CALLABLE PX_INLINE PxMat44(const PxQuat& q)
+ {
+ const float x = q.x;
+ const float y = q.y;
+ const float z = q.z;
+ const float w = q.w;
+
+ const float x2 = x + x;
+ const float y2 = y + y;
+ const float z2 = z + z;
+
+ const float xx = x2 * x;
+ const float yy = y2 * y;
+ const float zz = z2 * z;
+
+ const float xy = x2 * y;
+ const float xz = x2 * z;
+ const float xw = x2 * w;
+
+ const float yz = y2 * z;
+ const float yw = y2 * w;
+ const float zw = z2 * w;
+
+ column0 = PxVec4(1.0f - yy - zz, xy + zw, xz - yw, 0.0f);
+ column1 = PxVec4(xy - zw, 1.0f - xx - zz, yz + xw, 0.0f);
+ column2 = PxVec4(xz + yw, yz - xw, 1.0f - xx - yy, 0.0f);
+ column3 = PxVec4(0.0f, 0.0f, 0.0f, 1.0f);
+ }
+
+ //! Construct from a diagonal vector
+ explicit PX_CUDA_CALLABLE PX_INLINE PxMat44(const PxVec4& diagonal)
+ : column0(diagonal.x, 0.0f, 0.0f, 0.0f)
+ , column1(0.0f, diagonal.y, 0.0f, 0.0f)
+ , column2(0.0f, 0.0f, diagonal.z, 0.0f)
+ , column3(0.0f, 0.0f, 0.0f, diagonal.w)
+ {
+ }
+
+ //! Construct from Mat33 and a translation
+ PX_CUDA_CALLABLE PxMat44(const PxMat33& axes, const PxVec3& position)
+ : column0(axes.column0, 0.0f), column1(axes.column1, 0.0f), column2(axes.column2, 0.0f), column3(position, 1.0f)
+ {
+ }
+
+ PX_CUDA_CALLABLE PxMat44(const PxTransform& t)
+ {
+ *this = PxMat44(PxMat33(t.q), t.p);
+ }
+
+ /**
+ \brief returns true if the two matrices are exactly equal
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxMat44& m) const
+ {
+ return column0 == m.column0 && column1 == m.column1 && column2 == m.column2 && column3 == m.column3;
+ }
+
+ //! Copy constructor
+ PX_CUDA_CALLABLE PX_INLINE PxMat44(const PxMat44& other)
+ : column0(other.column0), column1(other.column1), column2(other.column2), column3(other.column3)
+ {
+ }
+
+ //! Assignment operator
+ PX_CUDA_CALLABLE PX_INLINE PxMat44& operator=(const PxMat44& other)
+ {
+ column0 = other.column0;
+ column1 = other.column1;
+ column2 = other.column2;
+ column3 = other.column3;
+ return *this;
+ }
+
+ //! Get transposed matrix
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 getTranspose() const
+ {
+ return PxMat44(
+ PxVec4(column0.x, column1.x, column2.x, column3.x), PxVec4(column0.y, column1.y, column2.y, column3.y),
+ PxVec4(column0.z, column1.z, column2.z, column3.z), PxVec4(column0.w, column1.w, column2.w, column3.w));
+ }
+
+ //! Unary minus
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 operator-() const
+ {
+ return PxMat44(-column0, -column1, -column2, -column3);
+ }
+
+ //! Add
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 operator+(const PxMat44& other) const
+ {
+ return PxMat44(column0 + other.column0, column1 + other.column1, column2 + other.column2,
+ column3 + other.column3);
+ }
+
+ //! Subtract
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 operator-(const PxMat44& other) const
+ {
+ return PxMat44(column0 - other.column0, column1 - other.column1, column2 - other.column2,
+ column3 - other.column3);
+ }
+
+ //! Scalar multiplication
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 operator*(float scalar) const
+ {
+ return PxMat44(column0 * scalar, column1 * scalar, column2 * scalar, column3 * scalar);
+ }
+
+ friend PxMat44 operator*(float, const PxMat44&);
+
+ //! Matrix multiplication
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 operator*(const PxMat44& other) const
+ {
+ // Rows from this <dot> columns from other
+ // column0 = transform(other.column0) etc
+ return PxMat44(transform(other.column0), transform(other.column1), transform(other.column2),
+ transform(other.column3));
+ }
+
+ // a <op>= b operators
+
+ //! Equals-add
+ PX_CUDA_CALLABLE PX_INLINE PxMat44& operator+=(const PxMat44& other)
+ {
+ column0 += other.column0;
+ column1 += other.column1;
+ column2 += other.column2;
+ column3 += other.column3;
+ return *this;
+ }
+
+ //! Equals-sub
+ PX_CUDA_CALLABLE PX_INLINE PxMat44& operator-=(const PxMat44& other)
+ {
+ column0 -= other.column0;
+ column1 -= other.column1;
+ column2 -= other.column2;
+ column3 -= other.column3;
+ return *this;
+ }
+
+ //! Equals scalar multiplication
+ PX_CUDA_CALLABLE PX_INLINE PxMat44& operator*=(float scalar)
+ {
+ column0 *= scalar;
+ column1 *= scalar;
+ column2 *= scalar;
+ column3 *= scalar;
+ return *this;
+ }
+
+ //! Equals matrix multiplication
+ PX_CUDA_CALLABLE PX_INLINE PxMat44& operator*=(const PxMat44& other)
+ {
+ *this = *this * other;
+ return *this;
+ }
+
+ //! Element access, mathematical way!
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE float operator()(unsigned int row, unsigned int col) const
+ {
+ return (*this)[col][row];
+ }
+
+ //! Element access, mathematical way!
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE float& operator()(unsigned int row, unsigned int col)
+ {
+ return (*this)[col][row];
+ }
+
+ //! Transform vector by matrix, equal to v' = M*v
+ PX_CUDA_CALLABLE PX_INLINE const PxVec4 transform(const PxVec4& other) const
+ {
+ return column0 * other.x + column1 * other.y + column2 * other.z + column3 * other.w;
+ }
+
+ //! Transform vector by matrix, equal to v' = M*v
+ PX_CUDA_CALLABLE PX_INLINE const PxVec3 transform(const PxVec3& other) const
+ {
+ return transform(PxVec4(other, 1.0f)).getXYZ();
+ }
+
+ //! Rotate vector by matrix, equal to v' = M*v
+ PX_CUDA_CALLABLE PX_INLINE const PxVec4 rotate(const PxVec4& other) const
+ {
+ return column0 * other.x + column1 * other.y + column2 * other.z; // + column3*0;
+ }
+
+ //! Rotate vector by matrix, equal to v' = M*v
+ PX_CUDA_CALLABLE PX_INLINE const PxVec3 rotate(const PxVec3& other) const
+ {
+ return rotate(PxVec4(other, 1.0f)).getXYZ();
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE const PxVec3 getBasis(int num) const
+ {
+ PX_ASSERT(num >= 0 && num < 3);
+ return (&column0)[num].getXYZ();
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE const PxVec3 getPosition() const
+ {
+ return column3.getXYZ();
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE void setPosition(const PxVec3& position)
+ {
+ column3.x = position.x;
+ column3.y = position.y;
+ column3.z = position.z;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const float* front() const
+ {
+ return &column0.x;
+ }
+
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4& operator[](unsigned int num)
+ {
+ return (&column0)[num];
+ }
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec4& operator[](unsigned int num) const
+ {
+ return (&column0)[num];
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE void scale(const PxVec4& p)
+ {
+ column0 *= p.x;
+ column1 *= p.y;
+ column2 *= p.z;
+ column3 *= p.w;
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE const PxMat44 inverseRT(void) const
+ {
+ PxVec3 r0(column0.x, column1.x, column2.x), r1(column0.y, column1.y, column2.y),
+ r2(column0.z, column1.z, column2.z);
+
+ return PxMat44(r0, r1, r2, -(r0 * column3.x + r1 * column3.y + r2 * column3.z));
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE bool isFinite() const
+ {
+ return column0.isFinite() && column1.isFinite() && column2.isFinite() && column3.isFinite();
+ }
+
+ // Data, see above for format!
+
+ PxVec4 column0, column1, column2, column3; // the four base vectors
+};
+
+// implementation from PxTransform.h
+PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform::PxTransform(const PxMat44& m)
+{
+ PxVec3 column0 = PxVec3(m.column0.x, m.column0.y, m.column0.z);
+ PxVec3 column1 = PxVec3(m.column1.x, m.column1.y, m.column1.z);
+ PxVec3 column2 = PxVec3(m.column2.x, m.column2.y, m.column2.z);
+
+ q = PxQuat(PxMat33(column0, column1, column2));
+ p = PxVec3(m.column3.x, m.column3.y, m.column3.z);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXMAT44_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMath.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMath.h
new file mode 100644
index 0000000..7cea398
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMath.h
@@ -0,0 +1,338 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXMATH_H
+#define PXFOUNDATION_PXMATH_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxPreprocessor.h"
+
+#if PX_VC
+#pragma warning(push)
+#pragma warning(disable : 4985) // 'symbol name': attributes not present on previous declaration
+#endif
+#include <math.h>
+#if PX_VC
+#pragma warning(pop)
+#endif
+
+#include <float.h>
+#include "foundation/PxIntrinsics.h"
+#include "foundation/PxAssert.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+// constants
+static const float PxPi = float(3.141592653589793);
+static const float PxHalfPi = float(1.57079632679489661923);
+static const float PxTwoPi = float(6.28318530717958647692);
+static const float PxInvPi = float(0.31830988618379067154);
+static const float PxInvTwoPi = float(0.15915494309189533577);
+static const float PxPiDivTwo = float(1.57079632679489661923);
+static const float PxPiDivFour = float(0.78539816339744830962);
+
+/**
+\brief The return value is the greater of the two specified values.
+*/
+template <class T>
+PX_CUDA_CALLABLE PX_FORCE_INLINE T PxMax(T a, T b)
+{
+ return a < b ? b : a;
+}
+
+//! overload for float to use fsel on xbox
+template <>
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxMax(float a, float b)
+{
+ return intrinsics::selectMax(a, b);
+}
+
+/**
+\brief The return value is the lesser of the two specified values.
+*/
+template <class T>
+PX_CUDA_CALLABLE PX_FORCE_INLINE T PxMin(T a, T b)
+{
+ return a < b ? a : b;
+}
+
+template <>
+//! overload for float to use fsel on xbox
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxMin(float a, float b)
+{
+ return intrinsics::selectMin(a, b);
+}
+
+/*
+Many of these are just implemented as PX_CUDA_CALLABLE PX_FORCE_INLINE calls to the C lib right now,
+but later we could replace some of them with some approximations or more
+clever stuff.
+*/
+
+/**
+\brief abs returns the absolute value of its argument.
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAbs(float a)
+{
+ return intrinsics::abs(a);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxEquals(float a, float b, float eps)
+{
+ return (PxAbs(a - b) < eps);
+}
+
+/**
+\brief abs returns the absolute value of its argument.
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAbs(double a)
+{
+ return ::fabs(a);
+}
+
+/**
+\brief abs returns the absolute value of its argument.
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE int32_t PxAbs(int32_t a)
+{
+ return ::abs(a);
+}
+
+/**
+\brief Clamps v to the range [hi,lo]
+*/
+template <class T>
+PX_CUDA_CALLABLE PX_FORCE_INLINE T PxClamp(T v, T lo, T hi)
+{
+ PX_ASSERT(lo <= hi);
+ return PxMin(hi, PxMax(lo, v));
+}
+
+//! \brief Square root.
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSqrt(float a)
+{
+ return intrinsics::sqrt(a);
+}
+
+//! \brief Square root.
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxSqrt(double a)
+{
+ return ::sqrt(a);
+}
+
+//! \brief reciprocal square root.
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxRecipSqrt(float a)
+{
+ return intrinsics::recipSqrt(a);
+}
+
+//! \brief reciprocal square root.
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxRecipSqrt(double a)
+{
+ return 1 / ::sqrt(a);
+}
+
+//! trigonometry -- all angles are in radians.
+
+//! \brief Sine of an angle ( <b>Unit:</b> Radians )
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSin(float a)
+{
+ return intrinsics::sin(a);
+}
+
+//! \brief Sine of an angle ( <b>Unit:</b> Radians )
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxSin(double a)
+{
+ return ::sin(a);
+}
+
+//! \brief Cosine of an angle (<b>Unit:</b> Radians)
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxCos(float a)
+{
+ return intrinsics::cos(a);
+}
+
+//! \brief Cosine of an angle (<b>Unit:</b> Radians)
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxCos(double a)
+{
+ return ::cos(a);
+}
+
+/**
+\brief Tangent of an angle.
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxTan(float a)
+{
+ return ::tanf(a);
+}
+
+/**
+\brief Tangent of an angle.
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxTan(double a)
+{
+ return ::tan(a);
+}
+
+/**
+\brief Arcsine.
+Returns angle between -PI/2 and PI/2 in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAsin(float f)
+{
+ return ::asinf(PxClamp(f, -1.0f, 1.0f));
+}
+
+/**
+\brief Arcsine.
+Returns angle between -PI/2 and PI/2 in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAsin(double f)
+{
+ return ::asin(PxClamp(f, -1.0, 1.0));
+}
+
+/**
+\brief Arccosine.
+Returns angle between 0 and PI in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAcos(float f)
+{
+ return ::acosf(PxClamp(f, -1.0f, 1.0f));
+}
+
+/**
+\brief Arccosine.
+Returns angle between 0 and PI in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAcos(double f)
+{
+ return ::acos(PxClamp(f, -1.0, 1.0));
+}
+
+/**
+\brief ArcTangent.
+Returns angle between -PI/2 and PI/2 in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAtan(float a)
+{
+ return ::atanf(a);
+}
+
+/**
+\brief ArcTangent.
+Returns angle between -PI/2 and PI/2 in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAtan(double a)
+{
+ return ::atan(a);
+}
+
+/**
+\brief Arctangent of (x/y) with correct sign.
+Returns angle between -PI and PI in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxAtan2(float x, float y)
+{
+ return ::atan2f(x, y);
+}
+
+/**
+\brief Arctangent of (x/y) with correct sign.
+Returns angle between -PI and PI in radians
+<b>Unit:</b> Radians
+*/
+PX_CUDA_CALLABLE PX_FORCE_INLINE double PxAtan2(double x, double y)
+{
+ return ::atan2(x, y);
+}
+
+//! \brief returns true if the passed number is a finite floating point number as opposed to INF, NAN, etc.
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxIsFinite(float f)
+{
+ return intrinsics::isFinite(f);
+}
+
+//! \brief returns true if the passed number is a finite floating point number as opposed to INF, NAN, etc.
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool PxIsFinite(double f)
+{
+ return intrinsics::isFinite(f);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxFloor(float a)
+{
+ return ::floorf(a);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxExp(float a)
+{
+ return ::expf(a);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxCeil(float a)
+{
+ return ::ceilf(a);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxSign(float a)
+{
+ return physx::intrinsics::sign(a);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxPow(float x, float y)
+{
+ return ::powf(x, y);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float PxLog(float x)
+{
+ return ::logf(x);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXMATH_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMathUtils.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMathUtils.h
new file mode 100644
index 0000000..11ddde5
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMathUtils.h
@@ -0,0 +1,73 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXMATHUTILS_H
+#define PXFOUNDATION_PXMATHUTILS_H
+
+/** \addtogroup common
+ @{
+*/
+
+#include "foundation/Px.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief finds the shortest rotation between two vectors.
+
+\param[in] from the vector to start from
+\param[in] target the vector to rotate to
+\return a rotation about an axis normal to the two vectors which takes one to the other via the shortest path
+*/
+
+PX_FOUNDATION_API PxQuat PxShortestRotation(const PxVec3& from, const PxVec3& target);
+
+/* \brief diagonalizes a 3x3 symmetric matrix y
+
+The returned matrix satisfies M = R * D * R', where R is the rotation matrix for the output quaternion, R' its
+transpose, and D the diagonal matrix
+
+If the matrix is not symmetric, the result is undefined.
+
+\param[in] m the matrix to diagonalize
+\param[out] axes a quaternion rotation which diagonalizes the matrix
+\return the vector diagonal of the diagonalized matrix.
+*/
+
+PX_FOUNDATION_API PxVec3 PxDiagonalize(const PxMat33& m, PxQuat& axes);
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMemory.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMemory.h
new file mode 100644
index 0000000..b0191e3
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxMemory.h
@@ -0,0 +1,110 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXMEMORY_H
+#define PXFOUNDATION_PXMEMORY_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/Px.h"
+#include "foundation/PxIntrinsics.h"
+#include "foundation/PxSimpleTypes.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Sets the bytes of the provided buffer to zero.
+
+\param dest Pointer to block of memory to set zero.
+\param count Number of bytes to set to zero.
+
+\return Pointer to memory block (same as input)
+*/
+PX_FORCE_INLINE void* PxMemZero(void* dest, PxU32 count)
+{
+ return physx::intrinsics::memZero(dest, count);
+}
+
+/**
+\brief Sets the bytes of the provided buffer to the specified value.
+
+\param dest Pointer to block of memory to set to the specified value.
+\param c Value to set the bytes of the block of memory to.
+\param count Number of bytes to set to the specified value.
+
+\return Pointer to memory block (same as input)
+*/
+PX_FORCE_INLINE void* PxMemSet(void* dest, PxI32 c, PxU32 count)
+{
+ return physx::intrinsics::memSet(dest, c, count);
+}
+
+/**
+\brief Copies the bytes of one memory block to another. The memory blocks must not overlap.
+
+\note Use #PxMemMove if memory blocks overlap.
+
+\param dest Pointer to block of memory to copy to.
+\param src Pointer to block of memory to copy from.
+\param count Number of bytes to copy.
+
+\return Pointer to destination memory block
+*/
+PX_FORCE_INLINE void* PxMemCopy(void* PX_RESTRICT dest, const void* PX_RESTRICT src, PxU32 count)
+{
+ return physx::intrinsics::memCopy(dest, src, count);
+}
+
+/**
+\brief Copies the bytes of one memory block to another. The memory blocks can overlap.
+
+\note Use #PxMemCopy if memory blocks do not overlap.
+
+\param dest Pointer to block of memory to copy to.
+\param src Pointer to block of memory to copy from.
+\param count Number of bytes to copy.
+
+\return Pointer to destination memory block
+*/
+PX_FORCE_INLINE void* PxMemMove(void* dest, const void* src, PxU32 count)
+{
+ return physx::intrinsics::memMove(dest, src, count);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // PXFOUNDATION_PXMEMORY_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPlane.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPlane.h
new file mode 100644
index 0000000..dcd542a
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPlane.h
@@ -0,0 +1,145 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXPLANE_H
+#define PXFOUNDATION_PXPLANE_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxMath.h"
+#include "foundation/PxVec3.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Representation of a plane.
+
+ Plane equation used: n.dot(v) + d = 0
+*/
+class PxPlane
+{
+ public:
+ /**
+ \brief Constructor
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane()
+ {
+ }
+
+ /**
+ \brief Constructor from a normal and a distance
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(float nx, float ny, float nz, float distance) : n(nx, ny, nz), d(distance)
+ {
+ }
+
+ /**
+ \brief Constructor from a normal and a distance
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(const PxVec3& normal, float distance) : n(normal), d(distance)
+ {
+ }
+
+ /**
+ \brief Constructor from a point on the plane and a normal
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(const PxVec3& point, const PxVec3& normal)
+ : n(normal), d(-point.dot(n)) // p satisfies normal.dot(p) + d = 0
+ {
+ }
+
+ /**
+ \brief Constructor from three points
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2)
+ {
+ n = (p1 - p0).cross(p2 - p0).getNormalized();
+ d = -p0.dot(n);
+ }
+
+ /**
+ \brief returns true if the two planes are exactly equal
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxPlane& p) const
+ {
+ return n == p.n && d == p.d;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float distance(const PxVec3& p) const
+ {
+ return p.dot(n) + d;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool contains(const PxVec3& p) const
+ {
+ return PxAbs(distance(p)) < (1.0e-7f);
+ }
+
+ /**
+ \brief projects p into the plane
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 project(const PxVec3& p) const
+ {
+ return p - n * distance(p);
+ }
+
+ /**
+ \brief find an arbitrary point in the plane
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 pointInPlane() const
+ {
+ return -n * d;
+ }
+
+ /**
+ \brief equivalent plane with unit normal
+ */
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE void normalize()
+ {
+ float denom = 1.0f / n.magnitude();
+ n *= denom;
+ d *= denom;
+ }
+
+ PxVec3 n; //!< The normal to the plane
+ float d; //!< The distance from the origin
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXPLANE_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPreprocessor.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPreprocessor.h
new file mode 100644
index 0000000..1bb74a4
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxPreprocessor.h
@@ -0,0 +1,536 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXPREPROCESSOR_H
+#define PXFOUNDATION_PXPREPROCESSOR_H
+
+#include <stddef.h>
+#if !defined(PX_GENERATE_META_DATA)
+#include <ciso646>
+#endif
+/** \addtogroup foundation
+ @{
+*/
+
+/*
+The following preprocessor identifiers specify compiler, OS, and architecture.
+All definitions have a value of 1 or 0, use '#if' instead of '#ifdef'.
+*/
+
+/**
+Compiler defines, see http://sourceforge.net/p/predef/wiki/Compilers/
+*/
+#if defined(_MSC_VER)
+#if _MSC_VER >= 1900
+#define PX_VC 14
+#elif _MSC_VER >= 1800
+#define PX_VC 12
+#elif _MSC_VER >= 1700
+#define PX_VC 11
+#elif _MSC_VER >= 1600
+#define PX_VC 10
+#elif _MSC_VER >= 1500
+#define PX_VC 9
+#else
+#error "Unknown VC version"
+#endif
+#elif defined(__clang__)
+#define PX_CLANG 1
+#elif defined(__GNUC__) // note: __clang__ implies __GNUC__
+#define PX_GCC 1
+#else
+#error "Unknown compiler"
+#endif
+
+/**
+Operating system defines, see http://sourceforge.net/p/predef/wiki/OperatingSystems/
+*/
+#if defined(_XBOX_ONE)
+#define PX_XBOXONE 1
+#elif defined(_WIN64) // note: _XBOX_ONE implies _WIN64
+#define PX_WIN64 1
+#elif defined(_WIN32) // note: _M_PPC implies _WIN32
+#define PX_WIN32 1
+#elif defined(__ANDROID__)
+#define PX_ANDROID 1
+#elif defined(__linux__) || defined (__EMSCRIPTEN__) // note: __ANDROID__ implies __linux__
+#define PX_LINUX 1
+#elif defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
+#define PX_IOS 1
+#elif defined(__APPLE__)
+#define PX_OSX 1
+#elif defined(__ORBIS__)
+#define PX_PS4 1
+#elif defined(__NX__)
+#define PX_NX 1
+#else
+#error "Unknown operating system"
+#endif
+
+/**
+Architecture defines, see http://sourceforge.net/p/predef/wiki/Architectures/
+*/
+#if defined(__x86_64__) || defined(_M_X64) // ps4 compiler defines _M_X64 without value
+#define PX_X64 1
+#elif defined(__i386__) || defined(_M_IX86) || defined (__EMSCRIPTEN__)
+#define PX_X86 1
+#elif defined(__arm64__) || defined(__aarch64__)
+#define PX_A64 1
+#elif defined(__arm__) || defined(_M_ARM)
+#define PX_ARM 1
+#elif defined(__ppc__) || defined(_M_PPC) || defined(__CELLOS_LV2__)
+#define PX_PPC 1
+#else
+#error "Unknown architecture"
+#endif
+
+/**
+SIMD defines
+*/
+#if !defined(PX_SIMD_DISABLED)
+#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) || (defined (__EMSCRIPTEN__) && defined(__SSE2__))
+#define PX_SSE2 1
+#endif
+#if defined(_M_ARM) || defined(__ARM_NEON__) || defined(__ARM_NEON)
+#define PX_NEON 1
+#endif
+#if defined(_M_PPC) || defined(__CELLOS_LV2__)
+#define PX_VMX 1
+#endif
+#endif
+
+/**
+define anything not defined on this platform to 0
+*/
+#ifndef PX_VC
+#define PX_VC 0
+#endif
+#ifndef PX_CLANG
+#define PX_CLANG 0
+#endif
+#ifndef PX_GCC
+#define PX_GCC 0
+#endif
+#ifndef PX_XBOXONE
+#define PX_XBOXONE 0
+#endif
+#ifndef PX_WIN64
+#define PX_WIN64 0
+#endif
+#ifndef PX_WIN32
+#define PX_WIN32 0
+#endif
+#ifndef PX_ANDROID
+#define PX_ANDROID 0
+#endif
+#ifndef PX_LINUX
+#define PX_LINUX 0
+#endif
+#ifndef PX_IOS
+#define PX_IOS 0
+#endif
+#ifndef PX_OSX
+#define PX_OSX 0
+#endif
+#ifndef PX_PS4
+#define PX_PS4 0
+#endif
+#ifndef PX_NX
+#define PX_NX 0
+#endif
+#ifndef PX_X64
+#define PX_X64 0
+#endif
+#ifndef PX_X86
+#define PX_X86 0
+#endif
+#ifndef PX_A64
+#define PX_A64 0
+#endif
+#ifndef PX_ARM
+#define PX_ARM 0
+#endif
+#ifndef PX_PPC
+#define PX_PPC 0
+#endif
+#ifndef PX_SSE2
+#define PX_SSE2 0
+#endif
+#ifndef PX_NEON
+#define PX_NEON 0
+#endif
+#ifndef PX_VMX
+#define PX_VMX 0
+#endif
+
+/*
+define anything not defined through the command line to 0
+*/
+#ifndef PX_DEBUG
+#define PX_DEBUG 0
+#endif
+#ifndef PX_CHECKED
+#define PX_CHECKED 0
+#endif
+#ifndef PX_PROFILE
+#define PX_PROFILE 0
+#endif
+#ifndef PX_NVTX
+#define PX_NVTX 0
+#endif
+#ifndef PX_DOXYGEN
+#define PX_DOXYGEN 0
+#endif
+
+/**
+family shortcuts
+*/
+// compiler
+#define PX_GCC_FAMILY (PX_CLANG || PX_GCC)
+// os
+#define PX_WINDOWS_FAMILY (PX_WIN32 || PX_WIN64)
+#define PX_MICROSOFT_FAMILY (PX_XBOXONE || PX_WINDOWS_FAMILY)
+#define PX_LINUX_FAMILY (PX_LINUX || PX_ANDROID)
+#define PX_APPLE_FAMILY (PX_IOS || PX_OSX) // equivalent to #if __APPLE__
+#define PX_UNIX_FAMILY (PX_LINUX_FAMILY || PX_APPLE_FAMILY) // shortcut for unix/posix platforms
+#if defined(__EMSCRIPTEN__)
+#define PX_EMSCRIPTEN 1
+#else
+#define PX_EMSCRIPTEN 0
+#endif
+// architecture
+#define PX_INTEL_FAMILY (PX_X64 || PX_X86)
+#define PX_ARM_FAMILY (PX_ARM || PX_A64)
+#define PX_P64_FAMILY (PX_X64 || PX_A64) // shortcut for 64-bit architectures
+
+/**
+C++ standard library defines
+*/
+#if defined(_LIBCPP_VERSION) || PX_WIN64 || PX_WIN32 || PX_PS4 || PX_XBOXONE || PX_EMSCRIPTEN
+#define PX_LIBCPP 1
+#else
+#define PX_LIBCPP 0
+#endif
+
+// legacy define for PhysX
+#define PX_WINDOWS (PX_WINDOWS_FAMILY && !PX_ARM_FAMILY)
+
+/**
+Assert macro
+*/
+#ifndef PX_ENABLE_ASSERTS
+#if PX_DEBUG && !defined(__CUDACC__)
+#define PX_ENABLE_ASSERTS 1
+#else
+#define PX_ENABLE_ASSERTS 0
+#endif
+#endif
+
+/**
+DLL export macros
+*/
+#ifndef PX_C_EXPORT
+#if PX_WINDOWS_FAMILY || PX_LINUX
+#define PX_C_EXPORT extern "C"
+#else
+#define PX_C_EXPORT
+#endif
+#endif
+
+#if PX_UNIX_FAMILY&& __GNUC__ >= 4
+#define PX_UNIX_EXPORT __attribute__((visibility("default")))
+#else
+#define PX_UNIX_EXPORT
+#endif
+
+#if PX_WINDOWS_FAMILY
+#define PX_DLL_EXPORT __declspec(dllexport)
+#define PX_DLL_IMPORT __declspec(dllimport)
+#else
+#define PX_DLL_EXPORT PX_UNIX_EXPORT
+#define PX_DLL_IMPORT
+#endif
+
+/**
+Define API function declaration
+
+PX_FOUNDATION_DLL=1 - used by the DLL library (PhysXCommon) to export the API
+PX_FOUNDATION_DLL=0 - for windows configurations where the PX_FOUNDATION_API is linked through standard static linking
+no definition - this will allow DLLs and libraries to use the exported API from PhysXCommon
+
+*/
+
+#if PX_WINDOWS_FAMILY && !PX_ARM_FAMILY
+#ifndef PX_FOUNDATION_DLL
+#define PX_FOUNDATION_API PX_DLL_IMPORT
+#elif PX_FOUNDATION_DLL
+#define PX_FOUNDATION_API PX_DLL_EXPORT
+#endif
+#elif PX_UNIX_FAMILY
+#ifdef PX_FOUNDATION_DLL
+#define PX_FOUNDATION_API PX_UNIX_EXPORT
+#endif
+#endif
+
+#ifndef PX_FOUNDATION_API
+#define PX_FOUNDATION_API
+#endif
+
+/**
+Calling convention
+*/
+#ifndef PX_CALL_CONV
+#if PX_MICROSOFT_FAMILY
+#define PX_CALL_CONV __cdecl
+#else
+#define PX_CALL_CONV
+#endif
+#endif
+
+/**
+Pack macros - disabled on SPU because they are not supported
+*/
+#if PX_VC
+#define PX_PUSH_PACK_DEFAULT __pragma(pack(push, 8))
+#define PX_POP_PACK __pragma(pack(pop))
+#elif PX_GCC_FAMILY
+#define PX_PUSH_PACK_DEFAULT _Pragma("pack(push, 8)")
+#define PX_POP_PACK _Pragma("pack(pop)")
+#else
+#define PX_PUSH_PACK_DEFAULT
+#define PX_POP_PACK
+#endif
+
+/**
+Inline macro
+*/
+#define PX_INLINE inline
+#if PX_MICROSOFT_FAMILY
+#pragma inline_depth(255)
+#endif
+
+/**
+Force inline macro
+*/
+#if PX_VC
+#define PX_FORCE_INLINE __forceinline
+#elif PX_LINUX // Workaround; Fedora Core 3 do not agree with force inline and PxcPool
+#define PX_FORCE_INLINE inline
+#elif PX_GCC_FAMILY
+#define PX_FORCE_INLINE inline __attribute__((always_inline))
+#else
+#define PX_FORCE_INLINE inline
+#endif
+
+/**
+Noinline macro
+*/
+#if PX_MICROSOFT_FAMILY
+#define PX_NOINLINE __declspec(noinline)
+#elif PX_GCC_FAMILY
+#define PX_NOINLINE __attribute__((noinline))
+#else
+#define PX_NOINLINE
+#endif
+
+/**
+Restrict macro
+*/
+#if defined(__CUDACC__)
+#define PX_RESTRICT __restrict__
+#else
+#define PX_RESTRICT __restrict
+#endif
+
+/**
+Noalias macro
+*/
+#if PX_MICROSOFT_FAMILY
+#define PX_NOALIAS __declspec(noalias)
+#else
+#define PX_NOALIAS
+#endif
+
+/**
+Alignment macros
+
+PX_ALIGN_PREFIX and PX_ALIGN_SUFFIX can be used for type alignment instead of aligning individual variables as follows:
+PX_ALIGN_PREFIX(16)
+struct A {
+...
+} PX_ALIGN_SUFFIX(16);
+This declaration style is parsed correctly by Visual Assist.
+
+*/
+#ifndef PX_ALIGN
+#if PX_MICROSOFT_FAMILY
+#define PX_ALIGN(alignment, decl) __declspec(align(alignment)) decl
+#define PX_ALIGN_PREFIX(alignment) __declspec(align(alignment))
+#define PX_ALIGN_SUFFIX(alignment)
+#elif PX_GCC_FAMILY
+#define PX_ALIGN(alignment, decl) decl __attribute__((aligned(alignment)))
+#define PX_ALIGN_PREFIX(alignment)
+#define PX_ALIGN_SUFFIX(alignment) __attribute__((aligned(alignment)))
+#elif defined __CUDACC__
+#define PX_ALIGN(alignment, decl) __align__(alignment) decl
+#define PX_ALIGN_PREFIX(alignment)
+#define PX_ALIGN_SUFFIX(alignment) __align__(alignment))
+#else
+#define PX_ALIGN(alignment, decl)
+#define PX_ALIGN_PREFIX(alignment)
+#define PX_ALIGN_SUFFIX(alignment)
+#endif
+#endif
+
+/**
+Deprecated macro
+- To deprecate a function: Place PX_DEPRECATED at the start of the function header (leftmost word).
+- To deprecate a 'typedef', a 'struct' or a 'class': Place PX_DEPRECATED directly after the keywords ('typdef',
+'struct', 'class').
+
+Use these macro definitions to create warnings for deprecated functions
+\#define PX_DEPRECATED __declspec(deprecated) // Microsoft
+\#define PX_DEPRECATED __attribute__((deprecated())) // GCC
+*/
+#define PX_DEPRECATED
+
+/**
+General defines
+*/
+
+// static assert
+#if(defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))) || (PX_PS4) || (PX_APPLE_FAMILY) || (PX_NX)
+#define PX_COMPILE_TIME_ASSERT(exp) typedef char PxCompileTimeAssert_Dummy[(exp) ? 1 : -1] __attribute__((unused))
+#else
+#define PX_COMPILE_TIME_ASSERT(exp) typedef char PxCompileTimeAssert_Dummy[(exp) ? 1 : -1]
+#endif
+
+#if PX_GCC_FAMILY
+#define PX_OFFSET_OF(X, Y) __builtin_offsetof(X, Y)
+#else
+#define PX_OFFSET_OF(X, Y) offsetof(X, Y)
+#endif
+
+#define PX_OFFSETOF_BASE 0x100 // casting the null ptr takes a special-case code path, which we don't want
+#define PX_OFFSET_OF_RT(Class, Member) \
+ (reinterpret_cast<size_t>(&reinterpret_cast<Class*>(PX_OFFSETOF_BASE)->Member) - size_t(PX_OFFSETOF_BASE))
+
+// check that exactly one of NDEBUG and _DEBUG is defined
+#if !defined(NDEBUG) ^ defined(_DEBUG)
+#error Exactly one of NDEBUG and _DEBUG needs to be defined!
+#endif
+
+// make sure PX_CHECKED is defined in all _DEBUG configurations as well
+#if !PX_CHECKED && PX_DEBUG
+#error PX_CHECKED must be defined when PX_DEBUG is defined
+#endif
+
+#ifdef __CUDACC__
+#define PX_CUDA_CALLABLE __host__ __device__
+#else
+#define PX_CUDA_CALLABLE
+#endif
+
+// avoid unreferenced parameter warning
+// preferred solution: omit the parameter's name from the declaration
+template <class T>
+PX_CUDA_CALLABLE PX_INLINE void PX_UNUSED(T const&)
+{
+}
+
+// Ensure that the application hasn't tweaked the pack value to less than 8, which would break
+// matching between the API headers and the binaries
+// This assert works on win32/win64, but may need further specialization on other platforms.
+// Some GCC compilers need the compiler flag -malign-double to be set.
+// Apparently the apple-clang-llvm compiler doesn't support malign-double.
+#if PX_PS4 || PX_APPLE_FAMILY
+struct PxPackValidation
+{
+ char _;
+ long a;
+};
+#elif PX_ANDROID
+struct PxPackValidation
+{
+ char _;
+ double a;
+};
+#else
+struct PxPackValidation
+{
+ char _;
+ long long a;
+};
+#endif
+#if !PX_APPLE_FAMILY
+PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxPackValidation, a) == 8);
+#endif
+
+// use in a cpp file to suppress LNK4221
+#if PX_VC
+#define PX_DUMMY_SYMBOL \
+ namespace \
+ { \
+ char PxDummySymbol; \
+ }
+#else
+#define PX_DUMMY_SYMBOL
+#endif
+
+#if PX_GCC_FAMILY
+#define PX_WEAK_SYMBOL __attribute__((weak)) // this is to support SIMD constant merging in template specialization
+#else
+#define PX_WEAK_SYMBOL
+#endif
+
+// Macro for avoiding default assignment and copy, because doing this by inheritance can increase class size on some
+// platforms.
+#define PX_NOCOPY(Class) \
+ \
+protected: \
+ Class(const Class&); \
+ Class& operator=(const Class&);
+
+#define PX_STRINGIZE_HELPER(X) #X
+#define PX_STRINGIZE(X) PX_STRINGIZE_HELPER(X)
+
+#define PX_CONCAT_HELPER(X, Y) X##Y
+#define PX_CONCAT(X, Y) PX_CONCAT_HELPER(X, Y)
+
+#ifndef DISABLE_CUDA_PHYSX
+//CUDA is currently supported only on windows
+#define PX_SUPPORT_GPU_PHYSX ((PX_WINDOWS_FAMILY) || (PX_LINUX && PX_X64))
+#else
+#define PX_SUPPORT_GPU_PHYSX 0
+#endif
+
+#define PX_SUPPORT_COMPUTE_PHYSX 0
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXPREPROCESSOR_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxProfiler.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxProfiler.h
new file mode 100644
index 0000000..4864969
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxProfiler.h
@@ -0,0 +1,116 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+
+#ifndef PXFOUNDATION_PXPROFILER_H
+#define PXFOUNDATION_PXPROFILER_H
+
+#include "foundation/PxFoundation.h"
+
+namespace physx
+{
+
+/**
+\brief The pure virtual callback interface for general purpose instrumentation and profiling of GameWorks modules as
+well as applications
+*/
+class PxProfilerCallback
+{
+protected:
+ virtual ~PxProfilerCallback() {}
+
+public:
+ /**************************************************************************************************************************
+ Instrumented profiling events
+ ***************************************************************************************************************************/
+
+ /**
+ \brief Mark the beginning of a nested profile block
+ \param[in] eventName Event name. Must be a persistent const char *
+ \param[in] detached True for cross thread events
+ \param[in] contextId the context id of this zone. Zones with the same id belong to the same group. 0 is used for no specific group.
+ \return Returns implementation-specific profiler data for this event
+ */
+ virtual void* zoneStart(const char* eventName, bool detached, uint64_t contextId) = 0;
+
+ /**
+ \brief Mark the end of a nested profile block
+ \param[in] profilerData The data returned by the corresponding zoneStart call (or NULL if not available)
+ \param[in] eventName The name of the zone ending, must match the corresponding name passed with 'zoneStart'. Must be a persistent const char *.
+ \param[in] detached True for cross thread events. Should match the value passed to zoneStart.
+ \param[in] contextId The context of this zone. Should match the value passed to zoneStart.
+
+ \note eventName plus contextId can be used to uniquely match up start and end of a zone.
+ */
+ virtual void zoneEnd(void* profilerData, const char* eventName, bool detached, uint64_t contextId) = 0;
+};
+
+class PxProfileScoped
+{
+ public:
+ PX_FORCE_INLINE PxProfileScoped(const char* eventName, bool detached, uint64_t contextId) : mCallback(PxGetProfilerCallback()), mProfilerData(NULL)
+ {
+ if(mCallback)
+ {
+ mEventName = eventName;
+ mContextId = contextId;
+ mDetached = detached;
+ mProfilerData = mCallback->zoneStart(eventName, detached, contextId);
+ }
+ }
+
+ PX_FORCE_INLINE ~PxProfileScoped()
+ {
+ if(mCallback)
+ mCallback->zoneEnd(mProfilerData, mEventName, mDetached, mContextId);
+ }
+ physx::PxProfilerCallback* mCallback;
+ const char* mEventName;
+ void* mProfilerData;
+ uint64_t mContextId;
+ bool mDetached;
+};
+
+} // end of physx namespace
+
+#if PX_DEBUG || PX_CHECKED || PX_PROFILE
+ #define PX_PROFILE_ZONE(x, y) \
+ physx::PxProfileScoped PX_CONCAT(_scoped, __LINE__)(x, false, y)
+ #define PX_PROFILE_START_CROSSTHREAD(x, y) \
+ if(PxGetProfilerCallback()) \
+ PxGetProfilerCallback()->zoneStart(x, true, y)
+ #define PX_PROFILE_STOP_CROSSTHREAD(x, y) \
+ if(PxGetProfilerCallback()) \
+ PxGetProfilerCallback()->zoneEnd(NULL, x, true, y)
+#else
+ #define PX_PROFILE_ZONE(x, y)
+ #define PX_PROFILE_START_CROSSTHREAD(x, y)
+ #define PX_PROFILE_STOP_CROSSTHREAD(x, y)
+#endif
+
+#define PX_PROFILE_POINTER_TO_U64(pointer) static_cast<uint64_t>(reinterpret_cast<size_t>(pointer))
+
+#endif // PXFOUNDATION_PXPROFILER_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxQuat.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxQuat.h
new file mode 100644
index 0000000..1313b0e
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxQuat.h
@@ -0,0 +1,403 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXQUAT_H
+#define PXFOUNDATION_PXQUAT_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxVec3.h"
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief This is a quaternion class. For more information on quaternion mathematics
+consult a mathematics source on complex numbers.
+
+*/
+
+class PxQuat
+{
+ public:
+ /**
+ \brief Default constructor, does not do any initialization.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat()
+ {
+ }
+
+ //! identity constructor
+ PX_CUDA_CALLABLE PX_INLINE PxQuat(PxIDENTITY r) : x(0.0f), y(0.0f), z(0.0f), w(1.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ /**
+ \brief Constructor from a scalar: sets the real part w to the scalar value, and the imaginary parts (x,y,z) to zero
+ */
+ explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat(float r) : x(0.0f), y(0.0f), z(0.0f), w(r)
+ {
+ }
+
+ /**
+ \brief Constructor. Take note of the order of the elements!
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat(float nx, float ny, float nz, float nw) : x(nx), y(ny), z(nz), w(nw)
+ {
+ }
+
+ /**
+ \brief Creates from angle-axis representation.
+
+ Axis must be normalized!
+
+ Angle is in radians!
+
+ <b>Unit:</b> Radians
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxQuat(float angleRadians, const PxVec3& unitAxis)
+ {
+ PX_ASSERT(PxAbs(1.0f - unitAxis.magnitude()) < 1e-3f);
+ const float a = angleRadians * 0.5f;
+ const float s = PxSin(a);
+ w = PxCos(a);
+ x = unitAxis.x * s;
+ y = unitAxis.y * s;
+ z = unitAxis.z * s;
+ }
+
+ /**
+ \brief Copy ctor.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat(const PxQuat& v) : x(v.x), y(v.y), z(v.z), w(v.w)
+ {
+ }
+
+ /**
+ \brief Creates from orientation matrix.
+
+ \param[in] m Rotation matrix to extract quaternion from.
+ */
+ PX_CUDA_CALLABLE PX_INLINE explicit PxQuat(const PxMat33& m); /* defined in PxMat33.h */
+
+ /**
+ \brief returns true if quat is identity
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isIdentity() const
+ {
+ return x==0.0f && y==0.0f && z==0.0f && w==1.0f;
+ }
+
+ /**
+ \brief returns true if all elements are finite (not NAN or INF, etc.)
+ */
+ PX_CUDA_CALLABLE bool isFinite() const
+ {
+ return PxIsFinite(x) && PxIsFinite(y) && PxIsFinite(z) && PxIsFinite(w);
+ }
+
+ /**
+ \brief returns true if finite and magnitude is close to unit
+ */
+ PX_CUDA_CALLABLE bool isUnit() const
+ {
+ const float unitTolerance = 1e-4f;
+ return isFinite() && PxAbs(magnitude() - 1) < unitTolerance;
+ }
+
+ /**
+ \brief returns true if finite and magnitude is reasonably close to unit to allow for some accumulation of error vs
+ isValid
+ */
+ PX_CUDA_CALLABLE bool isSane() const
+ {
+ const float unitTolerance = 1e-2f;
+ return isFinite() && PxAbs(magnitude() - 1) < unitTolerance;
+ }
+
+ /**
+ \brief returns true if the two quaternions are exactly equal
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxQuat& q) const
+ {
+ return x == q.x && y == q.y && z == q.z && w == q.w;
+ }
+
+ /**
+ \brief converts this quaternion to angle-axis representation
+ */
+ PX_CUDA_CALLABLE PX_INLINE void toRadiansAndUnitAxis(float& angle, PxVec3& axis) const
+ {
+ const float quatEpsilon = 1.0e-8f;
+ const float s2 = x * x + y * y + z * z;
+ if(s2 < quatEpsilon * quatEpsilon) // can't extract a sensible axis
+ {
+ angle = 0.0f;
+ axis = PxVec3(1.0f, 0.0f, 0.0f);
+ }
+ else
+ {
+ const float s = PxRecipSqrt(s2);
+ axis = PxVec3(x, y, z) * s;
+ angle = PxAbs(w) < quatEpsilon ? PxPi : PxAtan2(s2 * s, w) * 2.0f;
+ }
+ }
+
+ /**
+ \brief Gets the angle between this quat and the identity quaternion.
+
+ <b>Unit:</b> Radians
+ */
+ PX_CUDA_CALLABLE PX_INLINE float getAngle() const
+ {
+ return PxAcos(w) * 2.0f;
+ }
+
+ /**
+ \brief Gets the angle between this quat and the argument
+
+ <b>Unit:</b> Radians
+ */
+ PX_CUDA_CALLABLE PX_INLINE float getAngle(const PxQuat& q) const
+ {
+ return PxAcos(dot(q)) * 2.0f;
+ }
+
+ /**
+ \brief This is the squared 4D vector length, should be 1 for unit quaternions.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float magnitudeSquared() const
+ {
+ return x * x + y * y + z * z + w * w;
+ }
+
+ /**
+ \brief returns the scalar product of this and other.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float dot(const PxQuat& v) const
+ {
+ return x * v.x + y * v.y + z * v.z + w * v.w;
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE PxQuat getNormalized() const
+ {
+ const float s = 1.0f / magnitude();
+ return PxQuat(x * s, y * s, z * s, w * s);
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE float magnitude() const
+ {
+ return PxSqrt(magnitudeSquared());
+ }
+
+ // modifiers:
+ /**
+ \brief maps to the closest unit quaternion.
+ */
+ PX_CUDA_CALLABLE PX_INLINE float normalize() // convert this PxQuat to a unit quaternion
+ {
+ const float mag = magnitude();
+ if(mag != 0.0f)
+ {
+ const float imag = 1.0f / mag;
+
+ x *= imag;
+ y *= imag;
+ z *= imag;
+ w *= imag;
+ }
+ return mag;
+ }
+
+ /*
+ \brief returns the conjugate.
+
+ \note for unit quaternions, this is the inverse.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxQuat getConjugate() const
+ {
+ return PxQuat(-x, -y, -z, w);
+ }
+
+ /*
+ \brief returns imaginary part.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec3 getImaginaryPart() const
+ {
+ return PxVec3(x, y, z);
+ }
+
+ /** brief computes rotation of x-axis */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getBasisVector0() const
+ {
+ const float x2 = x * 2.0f;
+ const float w2 = w * 2.0f;
+ return PxVec3((w * w2) - 1.0f + x * x2, (z * w2) + y * x2, (-y * w2) + z * x2);
+ }
+
+ /** brief computes rotation of y-axis */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getBasisVector1() const
+ {
+ const float y2 = y * 2.0f;
+ const float w2 = w * 2.0f;
+ return PxVec3((-z * w2) + x * y2, (w * w2) - 1.0f + y * y2, (x * w2) + z * y2);
+ }
+
+ /** brief computes rotation of z-axis */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getBasisVector2() const
+ {
+ const float z2 = z * 2.0f;
+ const float w2 = w * 2.0f;
+ return PxVec3((y * w2) + x * z2, (-x * w2) + y * z2, (w * w2) - 1.0f + z * z2);
+ }
+
+ /**
+ rotates passed vec by this (assumed unitary)
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3 rotate(const PxVec3& v) const
+ {
+ const float vx = 2.0f * v.x;
+ const float vy = 2.0f * v.y;
+ const float vz = 2.0f * v.z;
+ const float w2 = w * w - 0.5f;
+ const float dot2 = (x * vx + y * vy + z * vz);
+ return PxVec3((vx * w2 + (y * vz - z * vy) * w + x * dot2), (vy * w2 + (z * vx - x * vz) * w + y * dot2),
+ (vz * w2 + (x * vy - y * vx) * w + z * dot2));
+ }
+
+ /**
+ inverse rotates passed vec by this (assumed unitary)
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3 rotateInv(const PxVec3& v) const
+ {
+ const float vx = 2.0f * v.x;
+ const float vy = 2.0f * v.y;
+ const float vz = 2.0f * v.z;
+ const float w2 = w * w - 0.5f;
+ const float dot2 = (x * vx + y * vy + z * vz);
+ return PxVec3((vx * w2 - (y * vz - z * vy) * w + x * dot2), (vy * w2 - (z * vx - x * vz) * w + y * dot2),
+ (vz * w2 - (x * vy - y * vx) * w + z * dot2));
+ }
+
+ /**
+ \brief Assignment operator
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat& operator=(const PxQuat& p)
+ {
+ x = p.x;
+ y = p.y;
+ z = p.z;
+ w = p.w;
+ return *this;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat& operator*=(const PxQuat& q)
+ {
+ const float tx = w * q.x + q.w * x + y * q.z - q.y * z;
+ const float ty = w * q.y + q.w * y + z * q.x - q.z * x;
+ const float tz = w * q.z + q.w * z + x * q.y - q.x * y;
+
+ w = w * q.w - q.x * x - y * q.y - q.z * z;
+ x = tx;
+ y = ty;
+ z = tz;
+
+ return *this;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat& operator+=(const PxQuat& q)
+ {
+ x += q.x;
+ y += q.y;
+ z += q.z;
+ w += q.w;
+ return *this;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat& operator-=(const PxQuat& q)
+ {
+ x -= q.x;
+ y -= q.y;
+ z -= q.z;
+ w -= q.w;
+ return *this;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat& operator*=(const float s)
+ {
+ x *= s;
+ y *= s;
+ z *= s;
+ w *= s;
+ return *this;
+ }
+
+ /** quaternion multiplication */
+ PX_CUDA_CALLABLE PX_INLINE PxQuat operator*(const PxQuat& q) const
+ {
+ return PxQuat(w * q.x + q.w * x + y * q.z - q.y * z, w * q.y + q.w * y + z * q.x - q.z * x,
+ w * q.z + q.w * z + x * q.y - q.x * y, w * q.w - x * q.x - y * q.y - z * q.z);
+ }
+
+ /** quaternion addition */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat operator+(const PxQuat& q) const
+ {
+ return PxQuat(x + q.x, y + q.y, z + q.z, w + q.w);
+ }
+
+ /** quaternion subtraction */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat operator-() const
+ {
+ return PxQuat(-x, -y, -z, -w);
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat operator-(const PxQuat& q) const
+ {
+ return PxQuat(x - q.x, y - q.y, z - q.z, w - q.w);
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxQuat operator*(float r) const
+ {
+ return PxQuat(x * r, y * r, z * r, w * r);
+ }
+
+ /** the quaternion elements */
+ float x, y, z, w;
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXQUAT_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxSimpleTypes.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxSimpleTypes.h
new file mode 100644
index 0000000..6ecba13
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxSimpleTypes.h
@@ -0,0 +1,112 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXSIMPLETYPES_H
+#define PXFOUNDATION_PXSIMPLETYPES_H
+
+/** \addtogroup foundation
+ @{
+*/
+
+// Platform specific types:
+// Design note: Its OK to use int for general loop variables and temps.
+
+#include "foundation/PxPreprocessor.h"
+#if PX_VC
+#pragma warning(push)
+#pragma warning(disable : 4668) // suppressing warning generated by Microsoft Visual Studio when including this standard
+// header
+#endif
+
+#if PX_LINUX
+#define __STDC_LIMIT_MACROS
+#endif
+
+#include <stdint.h>
+#if PX_VC
+#pragma warning(pop)
+#endif
+
+#if PX_VC // we could use inttypes.h starting with VC12
+#define PX_PRIu64 "I64u"
+#else
+#if !PX_PS4 && !PX_APPLE_FAMILY
+#define __STDC_FORMAT_MACROS
+#endif
+#include <inttypes.h>
+#define PX_PRIu64 PRIu64
+#endif
+
+namespace physx
+{
+typedef int64_t PxI64;
+typedef uint64_t PxU64;
+typedef int32_t PxI32;
+typedef uint32_t PxU32;
+typedef int16_t PxI16;
+typedef uint16_t PxU16;
+typedef int8_t PxI8;
+typedef uint8_t PxU8;
+typedef float PxF32;
+typedef double PxF64;
+typedef float PxReal;
+}
+
+// Type ranges
+
+// These are here because we sometimes have non-IEEE compliant platforms to deal with.
+// Removal is under consideration (issue GWSD-34)
+
+#define PX_MAX_F32 3.4028234663852885981170418348452e+38F
+// maximum possible float value
+#define PX_MAX_F64 DBL_MAX // maximum possible double value
+
+#define PX_EPS_F32 FLT_EPSILON // maximum relative error of float rounding
+#define PX_EPS_F64 DBL_EPSILON // maximum relative error of double rounding
+
+#define PX_MAX_REAL PX_MAX_F32
+#define PX_EPS_REAL PX_EPS_F32
+#define PX_NORMALIZATION_EPSILON float(1e-20f)
+
+// Legacy type ranges used by PhysX
+#define PX_MAX_I8 INT8_MAX
+#define PX_MIN_I8 INT8_MIN
+#define PX_MAX_U8 UINT8_MAX
+#define PX_MIN_U8 UINT8_MIN
+#define PX_MAX_I16 INT16_MAX
+#define PX_MIN_I16 INT16_MIN
+#define PX_MAX_U16 UINT16_MAX
+#define PX_MIN_U16 UINT16_MIN
+#define PX_MAX_I32 INT32_MAX
+#define PX_MIN_I32 INT32_MIN
+#define PX_MAX_U32 UINT32_MAX
+#define PX_MIN_U32 UINT32_MIN
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXSIMPLETYPES_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxStrideIterator.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxStrideIterator.h
new file mode 100644
index 0000000..1e4c448
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxStrideIterator.h
@@ -0,0 +1,353 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXSTRIDEITERATOR_H
+#define PXFOUNDATION_PXSTRIDEITERATOR_H
+
+#include "foundation/Px.h"
+#include "foundation/PxAssert.h"
+
+/** \addtogroup foundation
+ @{
+*/
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief Iterator class for iterating over arrays of data that may be interleaved with other data.
+
+This class is used for iterating over arrays of elements that may have a larger element to element
+offset, called the stride, than the size of the element itself (non-contiguous).
+
+The template parameter T denotes the type of the element accessed. The stride itself
+is stored as a member field so multiple instances of a PxStrideIterator class can have
+different strides. This is useful for cases were the stride depends on runtime configuration.
+
+The stride iterator can be used for index based access, e.g.:
+\code
+ PxStrideIterator<PxVec3> strideArray(...);
+ for (unsigned i = 0; i < 10; ++i)
+ {
+ PxVec3& vec = strideArray[i];
+ ...
+ }
+\endcode
+or iteration by increment, e.g.:
+\code
+ PxStrideIterator<PxVec3> strideBegin(...);
+ PxStrideIterator<PxVec3> strideEnd(strideBegin + 10);
+ for (PxStrideIterator<PxVec3> it = strideBegin; it < strideEnd; ++it)
+ {
+ PxVec3& vec = *it;
+ ...
+ }
+\endcode
+
+Two special cases:
+- A stride of sizeof(T) represents a regular c array of type T.
+- A stride of 0 can be used to describe re-occurrence of the same element multiple times.
+
+*/
+template <typename T>
+class PxStrideIterator
+{
+
+#if !PX_DOXYGEN
+ template <typename X>
+ struct StripConst
+ {
+ typedef X Type;
+ };
+
+ template <typename X>
+ struct StripConst<const X>
+ {
+ typedef X Type;
+ };
+#endif
+
+ public:
+ /**
+ \brief Constructor.
+
+ Optionally takes a pointer to an element and a stride.
+
+ \param[in] ptr pointer to element, defaults to NULL.
+ \param[in] stride stride for accessing consecutive elements, defaults to the size of one element.
+ */
+ explicit PX_INLINE PxStrideIterator(T* ptr = NULL, PxU32 stride = sizeof(T)) : mPtr(ptr), mStride(stride)
+ {
+ PX_ASSERT(mStride == 0 || sizeof(T) <= mStride);
+ }
+
+ /**
+ \brief Copy constructor.
+
+ \param[in] strideIterator PxStrideIterator to be copied.
+ */
+ PX_INLINE PxStrideIterator(const PxStrideIterator<typename StripConst<T>::Type>& strideIterator)
+ : mPtr(strideIterator.ptr()), mStride(strideIterator.stride())
+ {
+ PX_ASSERT(mStride == 0 || sizeof(T) <= mStride);
+ }
+
+ /**
+ \brief Get pointer to element.
+ */
+ PX_INLINE T* ptr() const
+ {
+ return mPtr;
+ }
+
+ /**
+ \brief Get stride.
+ */
+ PX_INLINE PxU32 stride() const
+ {
+ return mStride;
+ }
+
+ /**
+ \brief Indirection operator.
+ */
+ PX_INLINE T& operator*() const
+ {
+ return *mPtr;
+ }
+
+ /**
+ \brief Dereferencing operator.
+ */
+ PX_INLINE T* operator->() const
+ {
+ return mPtr;
+ }
+
+ /**
+ \brief Indexing operator.
+ */
+ PX_INLINE T& operator[](unsigned int i) const
+ {
+ return *byteAdd(mPtr, i * stride());
+ }
+
+ /**
+ \brief Pre-increment operator.
+ */
+ PX_INLINE PxStrideIterator& operator++()
+ {
+ mPtr = byteAdd(mPtr, stride());
+ return *this;
+ }
+
+ /**
+ \brief Post-increment operator.
+ */
+ PX_INLINE PxStrideIterator operator++(int)
+ {
+ PxStrideIterator tmp = *this;
+ mPtr = byteAdd(mPtr, stride());
+ return tmp;
+ }
+
+ /**
+ \brief Pre-decrement operator.
+ */
+ PX_INLINE PxStrideIterator& operator--()
+ {
+ mPtr = byteSub(mPtr, stride());
+ return *this;
+ }
+
+ /**
+ \brief Post-decrement operator.
+ */
+ PX_INLINE PxStrideIterator operator--(int)
+ {
+ PxStrideIterator tmp = *this;
+ mPtr = byteSub(mPtr, stride());
+ return tmp;
+ }
+
+ /**
+ \brief Addition operator.
+ */
+ PX_INLINE PxStrideIterator operator+(unsigned int i) const
+ {
+ return PxStrideIterator(byteAdd(mPtr, i * stride()), stride());
+ }
+
+ /**
+ \brief Subtraction operator.
+ */
+ PX_INLINE PxStrideIterator operator-(unsigned int i) const
+ {
+ return PxStrideIterator(byteSub(mPtr, i * stride()), stride());
+ }
+
+ /**
+ \brief Addition compound assignment operator.
+ */
+ PX_INLINE PxStrideIterator& operator+=(unsigned int i)
+ {
+ mPtr = byteAdd(mPtr, i * stride());
+ return *this;
+ }
+
+ /**
+ \brief Subtraction compound assignment operator.
+ */
+ PX_INLINE PxStrideIterator& operator-=(unsigned int i)
+ {
+ mPtr = byteSub(mPtr, i * stride());
+ return *this;
+ }
+
+ /**
+ \brief Iterator difference.
+ */
+ PX_INLINE int operator-(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ int byteDiff = static_cast<int>(reinterpret_cast<const PxU8*>(mPtr) - reinterpret_cast<const PxU8*>(other.mPtr));
+ return byteDiff / static_cast<int>(stride());
+ }
+
+ /**
+ \brief Equality operator.
+ */
+ PX_INLINE bool operator==(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ return mPtr == other.mPtr;
+ }
+
+ /**
+ \brief Inequality operator.
+ */
+ PX_INLINE bool operator!=(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ return mPtr != other.mPtr;
+ }
+
+ /**
+ \brief Less than operator.
+ */
+ PX_INLINE bool operator<(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ return mPtr < other.mPtr;
+ }
+
+ /**
+ \brief Greater than operator.
+ */
+ PX_INLINE bool operator>(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ return mPtr > other.mPtr;
+ }
+
+ /**
+ \brief Less or equal than operator.
+ */
+ PX_INLINE bool operator<=(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ return mPtr <= other.mPtr;
+ }
+
+ /**
+ \brief Greater or equal than operator.
+ */
+ PX_INLINE bool operator>=(const PxStrideIterator& other) const
+ {
+ PX_ASSERT(isCompatible(other));
+ return mPtr >= other.mPtr;
+ }
+
+ private:
+ PX_INLINE static T* byteAdd(T* ptr, PxU32 bytes)
+ {
+ return const_cast<T*>(reinterpret_cast<const T*>(reinterpret_cast<const PxU8*>(ptr) + bytes));
+ }
+
+ PX_INLINE static T* byteSub(T* ptr, PxU32 bytes)
+ {
+ return const_cast<T*>(reinterpret_cast<const T*>(reinterpret_cast<const PxU8*>(ptr) - bytes));
+ }
+
+ PX_INLINE bool isCompatible(const PxStrideIterator& other) const
+ {
+ int byteDiff = static_cast<int>(reinterpret_cast<const PxU8*>(mPtr) - reinterpret_cast<const PxU8*>(other.mPtr));
+ return (stride() == other.stride()) && (abs(byteDiff) % stride() == 0);
+ }
+
+ T* mPtr;
+ PxU32 mStride;
+};
+
+/**
+\brief Addition operator.
+*/
+template <typename T>
+PX_INLINE PxStrideIterator<T> operator+(int i, PxStrideIterator<T> it)
+{
+ it += i;
+ return it;
+}
+
+/**
+\brief Stride iterator factory function which infers the iterator type.
+*/
+template <typename T>
+PX_INLINE PxStrideIterator<T> PxMakeIterator(T* ptr, PxU32 stride = sizeof(T))
+{
+ return PxStrideIterator<T>(ptr, stride);
+}
+
+/**
+\brief Stride iterator factory function which infers the iterator type.
+*/
+template <typename T>
+PX_INLINE PxStrideIterator<const T> PxMakeIterator(const T* ptr, PxU32 stride = sizeof(T))
+{
+ return PxStrideIterator<const T>(ptr, stride);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // PXFOUNDATION_PXSTRIDEITERATOR_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxTransform.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxTransform.h
new file mode 100644
index 0000000..ddba031
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxTransform.h
@@ -0,0 +1,215 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXTRANSFORM_H
+#define PXFOUNDATION_PXTRANSFORM_H
+/** \addtogroup foundation
+ @{
+*/
+
+#include "foundation/PxQuat.h"
+#include "foundation/PxPlane.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/*!
+\brief class representing a rigid euclidean transform as a quaternion and a vector
+*/
+
+class PxTransform
+{
+ public:
+ PxQuat q;
+ PxVec3 p;
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform()
+ {
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransform(const PxVec3& position) : q(PxIdentity), p(position)
+ {
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransform(PxIDENTITY r) : q(PxIdentity), p(PxZero)
+ {
+ PX_UNUSED(r);
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransform(const PxQuat& orientation) : q(orientation), p(0)
+ {
+ PX_ASSERT(orientation.isSane());
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform(float x, float y, float z, PxQuat aQ = PxQuat(PxIdentity))
+ : q(aQ), p(x, y, z)
+ {
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform(const PxVec3& p0, const PxQuat& q0) : q(q0), p(p0)
+ {
+ PX_ASSERT(q0.isSane());
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE explicit PxTransform(const PxMat44& m); // defined in PxMat44.h
+
+ /**
+ \brief returns true if the two transforms are exactly equal
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxTransform& t) const
+ {
+ return p == t.p && q == t.q;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform operator*(const PxTransform& x) const
+ {
+ PX_ASSERT(x.isSane());
+ return transform(x);
+ }
+
+ //! Equals matrix multiplication
+ PX_CUDA_CALLABLE PX_INLINE PxTransform& operator*=(PxTransform& other)
+ {
+ *this = *this * other;
+ return *this;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform getInverse() const
+ {
+ PX_ASSERT(isFinite());
+ return PxTransform(q.rotateInv(-p), q.getConjugate());
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 transform(const PxVec3& input) const
+ {
+ PX_ASSERT(isFinite());
+ return q.rotate(input) + p;
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 transformInv(const PxVec3& input) const
+ {
+ PX_ASSERT(isFinite());
+ return q.rotateInv(input - p);
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 rotate(const PxVec3& input) const
+ {
+ PX_ASSERT(isFinite());
+ return q.rotate(input);
+ }
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 rotateInv(const PxVec3& input) const
+ {
+ PX_ASSERT(isFinite());
+ return q.rotateInv(input);
+ }
+
+ //! Transform transform to parent (returns compound transform: first src, then *this)
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform transform(const PxTransform& src) const
+ {
+ PX_ASSERT(src.isSane());
+ PX_ASSERT(isSane());
+ // src = [srct, srcr] -> [r*srct + t, r*srcr]
+ return PxTransform(q.rotate(src.p) + p, q * src.q);
+ }
+
+ /**
+ \brief returns true if finite and q is a unit quaternion
+ */
+
+ PX_CUDA_CALLABLE bool isValid() const
+ {
+ return p.isFinite() && q.isFinite() && q.isUnit();
+ }
+
+ /**
+ \brief returns true if finite and quat magnitude is reasonably close to unit to allow for some accumulation of error
+ vs isValid
+ */
+
+ PX_CUDA_CALLABLE bool isSane() const
+ {
+ return isFinite() && q.isSane();
+ }
+
+ /**
+ \brief returns true if all elems are finite (not NAN or INF, etc.)
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite() const
+ {
+ return p.isFinite() && q.isFinite();
+ }
+
+ //! Transform transform from parent (returns compound transform: first src, then this->inverse)
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform transformInv(const PxTransform& src) const
+ {
+ PX_ASSERT(src.isSane());
+ PX_ASSERT(isFinite());
+ // src = [srct, srcr] -> [r^-1*(srct-t), r^-1*srcr]
+ PxQuat qinv = q.getConjugate();
+ return PxTransform(qinv.rotate(src.p - p), qinv * src.q);
+ }
+
+ /**
+ \brief transform plane
+ */
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane transform(const PxPlane& plane) const
+ {
+ PxVec3 transformedNormal = rotate(plane.n);
+ return PxPlane(transformedNormal, plane.d - p.dot(transformedNormal));
+ }
+
+ /**
+ \brief inverse-transform plane
+ */
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxPlane inverseTransform(const PxPlane& plane) const
+ {
+ PxVec3 transformedNormal = rotateInv(plane.n);
+ return PxPlane(transformedNormal, plane.d + p.dot(plane.n));
+ }
+
+ /**
+ \brief return a normalized transform (i.e. one in which the quaternion has unit magnitude)
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxTransform getNormalized() const
+ {
+ return PxTransform(p, q.getNormalized());
+ }
+};
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXTRANSFORM_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxUnionCast.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxUnionCast.h
new file mode 100644
index 0000000..7bead42
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxUnionCast.h
@@ -0,0 +1,64 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXUNIONCAST_H
+#define PXFOUNDATION_PXUNIONCAST_H
+
+#include "foundation/Px.h"
+
+/** \addtogroup foundation
+@{
+*/
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+template <class A, class B>
+PX_FORCE_INLINE A PxUnionCast(B b)
+{
+ union AB
+ {
+ AB(B bb) : _b(bb)
+ {
+ }
+ B _b;
+ A _a;
+ } u(b);
+ return u._a;
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+
+#endif // PXFOUNDATION_PXUNIONCAST_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec2.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec2.h
new file mode 100644
index 0000000..bee58e8
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec2.h
@@ -0,0 +1,347 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXVEC2_H
+#define PXFOUNDATION_PXVEC2_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxMath.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief 2 Element vector class.
+
+This is a 2-dimensional vector class with public data members.
+*/
+class PxVec2
+{
+ public:
+ /**
+ \brief default constructor leaves data uninitialized.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2()
+ {
+ }
+
+ /**
+ \brief zero constructor.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2(PxZERO r) : x(0.0f), y(0.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ /**
+ \brief Assigns scalar parameter to all elements.
+
+ Useful to initialize to zero or one.
+
+ \param[in] a Value to assign to elements.
+ */
+ explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2(float a) : x(a), y(a)
+ {
+ }
+
+ /**
+ \brief Initializes from 2 scalar parameters.
+
+ \param[in] nx Value to initialize X component.
+ \param[in] ny Value to initialize Y component.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2(float nx, float ny) : x(nx), y(ny)
+ {
+ }
+
+ /**
+ \brief Copy ctor.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2(const PxVec2& v) : x(v.x), y(v.y)
+ {
+ }
+
+ // Operators
+
+ /**
+ \brief Assignment operator
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2& operator=(const PxVec2& p)
+ {
+ x = p.x;
+ y = p.y;
+ return *this;
+ }
+
+ /**
+ \brief element access
+ */
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE float& operator[](int index)
+ {
+ PX_ASSERT(index >= 0 && index <= 1);
+
+ return reinterpret_cast<float*>(this)[index];
+ }
+
+ /**
+ \brief element access
+ */
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE const float& operator[](int index) const
+ {
+ PX_ASSERT(index >= 0 && index <= 1);
+
+ return reinterpret_cast<const float*>(this)[index];
+ }
+
+ /**
+ \brief returns true if the two vectors are exactly equal.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator==(const PxVec2& v) const
+ {
+ return x == v.x && y == v.y;
+ }
+
+ /**
+ \brief returns true if the two vectors are not exactly equal.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator!=(const PxVec2& v) const
+ {
+ return x != v.x || y != v.y;
+ }
+
+ /**
+ \brief tests for exact zero vector
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isZero() const
+ {
+ return x == 0.0f && y == 0.0f;
+ }
+
+ /**
+ \brief returns true if all 2 elems of the vector are finite (not NAN or INF, etc.)
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool isFinite() const
+ {
+ return PxIsFinite(x) && PxIsFinite(y);
+ }
+
+ /**
+ \brief is normalized - used by API parameter validation
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isNormalized() const
+ {
+ const float unitTolerance = 1e-4f;
+ return isFinite() && PxAbs(magnitude() - 1) < unitTolerance;
+ }
+
+ /**
+ \brief returns the squared magnitude
+
+ Avoids calling PxSqrt()!
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float magnitudeSquared() const
+ {
+ return x * x + y * y;
+ }
+
+ /**
+ \brief returns the magnitude
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float magnitude() const
+ {
+ return PxSqrt(magnitudeSquared());
+ }
+
+ /**
+ \brief negation
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 operator-() const
+ {
+ return PxVec2(-x, -y);
+ }
+
+ /**
+ \brief vector addition
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 operator+(const PxVec2& v) const
+ {
+ return PxVec2(x + v.x, y + v.y);
+ }
+
+ /**
+ \brief vector difference
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 operator-(const PxVec2& v) const
+ {
+ return PxVec2(x - v.x, y - v.y);
+ }
+
+ /**
+ \brief scalar post-multiplication
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 operator*(float f) const
+ {
+ return PxVec2(x * f, y * f);
+ }
+
+ /**
+ \brief scalar division
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 operator/(float f) const
+ {
+ f = 1.0f / f; // PT: inconsistent notation with operator /=
+ return PxVec2(x * f, y * f);
+ }
+
+ /**
+ \brief vector addition
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2& operator+=(const PxVec2& v)
+ {
+ x += v.x;
+ y += v.y;
+ return *this;
+ }
+
+ /**
+ \brief vector difference
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2& operator-=(const PxVec2& v)
+ {
+ x -= v.x;
+ y -= v.y;
+ return *this;
+ }
+
+ /**
+ \brief scalar multiplication
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2& operator*=(float f)
+ {
+ x *= f;
+ y *= f;
+ return *this;
+ }
+ /**
+ \brief scalar division
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2& operator/=(float f)
+ {
+ f = 1.0f / f; // PT: inconsistent notation with operator /
+ x *= f;
+ y *= f;
+ return *this;
+ }
+
+ /**
+ \brief returns the scalar product of this and other.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float dot(const PxVec2& v) const
+ {
+ return x * v.x + y * v.y;
+ }
+
+ /** return a unit vector */
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 getNormalized() const
+ {
+ const float m = magnitudeSquared();
+ return m > 0.0f ? *this * PxRecipSqrt(m) : PxVec2(0, 0);
+ }
+
+ /**
+ \brief normalizes the vector in place
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float normalize()
+ {
+ const float m = magnitude();
+ if(m > 0.0f)
+ *this /= m;
+ return m;
+ }
+
+ /**
+ \brief a[i] * b[i], for all i.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 multiply(const PxVec2& a) const
+ {
+ return PxVec2(x * a.x, y * a.y);
+ }
+
+ /**
+ \brief element-wise minimum
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 minimum(const PxVec2& v) const
+ {
+ return PxVec2(PxMin(x, v.x), PxMin(y, v.y));
+ }
+
+ /**
+ \brief returns MIN(x, y);
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float minElement() const
+ {
+ return PxMin(x, y);
+ }
+
+ /**
+ \brief element-wise maximum
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec2 maximum(const PxVec2& v) const
+ {
+ return PxVec2(PxMax(x, v.x), PxMax(y, v.y));
+ }
+
+ /**
+ \brief returns MAX(x, y);
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float maxElement() const
+ {
+ return PxMax(x, y);
+ }
+
+ float x, y;
+};
+
+PX_CUDA_CALLABLE static PX_FORCE_INLINE PxVec2 operator*(float f, const PxVec2& v)
+{
+ return PxVec2(f * v.x, f * v.y);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXVEC2_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec3.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec3.h
new file mode 100644
index 0000000..7c15afb
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec3.h
@@ -0,0 +1,393 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXVEC3_H
+#define PXFOUNDATION_PXVEC3_H
+
+/** \addtogroup foundation
+@{
+*/
+
+#include "foundation/PxMath.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+/**
+\brief 3 Element vector class.
+
+This is a 3-dimensional vector class with public data members.
+*/
+class PxVec3
+{
+ public:
+ /**
+ \brief default constructor leaves data uninitialized.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3()
+ {
+ }
+
+ /**
+ \brief zero constructor.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3(PxZERO r) : x(0.0f), y(0.0f), z(0.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ /**
+ \brief Assigns scalar parameter to all elements.
+
+ Useful to initialize to zero or one.
+
+ \param[in] a Value to assign to elements.
+ */
+ explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3(float a) : x(a), y(a), z(a)
+ {
+ }
+
+ /**
+ \brief Initializes from 3 scalar parameters.
+
+ \param[in] nx Value to initialize X component.
+ \param[in] ny Value to initialize Y component.
+ \param[in] nz Value to initialize Z component.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3(float nx, float ny, float nz) : x(nx), y(ny), z(nz)
+ {
+ }
+
+ /**
+ \brief Copy ctor.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3(const PxVec3& v) : x(v.x), y(v.y), z(v.z)
+ {
+ }
+
+ // Operators
+
+ /**
+ \brief Assignment operator
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3& operator=(const PxVec3& p)
+ {
+ x = p.x;
+ y = p.y;
+ z = p.z;
+ return *this;
+ }
+
+ /**
+ \brief element access
+ */
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE float& operator[](unsigned int index)
+ {
+ PX_ASSERT(index <= 2);
+
+ return reinterpret_cast<float*>(this)[index];
+ }
+
+ /**
+ \brief element access
+ */
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_FORCE_INLINE const float& operator[](unsigned int index) const
+ {
+ PX_ASSERT(index <= 2);
+
+ return reinterpret_cast<const float*>(this)[index];
+ }
+ /**
+ \brief returns true if the two vectors are exactly equal.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator==(const PxVec3& v) const
+ {
+ return x == v.x && y == v.y && z == v.z;
+ }
+
+ /**
+ \brief returns true if the two vectors are not exactly equal.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool operator!=(const PxVec3& v) const
+ {
+ return x != v.x || y != v.y || z != v.z;
+ }
+
+ /**
+ \brief tests for exact zero vector
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isZero() const
+ {
+ return x == 0.0f && y == 0.0f && z == 0.0f;
+ }
+
+ /**
+ \brief returns true if all 3 elems of the vector are finite (not NAN or INF, etc.)
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool isFinite() const
+ {
+ return PxIsFinite(x) && PxIsFinite(y) && PxIsFinite(z);
+ }
+
+ /**
+ \brief is normalized - used by API parameter validation
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isNormalized() const
+ {
+ const float unitTolerance = 1e-4f;
+ return isFinite() && PxAbs(magnitude() - 1) < unitTolerance;
+ }
+
+ /**
+ \brief returns the squared magnitude
+
+ Avoids calling PxSqrt()!
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float magnitudeSquared() const
+ {
+ return x * x + y * y + z * z;
+ }
+
+ /**
+ \brief returns the magnitude
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float magnitude() const
+ {
+ return PxSqrt(magnitudeSquared());
+ }
+
+ /**
+ \brief negation
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 operator-() const
+ {
+ return PxVec3(-x, -y, -z);
+ }
+
+ /**
+ \brief vector addition
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 operator+(const PxVec3& v) const
+ {
+ return PxVec3(x + v.x, y + v.y, z + v.z);
+ }
+
+ /**
+ \brief vector difference
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 operator-(const PxVec3& v) const
+ {
+ return PxVec3(x - v.x, y - v.y, z - v.z);
+ }
+
+ /**
+ \brief scalar post-multiplication
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 operator*(float f) const
+ {
+ return PxVec3(x * f, y * f, z * f);
+ }
+
+ /**
+ \brief scalar division
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 operator/(float f) const
+ {
+ f = 1.0f / f;
+ return PxVec3(x * f, y * f, z * f);
+ }
+
+ /**
+ \brief vector addition
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3& operator+=(const PxVec3& v)
+ {
+ x += v.x;
+ y += v.y;
+ z += v.z;
+ return *this;
+ }
+
+ /**
+ \brief vector difference
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3& operator-=(const PxVec3& v)
+ {
+ x -= v.x;
+ y -= v.y;
+ z -= v.z;
+ return *this;
+ }
+
+ /**
+ \brief scalar multiplication
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3& operator*=(float f)
+ {
+ x *= f;
+ y *= f;
+ z *= f;
+ return *this;
+ }
+ /**
+ \brief scalar division
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3& operator/=(float f)
+ {
+ f = 1.0f / f;
+ x *= f;
+ y *= f;
+ z *= f;
+ return *this;
+ }
+
+ /**
+ \brief returns the scalar product of this and other.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float dot(const PxVec3& v) const
+ {
+ return x * v.x + y * v.y + z * v.z;
+ }
+
+ /**
+ \brief cross product
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 cross(const PxVec3& v) const
+ {
+ return PxVec3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
+ }
+
+ /** return a unit vector */
+
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 getNormalized() const
+ {
+ const float m = magnitudeSquared();
+ return m > 0.0f ? *this * PxRecipSqrt(m) : PxVec3(0, 0, 0);
+ }
+
+ /**
+ \brief normalizes the vector in place
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float normalize()
+ {
+ const float m = magnitude();
+ if(m > 0.0f)
+ *this /= m;
+ return m;
+ }
+
+ /**
+ \brief normalizes the vector in place. Does nothing if vector magnitude is under PX_NORMALIZATION_EPSILON.
+ Returns vector magnitude if >= PX_NORMALIZATION_EPSILON and 0.0f otherwise.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float normalizeSafe()
+ {
+ const float mag = magnitude();
+ if(mag < PX_NORMALIZATION_EPSILON)
+ return 0.0f;
+ *this *= 1.0f / mag;
+ return mag;
+ }
+
+ /**
+ \brief normalizes the vector in place. Asserts if vector magnitude is under PX_NORMALIZATION_EPSILON.
+ returns vector magnitude.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float normalizeFast()
+ {
+ const float mag = magnitude();
+ PX_ASSERT(mag >= PX_NORMALIZATION_EPSILON);
+ *this *= 1.0f / mag;
+ return mag;
+ }
+
+ /**
+ \brief a[i] * b[i], for all i.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 multiply(const PxVec3& a) const
+ {
+ return PxVec3(x * a.x, y * a.y, z * a.z);
+ }
+
+ /**
+ \brief element-wise minimum
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 minimum(const PxVec3& v) const
+ {
+ return PxVec3(PxMin(x, v.x), PxMin(y, v.y), PxMin(z, v.z));
+ }
+
+ /**
+ \brief returns MIN(x, y, z);
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float minElement() const
+ {
+ return PxMin(x, PxMin(y, z));
+ }
+
+ /**
+ \brief element-wise maximum
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 maximum(const PxVec3& v) const
+ {
+ return PxVec3(PxMax(x, v.x), PxMax(y, v.y), PxMax(z, v.z));
+ }
+
+ /**
+ \brief returns MAX(x, y, z);
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float maxElement() const
+ {
+ return PxMax(x, PxMax(y, z));
+ }
+
+ /**
+ \brief returns absolute values of components;
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 abs() const
+ {
+ return PxVec3(PxAbs(x), PxAbs(y), PxAbs(z));
+ }
+
+ float x, y, z;
+};
+
+PX_CUDA_CALLABLE static PX_FORCE_INLINE PxVec3 operator*(float f, const PxVec3& v)
+{
+ return PxVec3(f * v.x, f * v.y, f * v.z);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXVEC3_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec4.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec4.h
new file mode 100644
index 0000000..e33eddf
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/PxVec4.h
@@ -0,0 +1,376 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXVEC4_H
+#define PXFOUNDATION_PXVEC4_H
+/** \addtogroup foundation
+@{
+*/
+#include "foundation/PxMath.h"
+#include "foundation/PxVec3.h"
+#include "foundation/PxAssert.h"
+
+/**
+\brief 4 Element vector class.
+
+This is a 4-dimensional vector class with public data members.
+*/
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+
+class PxVec4
+{
+ public:
+ /**
+ \brief default constructor leaves data uninitialized.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4()
+ {
+ }
+
+ /**
+ \brief zero constructor.
+ */
+ PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4(PxZERO r) : x(0.0f), y(0.0f), z(0.0f), w(0.0f)
+ {
+ PX_UNUSED(r);
+ }
+
+ /**
+ \brief Assigns scalar parameter to all elements.
+
+ Useful to initialize to zero or one.
+
+ \param[in] a Value to assign to elements.
+ */
+ explicit PX_CUDA_CALLABLE PX_INLINE PxVec4(float a) : x(a), y(a), z(a), w(a)
+ {
+ }
+
+ /**
+ \brief Initializes from 3 scalar parameters.
+
+ \param[in] nx Value to initialize X component.
+ \param[in] ny Value to initialize Y component.
+ \param[in] nz Value to initialize Z component.
+ \param[in] nw Value to initialize W component.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4(float nx, float ny, float nz, float nw) : x(nx), y(ny), z(nz), w(nw)
+ {
+ }
+
+ /**
+ \brief Initializes from 3 scalar parameters.
+
+ \param[in] v Value to initialize the X, Y, and Z components.
+ \param[in] nw Value to initialize W component.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4(const PxVec3& v, float nw) : x(v.x), y(v.y), z(v.z), w(nw)
+ {
+ }
+
+ /**
+ \brief Initializes from an array of scalar parameters.
+
+ \param[in] v Value to initialize with.
+ */
+ explicit PX_CUDA_CALLABLE PX_INLINE PxVec4(const float v[]) : x(v[0]), y(v[1]), z(v[2]), w(v[3])
+ {
+ }
+
+ /**
+ \brief Copy ctor.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4(const PxVec4& v) : x(v.x), y(v.y), z(v.z), w(v.w)
+ {
+ }
+
+ // Operators
+
+ /**
+ \brief Assignment operator
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4& operator=(const PxVec4& p)
+ {
+ x = p.x;
+ y = p.y;
+ z = p.z;
+ w = p.w;
+ return *this;
+ }
+
+ /**
+ \brief element access
+ */
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_INLINE float& operator[](unsigned int index)
+ {
+ PX_ASSERT(index <= 3);
+
+ return reinterpret_cast<float*>(this)[index];
+ }
+
+ /**
+ \brief element access
+ */
+ PX_DEPRECATED PX_CUDA_CALLABLE PX_INLINE const float& operator[](unsigned int index) const
+ {
+ PX_ASSERT(index <= 3);
+
+ return reinterpret_cast<const float*>(this)[index];
+ }
+
+ /**
+ \brief returns true if the two vectors are exactly equal.
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator==(const PxVec4& v) const
+ {
+ return x == v.x && y == v.y && z == v.z && w == v.w;
+ }
+
+ /**
+ \brief returns true if the two vectors are not exactly equal.
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool operator!=(const PxVec4& v) const
+ {
+ return x != v.x || y != v.y || z != v.z || w != v.w;
+ }
+
+ /**
+ \brief tests for exact zero vector
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool isZero() const
+ {
+ return x == 0 && y == 0 && z == 0 && w == 0;
+ }
+
+ /**
+ \brief returns true if all 3 elems of the vector are finite (not NAN or INF, etc.)
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool isFinite() const
+ {
+ return PxIsFinite(x) && PxIsFinite(y) && PxIsFinite(z) && PxIsFinite(w);
+ }
+
+ /**
+ \brief is normalized - used by API parameter validation
+ */
+ PX_CUDA_CALLABLE PX_INLINE bool isNormalized() const
+ {
+ const float unitTolerance = 1e-4f;
+ return isFinite() && PxAbs(magnitude() - 1) < unitTolerance;
+ }
+
+ /**
+ \brief returns the squared magnitude
+
+ Avoids calling PxSqrt()!
+ */
+ PX_CUDA_CALLABLE PX_INLINE float magnitudeSquared() const
+ {
+ return x * x + y * y + z * z + w * w;
+ }
+
+ /**
+ \brief returns the magnitude
+ */
+ PX_CUDA_CALLABLE PX_INLINE float magnitude() const
+ {
+ return PxSqrt(magnitudeSquared());
+ }
+
+ /**
+ \brief negation
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 operator-() const
+ {
+ return PxVec4(-x, -y, -z, -w);
+ }
+
+ /**
+ \brief vector addition
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 operator+(const PxVec4& v) const
+ {
+ return PxVec4(x + v.x, y + v.y, z + v.z, w + v.w);
+ }
+
+ /**
+ \brief vector difference
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 operator-(const PxVec4& v) const
+ {
+ return PxVec4(x - v.x, y - v.y, z - v.z, w - v.w);
+ }
+
+ /**
+ \brief scalar post-multiplication
+ */
+
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 operator*(float f) const
+ {
+ return PxVec4(x * f, y * f, z * f, w * f);
+ }
+
+ /**
+ \brief scalar division
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 operator/(float f) const
+ {
+ f = 1.0f / f;
+ return PxVec4(x * f, y * f, z * f, w * f);
+ }
+
+ /**
+ \brief vector addition
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4& operator+=(const PxVec4& v)
+ {
+ x += v.x;
+ y += v.y;
+ z += v.z;
+ w += v.w;
+ return *this;
+ }
+
+ /**
+ \brief vector difference
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4& operator-=(const PxVec4& v)
+ {
+ x -= v.x;
+ y -= v.y;
+ z -= v.z;
+ w -= v.w;
+ return *this;
+ }
+
+ /**
+ \brief scalar multiplication
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4& operator*=(float f)
+ {
+ x *= f;
+ y *= f;
+ z *= f;
+ w *= f;
+ return *this;
+ }
+ /**
+ \brief scalar division
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4& operator/=(float f)
+ {
+ f = 1.0f / f;
+ x *= f;
+ y *= f;
+ z *= f;
+ w *= f;
+ return *this;
+ }
+
+ /**
+ \brief returns the scalar product of this and other.
+ */
+ PX_CUDA_CALLABLE PX_INLINE float dot(const PxVec4& v) const
+ {
+ return x * v.x + y * v.y + z * v.z + w * v.w;
+ }
+
+ /** return a unit vector */
+
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 getNormalized() const
+ {
+ float m = magnitudeSquared();
+ return m > 0.0f ? *this * PxRecipSqrt(m) : PxVec4(0, 0, 0, 0);
+ }
+
+ /**
+ \brief normalizes the vector in place
+ */
+ PX_CUDA_CALLABLE PX_INLINE float normalize()
+ {
+ float m = magnitude();
+ if(m > 0.0f)
+ *this /= m;
+ return m;
+ }
+
+ /**
+ \brief a[i] * b[i], for all i.
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 multiply(const PxVec4& a) const
+ {
+ return PxVec4(x * a.x, y * a.y, z * a.z, w * a.w);
+ }
+
+ /**
+ \brief element-wise minimum
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 minimum(const PxVec4& v) const
+ {
+ return PxVec4(PxMin(x, v.x), PxMin(y, v.y), PxMin(z, v.z), PxMin(w, v.w));
+ }
+
+ /**
+ \brief element-wise maximum
+ */
+ PX_CUDA_CALLABLE PX_INLINE PxVec4 maximum(const PxVec4& v) const
+ {
+ return PxVec4(PxMax(x, v.x), PxMax(y, v.y), PxMax(z, v.z), PxMax(w, v.w));
+ }
+
+ PX_CUDA_CALLABLE PX_INLINE PxVec3 getXYZ() const
+ {
+ return PxVec3(x, y, z);
+ }
+
+ /**
+ \brief set vector elements to zero
+ */
+ PX_CUDA_CALLABLE PX_INLINE void setZero()
+ {
+ x = y = z = w = 0.0f;
+ }
+
+ float x, y, z, w;
+};
+
+PX_CUDA_CALLABLE static PX_INLINE PxVec4 operator*(float f, const PxVec4& v)
+{
+ return PxVec4(f * v.x, f * v.y, f * v.z, f * v.w);
+}
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+
+/** @} */
+#endif // #ifndef PXFOUNDATION_PXVEC4_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/nx/PxNXIntrinsics.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/nx/PxNXIntrinsics.h
new file mode 100644
index 0000000..adf3bf5
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/nx/PxNXIntrinsics.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
+ *
+ * NVIDIA CORPORATION and its licensors retain all intellectual property
+ * and proprietary rights in and to this software, related documentation
+ * and any modifications thereto. Any use, reproduction, disclosure or
+ * distribution of this software and related documentation without an express
+ * license agreement from NVIDIA CORPORATION is strictly prohibited.
+ */
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+
+#ifndef PX_FOUNDATION_PX_NX_INTRINSICS_H
+#define PX_FOUNDATION_PX_NX_INTRINSICS_H
+
+#include "foundation/Px.h"
+#include "foundation/PxAssert.h"
+
+#if !PX_NX
+ #error "This file should only be included by NX builds!!"
+#endif
+
+#include <math.h>
+#include <float.h>
+
+#include "nn/cstd/cstd_CMath.h"
+
+#if !PX_DOXYGEN
+namespace physx
+{
+namespace intrinsics
+{
+#endif
+
+ //! \brief platform-specific absolute value
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float abs(float a) { return ::fabsf(a); }
+
+ //! \brief platform-specific select float
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float fsel(float a, float b, float c) { return (a >= 0.0f) ? b : c; }
+
+ //! \brief platform-specific sign
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float sign(float a) { return (a >= 0.0f) ? 1.0f : -1.0f; }
+
+ //! \brief platform-specific reciprocal
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float recip(float a) { return 1.0f/a; }
+
+ //! \brief platform-specific reciprocal estimate
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float recipFast(float a) { return 1.0f/a; }
+
+ //! \brief platform-specific square root
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float sqrt(float a) { return ::sqrtf(a); }
+
+ //! \brief platform-specific reciprocal square root
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrt(float a) { return 1.0f/::sqrtf(a); }
+
+ //! \brief platform-specific reciprocal square root estimate
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrtFast(float a) { return 1.0f/::sqrtf(a); }
+
+ //! \brief platform-specific sine
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float sin(float a) { return ::sinf(a); }
+
+ //! \brief platform-specific cosine
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float cos(float a) { return ::cosf(a); }
+
+ //! \brief platform-specific minimum
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMin(float a, float b) { return a<b ? a : b; }
+
+ //! \brief platform-specific maximum
+ PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMax(float a, float b) { return a>b ? a : b; }
+
+ //! \brief platform-specific finiteness check
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(float a)
+ {
+#ifdef __CUDACC__
+ return isfinite(a) ? true : false;
+#else
+ return !nn::cstd::IsNan(a) && !nn::cstd::IsInf(a);
+#endif
+ }
+
+ //! \brief platform-specific finiteness check
+ PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(double a)
+ {
+#ifdef __CUDACC__
+ return isfinite(a) ? true : false;
+#else
+ return !nn::cstd::IsNan(a) && !nn::cstd::IsInf(a);
+#endif
+ }
+
+ /*!
+ Sets \c count bytes starting at \c dst to zero.
+ */
+ PX_FORCE_INLINE void* memZero(void* PX_RESTRICT dest, uint32_t count)
+ {
+ return memset(dest, 0, count);
+ }
+
+ /*!
+ Sets \c count bytes starting at \c dst to \c c.
+ */
+ PX_FORCE_INLINE void* memSet(void* PX_RESTRICT dest, int32_t c, uint32_t count)
+ {
+ return memset(dest, c, count);
+ }
+
+ /*!
+ Copies \c count bytes from \c src to \c dst. User memMove if regions overlap.
+ */
+ PX_FORCE_INLINE void* memCopy(void* PX_RESTRICT dest, const void* PX_RESTRICT src, uint32_t count)
+ {
+ return memcpy(dest, src, count);
+ }
+
+ /*!
+ Copies \c count bytes from \c src to \c dst. Supports overlapping regions.
+ */
+ PX_FORCE_INLINE void* memMove(void* PX_RESTRICT dest, const void* PX_RESTRICT src, uint32_t count)
+ {
+ return memmove(dest, src, count);
+ }
+
+ /*!
+ Set 128B to zero starting at \c dst+offset. Must be aligned.
+ */
+ PX_FORCE_INLINE void memZero128(void* PX_RESTRICT dest, uint32_t offset = 0)
+ {
+ PX_ASSERT(((size_t(dest)+offset) & 0x7f) == 0);
+ memSet((char* PX_RESTRICT)dest+offset, 0, 128);
+ }
+
+#if !PX_DOXYGEN
+} // namespace intrinsics
+} // namespace physx
+#endif
+
+#endif
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/unix/PxUnixIntrinsics.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/unix/PxUnixIntrinsics.h
new file mode 100644
index 0000000..7b9b9f3
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/unix/PxUnixIntrinsics.h
@@ -0,0 +1,181 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXUNIXINTRINSICS_H
+#define PXFOUNDATION_PXUNIXINTRINSICS_H
+
+#include "foundation/Px.h"
+#include "foundation/PxAssert.h"
+
+#if !(PX_LINUX || PX_ANDROID || PX_PS4 || PX_APPLE_FAMILY)
+#error "This file should only be included by Unix builds!!"
+#endif
+
+#if PX_LINUX && PX_ARM
+ // Linux ARM toolchain can somehow end up including cmath header after math.h, which will undef a bunch of macros and place them in std namespace
+ #ifndef isfinite
+ #define isfinite std::isfinite
+ #endif
+#endif
+
+#include <math.h>
+#include <float.h>
+
+namespace physx
+{
+namespace intrinsics
+{
+//! \brief platform-specific absolute value
+PX_CUDA_CALLABLE PX_FORCE_INLINE float abs(float a)
+{
+ return ::fabsf(a);
+}
+
+//! \brief platform-specific select float
+PX_CUDA_CALLABLE PX_FORCE_INLINE float fsel(float a, float b, float c)
+{
+ return (a >= 0.0f) ? b : c;
+}
+
+//! \brief platform-specific sign
+PX_CUDA_CALLABLE PX_FORCE_INLINE float sign(float a)
+{
+ return (a >= 0.0f) ? 1.0f : -1.0f;
+}
+
+//! \brief platform-specific reciprocal
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recip(float a)
+{
+ return 1.0f / a;
+}
+
+//! \brief platform-specific reciprocal estimate
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recipFast(float a)
+{
+ return 1.0f / a;
+}
+
+//! \brief platform-specific square root
+PX_CUDA_CALLABLE PX_FORCE_INLINE float sqrt(float a)
+{
+ return ::sqrtf(a);
+}
+
+//! \brief platform-specific reciprocal square root
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrt(float a)
+{
+ return 1.0f / ::sqrtf(a);
+}
+
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrtFast(float a)
+{
+ return 1.0f / ::sqrtf(a);
+}
+
+//! \brief platform-specific sine
+PX_CUDA_CALLABLE PX_FORCE_INLINE float sin(float a)
+{
+ return ::sinf(a);
+}
+
+//! \brief platform-specific cosine
+PX_CUDA_CALLABLE PX_FORCE_INLINE float cos(float a)
+{
+ return ::cosf(a);
+}
+
+//! \brief platform-specific minimum
+PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMin(float a, float b)
+{
+ return a < b ? a : b;
+}
+
+//! \brief platform-specific maximum
+PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMax(float a, float b)
+{
+ return a > b ? a : b;
+}
+
+//! \brief platform-specific finiteness check (not INF or NAN)
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(float a)
+{
+ return !!isfinite(a);
+}
+
+//! \brief platform-specific finiteness check (not INF or NAN)
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(double a)
+{
+ return !!isfinite(a);
+}
+
+/*!
+Sets \c count bytes starting at \c dst to zero.
+*/
+PX_FORCE_INLINE void* memZero(void* dest, uint32_t count)
+{
+ return memset(dest, 0, count);
+}
+
+/*!
+Sets \c count bytes starting at \c dst to \c c.
+*/
+PX_FORCE_INLINE void* memSet(void* dest, int32_t c, uint32_t count)
+{
+ return memset(dest, c, count);
+}
+
+/*!
+Copies \c count bytes from \c src to \c dst. User memMove if regions overlap.
+*/
+PX_FORCE_INLINE void* memCopy(void* PX_RESTRICT dest, const void* PX_RESTRICT src, uint32_t count)
+{
+ return memcpy(dest, src, count);
+}
+
+/*!
+Copies \c count bytes from \c src to \c dst. Supports overlapping regions.
+*/
+PX_FORCE_INLINE void* memMove(void* dest, const void* src, uint32_t count)
+{
+ return memmove(dest, src, count);
+}
+
+/*!
+Set 128B to zero starting at \c dst+offset. Must be aligned.
+*/
+PX_FORCE_INLINE void memZero128(void* dest, uint32_t offset = 0)
+{
+ PX_ASSERT(((size_t(dest) + offset) & 0x7f) == 0);
+ memSet(reinterpret_cast<char*>(dest) + offset, 0, 128);
+}
+
+} // namespace intrinsics
+} // namespace physx
+
+#endif // #ifndef PXFOUNDATION_PXUNIXINTRINSICS_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsFoundationDelayLoadHook.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsFoundationDelayLoadHook.h
new file mode 100644
index 0000000..1d42185
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsFoundationDelayLoadHook.h
@@ -0,0 +1,71 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PX_FOUNDATION_DELAY_LOAD_HOOK
+#define PX_FOUNDATION_DELAY_LOAD_HOOK
+
+#include "foundation/PxPreprocessor.h"
+
+/** \addtogroup foundation
+@{
+*/
+
+#if !PX_DOXYGEN
+namespace physx
+{
+#endif
+ /**
+ \brief PxFoundationDelayLoadHook
+
+ This is a helper class for delay loading the PxFoundation dll.
+ If a PxFoundation dll with a non-default file name needs to be loaded,
+ PxFoundationDelayLoadHook can be sub-classed to provide the custom file names.
+
+ Once the names are set, the instance must be set for use by the loading dll.
+ */
+ class PxFoundationDelayLoadHook
+ {
+ public:
+ PxFoundationDelayLoadHook() {}
+ virtual ~PxFoundationDelayLoadHook() {}
+
+ virtual const char* getPxFoundationDEBUGDllName() const = 0;
+ virtual const char* getPxFoundationCHECKEDDllName() const = 0;
+ virtual const char* getPxFoundationPROFILEDllName() const = 0;
+ virtual const char* getPxFoundationDllName() const = 0;
+
+ protected:
+ private:
+ };
+
+#if !PX_DOXYGEN
+} // namespace physx
+#endif
+/** @} */
+#endif
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsIntrinsics.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsIntrinsics.h
new file mode 100644
index 0000000..766558e
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/windows/PxWindowsIntrinsics.h
@@ -0,0 +1,188 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXWINDOWSINTRINSICS_H
+#define PXFOUNDATION_PXWINDOWSINTRINSICS_H
+
+#include "foundation/Px.h"
+#include "foundation/PxAssert.h"
+
+#if !PX_WINDOWS_FAMILY
+#error "This file should only be included by Windows builds!!"
+#endif
+
+#include <math.h>
+#include <float.h>
+
+#if !PX_DOXYGEN
+namespace physx
+{
+namespace intrinsics
+{
+#endif
+
+//! \brief platform-specific absolute value
+PX_CUDA_CALLABLE PX_FORCE_INLINE float abs(float a)
+{
+ return ::fabsf(a);
+}
+
+//! \brief platform-specific select float
+PX_CUDA_CALLABLE PX_FORCE_INLINE float fsel(float a, float b, float c)
+{
+ return (a >= 0.0f) ? b : c;
+}
+
+//! \brief platform-specific sign
+PX_CUDA_CALLABLE PX_FORCE_INLINE float sign(float a)
+{
+ return (a >= 0.0f) ? 1.0f : -1.0f;
+}
+
+//! \brief platform-specific reciprocal
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recip(float a)
+{
+ return 1.0f / a;
+}
+
+//! \brief platform-specific reciprocal estimate
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recipFast(float a)
+{
+ return 1.0f / a;
+}
+
+//! \brief platform-specific square root
+PX_CUDA_CALLABLE PX_FORCE_INLINE float sqrt(float a)
+{
+ return ::sqrtf(a);
+}
+
+//! \brief platform-specific reciprocal square root
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrt(float a)
+{
+ return 1.0f / ::sqrtf(a);
+}
+
+//! \brief platform-specific reciprocal square root estimate
+PX_CUDA_CALLABLE PX_FORCE_INLINE float recipSqrtFast(float a)
+{
+ return 1.0f / ::sqrtf(a);
+}
+
+//! \brief platform-specific sine
+PX_CUDA_CALLABLE PX_FORCE_INLINE float sin(float a)
+{
+ return ::sinf(a);
+}
+
+//! \brief platform-specific cosine
+PX_CUDA_CALLABLE PX_FORCE_INLINE float cos(float a)
+{
+ return ::cosf(a);
+}
+
+//! \brief platform-specific minimum
+PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMin(float a, float b)
+{
+ return a < b ? a : b;
+}
+
+//! \brief platform-specific maximum
+PX_CUDA_CALLABLE PX_FORCE_INLINE float selectMax(float a, float b)
+{
+ return a > b ? a : b;
+}
+
+//! \brief platform-specific finiteness check (not INF or NAN)
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(float a)
+{
+#ifdef __CUDACC__
+ return !!isfinite(a);
+#else
+ return (0 == ((_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF) & _fpclass(a)));
+#endif
+}
+
+//! \brief platform-specific finiteness check (not INF or NAN)
+PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFinite(double a)
+{
+#ifdef __CUDACC__
+ return !!isfinite(a);
+#else
+ return (0 == ((_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF) & _fpclass(a)));
+#endif
+}
+
+/*!
+Sets \c count bytes starting at \c dst to zero.
+*/
+PX_FORCE_INLINE void* memZero(void* dest, uint32_t count)
+{
+ return memset(dest, 0, count);
+}
+
+/*!
+Sets \c count bytes starting at \c dst to \c c.
+*/
+PX_FORCE_INLINE void* memSet(void* dest, int32_t c, uint32_t count)
+{
+ return memset(dest, c, count);
+}
+
+/*!
+Copies \c count bytes from \c src to \c dst. User memMove if regions overlap.
+*/
+PX_FORCE_INLINE void* memCopy(void* PX_RESTRICT dest, const void* PX_RESTRICT src, uint32_t count)
+{
+ return memcpy(dest, src, count);
+}
+
+/*!
+Copies \c count bytes from \c src to \c dst. Supports overlapping regions.
+*/
+PX_FORCE_INLINE void* memMove(void* dest, const void* src, uint32_t count)
+{
+ return memmove(dest, src, count);
+}
+
+/*!
+Set 128B to zero starting at \c dst+offset. Must be aligned.
+*/
+PX_FORCE_INLINE void memZero128(void* dest, uint32_t offset = 0)
+{
+ PX_ASSERT(((size_t(dest) + offset) & 0x7f) == 0);
+ memSet(reinterpret_cast<char*>(dest) + offset, 0, 128);
+}
+
+#if !PX_DOXYGEN
+} // namespace intrinsics
+} // namespace physx
+#endif
+
+#endif // #ifndef PXFOUNDATION_PXWINDOWSINTRINSICS_H
diff --git a/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/xboxone/PxXboxOneIntrinsics.h b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/xboxone/PxXboxOneIntrinsics.h
new file mode 100644
index 0000000..b6ddf7a
--- /dev/null
+++ b/NvCloth/samples/external/PxShared/1.0.21467209.1/include/foundation/xboxone/PxXboxOneIntrinsics.h
@@ -0,0 +1,188 @@
+// This code contains NVIDIA Confidential Information and is disclosed to you
+// under a form of NVIDIA software license agreement provided separately to you.
+//
+// Notice
+// NVIDIA Corporation and its licensors retain all intellectual property and
+// proprietary rights in and to this software and related documentation and
+// any modifications thereto. Any use, reproduction, disclosure, or
+// distribution of this software and related documentation without an express
+// license agreement from NVIDIA Corporation is strictly prohibited.
+//
+// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
+// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
+//
+// Information and code furnished is believed to be accurate and reliable.
+// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved.
+// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
+// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
+
+#ifndef PXFOUNDATION_PXXBOXONEINTRINSICS_H
+#define PXFOUNDATION_PXXBOXONEINTRINSICS_H
+
+#include "foundation/Px.h"
+#include "foundation/PxAssert.h"
+
+#if !PX_XBOXONE
+#error "This file should only be included by XboxOne builds!!"
+#endif
+
+#include <math.h>
+#include <float.h>
+
+#if !PX_DOXYGEN
+namespace physx
+{
+namespace intrinsics
+{
+#endif
+
+//! \brief platform-specific absolute value
+PX_FORCE_INLINE float abs(float a)
+{
+ return ::fabsf(a);
+}
+
+//! \brief platform-specific select float
+PX_FORCE_INLINE float fsel(float a, float b, float c)
+{
+ return (a >= 0.0f) ? b : c;
+}
+
+//! \brief platform-specific sign
+PX_FORCE_INLINE float sign(float a)
+{
+ return (a >= 0.0f) ? 1.0f : -1.0f;
+}
+
+//! \brief platform-specific reciprocal
+PX_FORCE_INLINE float recip(float a)
+{
+ return 1.0f / a;
+}
+
+//! \brief platform-specific reciprocal estimate
+PX_FORCE_INLINE float recipFast(float a)
+{
+ return 1.0f / a;
+}
+
+//! \brief platform-specific square root
+PX_FORCE_INLINE float sqrt(float a)
+{
+ return ::sqrtf(a);
+}
+
+//! \brief platform-specific reciprocal square root
+PX_FORCE_INLINE float recipSqrt(float a)
+{
+ return 1.0f / ::sqrtf(a);
+}
+
+//! \brief platform-specific reciprocal square root estimate
+PX_FORCE_INLINE float recipSqrtFast(float a)
+{
+ return 1.0f / ::sqrtf(a);
+}
+
+//! \brief platform-specific sine
+PX_FORCE_INLINE float sin(float a)
+{
+ return ::sinf(a);
+}
+
+//! \brief platform-specific cosine
+PX_FORCE_INLINE float cos(float a)
+{
+ return ::cosf(a);
+}
+
+//! \brief platform-specific minimum
+PX_FORCE_INLINE float selectMin(float a, float b)
+{
+ return a < b ? a : b;
+}
+
+//! \brief platform-specific maximum
+PX_FORCE_INLINE float selectMax(float a, float b)
+{
+ return a > b ? a : b;
+}
+
+//! \brief platform-specific finiteness check (not INF or NAN)
+PX_FORCE_INLINE bool isFinite(float a)
+{
+#ifdef __CUDACC__
+ return isfinite(a) ? true : false;
+#else
+ return (0 == ((_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF) & _fpclass(a)));
+#endif
+}
+
+//! \brief platform-specific finiteness check (not INF or NAN)
+PX_FORCE_INLINE bool isFinite(double a)
+{
+#ifdef __CUDACC__
+ return isfinite(a) ? true : false;
+#else
+ return (0 == ((_FPCLASS_SNAN | _FPCLASS_QNAN | _FPCLASS_NINF | _FPCLASS_PINF) & _fpclass(a)));
+#endif
+}
+
+/*!
+Sets \c count bytes starting at \c dst to zero.
+*/
+PX_FORCE_INLINE void* memZero(void* dest, uint32_t count)
+{
+ return memset(dest, 0, count);
+}
+
+/*!
+Sets \c count bytes starting at \c dst to \c c.
+*/
+PX_FORCE_INLINE void* memSet(void* dest, int32_t c, uint32_t count)
+{
+ return memset(dest, c, count);
+}
+
+/*!
+Copies \c count bytes from \c src to \c dst. User memMove if regions overlap.
+*/
+PX_FORCE_INLINE void* memCopy(void* PX_RESTRICT dest, const void* PX_RESTRICT src, uint32_t count)
+{
+ return memcpy(dest, src, count);
+}
+
+/*!
+Copies \c count bytes from \c src to \c dst. Supports overlapping regions.
+*/
+PX_FORCE_INLINE void* memMove(void* dest, const void* src, uint32_t count)
+{
+ return memmove(dest, src, count);
+}
+
+/*!
+Set 128B to zero starting at \c dst+offset. Must be aligned.
+*/
+PX_FORCE_INLINE void memZero128(void* dest, uint32_t offset = 0)
+{
+ PX_ASSERT(((size_t(dest) + offset) & 0x7f) == 0);
+ memSet(reinterpret_cast<char*>(dest) + offset, 0, 128);
+}
+
+#if !PX_DOXYGEN
+} // namespace intrinsics
+} // namespace physx
+#endif
+
+#endif // #ifndef PXFOUNDATION_PXXBOXONEINTRINSICS_H
diff --git a/NvCloth/samples/external/hbao/GFSDK_SSAO.h b/NvCloth/samples/external/hbao/GFSDK_SSAO.h
new file mode 100644
index 0000000..d5e2a83
--- /dev/null
+++ b/NvCloth/samples/external/hbao/GFSDK_SSAO.h
@@ -0,0 +1,1391 @@
+/*
+* Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved.
+*
+* NVIDIA CORPORATION and its licensors retain all intellectual property
+* and proprietary rights in and to this software, related documentation
+* and any modifications thereto. Any use, reproduction, disclosure or
+* distribution of this software and related documentation without an express
+* license agreement from NVIDIA CORPORATION is strictly prohibited.
+*/
+
+/*====================================================================================================
+-------------------------------------------------------------------------------------------
+ HBAO+
+-------------------------------------------------------------------------------------------
+
+HBAO+ is a SSAO algorithm designed to achieve high efficiency on DX11 GPUs.
+The algorithm is based on HBAO [Bavoil and Sainz 2008], with the following differences:
+
+(1.) To minimize cache trashing, HBAO+ does not use any randomization texture.
+Instead, the algorithm uses an Interleaved Rendering approach, generating the AO
+in multiple passes with a unique jitter value per pass [Bavoil and Jansen 2013].
+
+(2.) To avoid over-occlusion artifacts, HBAO+ uses a simpler AO approximation than HBAO,
+similar to "Scalable Ambient Obscurance" [McGuire et al. 2012] [Bukowski et al. 2012].
+
+(3.) To minimize flickering, the HBAO+ is always rendered in full resolution,
+from full-resolution depths.
+
+[Bavoil et al. 2008] "Image-Space Horizon-Based Ambient Occlusion"
+http://www.nvidia.com/object/siggraph-2008-HBAO.html
+
+[McGuire et al. 2012] "Scalable Ambient Obscurance"
+http://graphics.cs.williams.edu/papers/SAOHPG12/
+
+[Bukowski et al. 2012] "Scalable High-Quality Motion Blur and Ambient Occlusion"
+http://graphics.cs.williams.edu/papers/VVSIGGRAPH12/
+
+[Bavoil and Jansen 2013] "Particle Shadows & Cache-Efficient Post-Processing"
+https://developer.nvidia.com/gdc-2013
+
+-------------------------------------------------------------------------------------------
+ MSAA
+-------------------------------------------------------------------------------------------
+
+(1.) The input depth & normal textures are required to have matching dimensions and MSAA sample count.
+
+(2.) The output render target can have arbitrary dimensions and MSAA sample count.
+
+(3.) If the input textures are MSAA, only sample 0 is used to render the AO.
+
+(4.) If the output render target is MSAA, a per-pixel AO value is written to all samples.
+
+-------------------------------------------------------------------------------------------
+ PERFORMANCE
+-------------------------------------------------------------------------------------------
+
+In 1920x1080 1xAA, using HARDWARE_DEPTHS as input and BLUR_RADIUS_4, the RenderAO call takes
+up to 46 MB of video memory and 2.3 ms / frame on GeForce GTX 680.
+
+-------------------------------------------------------------------------------------------
+ INTEGRATION EXAMPLE
+-------------------------------------------------------------------------------------------
+
+(1.) INITIALIZE THE LIBRARY
+
+ GFSDK_SSAO_CustomHeap CustomHeap;
+ CustomHeap.new_ = ::operator new;
+ CustomHeap.delete_ = ::operator delete;
+
+ GFSDK_SSAO_Status status;
+ GFSDK_SSAO_Context_D3D11* pAOContext;
+ status = GFSDK_SSAO_CreateContext_D3D11(pD3D11Device, &pAOContext, &CustomHeap);
+ assert(status == GFSDK_SSAO_OK); // HBAO+ requires feature level 11_0 or above
+
+(2.) SET INPUT DEPTHS
+
+ GFSDK_SSAO_InputData_D3D11 Input;
+ Input.DepthData.DepthTextureType = GFSDK_SSAO_HARDWARE_DEPTHS;
+ Input.DepthData.pFullResDepthTextureSRV = pDepthStencilTextureSRV;
+ Input.DepthData.ProjectionMatrix.Data = GFSDK_SSAO_Float4x4(pProjectionMatrix);
+ Input.DepthData.ProjectionMatrix.Layout = GFSDK_SSAO_ROW_MAJOR_ORDER;
+ Input.DepthData.MetersToViewSpaceUnits = SceneScale;
+
+(3.) SET AO PARAMETERS
+
+ GFSDK_SSAO_Parameters_D3D11 Params;
+ Params.Radius = 2.f;
+ Params.Bias = 0.1f;
+ Params.PowerExponent = 2.f;
+ Params.Blur.Enable = true;
+ Params.Blur.Radius = GFSDK_SSAO_BLUR_RADIUS_4;
+ Params.Blur.Sharpness = 16.f;
+
+(4.) SET RENDER TARGET
+
+ GFSDK_SSAO_Output_D3D11 Output;
+ Output.pRenderTargetView = pOutputColorRTV;
+ Output.Blend.Mode = GFSDK_SSAO_OVERWRITE_RGB;
+
+(5.) RENDER AO
+
+ status = pAOContext->RenderAO(pD3D11Context, Input, Params, Output);
+ assert(status == GFSDK_SSAO_OK);
+
+-------------------------------------------------------------------------------------------
+ DOCUMENTATION AND SUPPORT
+-------------------------------------------------------------------------------------------
+
+ See the documentation for more information on the input requirements and the parameters.
+ For any feedback or questions about this library, please contact [email protected].
+
+====================================================================================================*/
+
+#pragma once
+#pragma pack(push,8) // Make sure we have consistent structure packings
+
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+/*====================================================================================================
+ Entry-point declarations.
+====================================================================================================*/
+
+#if defined(ANDROID) || defined(LINUX) || defined(MACOSX)
+#define GFSDK_SSAO_CDECL
+#define GFSDK_SSAO_EXPORT
+#define GFSDK_SSAO_STDCALL
+#else
+#define GFSDK_SSAO_CDECL __cdecl
+#define GFSDK_SSAO_EXPORT __declspec(dllexport)
+#define GFSDK_SSAO_STDCALL __stdcall
+#endif
+
+#if GFSDK_SSAO_DYNAMIC_LOAD_LIBRARY
+
+#define GFSDK_SSAO_DECL(RETURN_TYPE, FUNCTION_NAME, ...) typedef RETURN_TYPE (*PFN_##FUNCTION_NAME)(__VA_ARGS__); extern PFN_##FUNCTION_NAME FUNCTION_NAME
+#define GFSDK_SSAO_VERSION_ARGUMENT GFSDK_SSAO_Version HeaderVersion
+#define GFSDK_SSAO_CUSTOM_HEAP_ARGUMENT const GFSDK_SSAO_CustomHeap* pCustomHeap
+
+#else
+
+#if !_WINDLL
+#define GFSDK_SSAO_DECL(RETURN_TYPE, FUNCTION_NAME, ...) extern "C" RETURN_TYPE GFSDK_SSAO_CDECL FUNCTION_NAME(__VA_ARGS__)
+#else
+#define GFSDK_SSAO_DECL(RETURN_TYPE, FUNCTION_NAME, ...) extern "C" GFSDK_SSAO_EXPORT RETURN_TYPE GFSDK_SSAO_CDECL FUNCTION_NAME(__VA_ARGS__)
+#endif
+
+#define GFSDK_SSAO_VERSION_ARGUMENT GFSDK_SSAO_Version HeaderVersion = GFSDK_SSAO_Version()
+#define GFSDK_SSAO_CUSTOM_HEAP_ARGUMENT const GFSDK_SSAO_CustomHeap* pCustomHeap = NULL
+
+#endif
+
+/*====================================================================================================
+ Forward declarations.
+====================================================================================================*/
+
+typedef char GLchar;
+typedef int GLint;
+typedef int GLsizei;
+typedef void GLvoid;
+typedef float GLfloat;
+typedef float GLclampf;
+typedef unsigned int GLenum;
+typedef unsigned int GLuint;
+typedef unsigned char GLboolean;
+typedef unsigned char GLubyte;
+typedef ptrdiff_t GLintptr;
+typedef ptrdiff_t GLsizeiptr;
+typedef unsigned int GFSDK_SSAO_BOOL;
+typedef unsigned int GFSDK_SSAO_UINT;
+typedef float GFSDK_SSAO_FLOAT;
+typedef size_t GFSDK_SSAO_SIZE_T;
+typedef uint64_t GFSDK_SSAO_UINT64;
+
+struct ID3D11Device;
+struct ID3D11DeviceContext;
+struct ID3D11ShaderResourceView;
+struct ID3D11BlendState;
+struct ID3D11DepthStencilState;
+struct ID3D11DepthStencilView;
+struct ID3D11RenderTargetView;
+
+struct ID3D12Device;
+struct ID3D12CommandList;
+struct ID3D12CommandQueue;
+struct ID3D12Resource;
+struct ID3D12GraphicsCommandList;
+struct ID3D12DescriptorHeap;
+struct ID3D12GraphicsCommandList;
+
+/*====================================================================================================
+ Build version.
+====================================================================================================*/
+
+struct GFSDK_SSAO_Version
+{
+ GFSDK_SSAO_Version()
+ : Major(3)
+ , Minor(0)
+ , Branch(0)
+ , Revision(0)
+ {
+ }
+
+ GFSDK_SSAO_UINT Major;
+ GFSDK_SSAO_UINT Minor;
+ GFSDK_SSAO_UINT Branch;
+ GFSDK_SSAO_UINT Revision;
+};
+
+/*====================================================================================================
+ Enums.
+====================================================================================================*/
+
+enum GFSDK_SSAO_Status
+{
+ GFSDK_SSAO_OK, // Success
+ GFSDK_SSAO_VERSION_MISMATCH, // The header version number does not match the DLL version number
+ GFSDK_SSAO_NULL_ARGUMENT, // One of the required argument pointers is NULL
+ GFSDK_SSAO_INVALID_PROJECTION_MATRIX, // The projection matrix is not valid
+ GFSDK_SSAO_INVALID_WORLD_TO_VIEW_MATRIX, // The world-to-view matrix is not valid (transposing it may help)
+ GFSDK_SSAO_INVALID_NORMAL_TEXTURE_RESOLUTION, // The normal-texture resolution does not match the depth-texture resolution
+ GFSDK_SSAO_INVALID_NORMAL_TEXTURE_SAMPLE_COUNT, // The normal-texture sample count does not match the depth-texture sample count
+ GFSDK_SSAO_INVALID_VIEWPORT_DIMENSIONS, // One of the viewport dimensions (width or height) is 0
+ GFSDK_SSAO_INVALID_VIEWPORT_DEPTH_RANGE, // The viewport depth range is not a sub-range of [0.f,1.f]
+ GFSDK_SSAO_MEMORY_ALLOCATION_FAILED, // Failed to allocate memory on the heap
+ GFSDK_SSAO_INVALID_DEPTH_STENCIL_RESOLUTION, // The depth-stencil resolution does not match the output render-target resolution
+ GFSDK_SSAO_INVALID_DEPTH_STENCIL_SAMPLE_COUNT, // The depth-stencil sample count does not match the output render-target sample count
+ //
+ // D3D-specific enums
+ //
+ GFSDK_SSAO_D3D_FEATURE_LEVEL_NOT_SUPPORTED, // The current D3D11 feature level is lower than 11_0
+ GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED, // A resource-creation call has failed (running out of memory?)
+ GFSDK_SSAO_D3D12_UNSUPPORTED_DEPTH_CLAMP_MODE, // CLAMP_TO_BORDER is used (implemented on D3D11 & GL, but not on D3D12)
+ GFSDK_SSAO_D3D12_INVALID_HEAP_TYPE, // One of the heaps provided to GFSDK_SSAO_CreateContext_D3D12 has an unexpected type
+ GFSDK_SSAO_D3D12_INSUFFICIENT_DESCRIPTORS, // One of the heaps provided to GFSDK_SSAO_CreateContext_D3D12 has insufficient descriptors
+ GFSDK_SSAO_D3D12_INVALID_NODE_MASK, // NodeMask has more than one bit set. HBAO+ only supports operation on one D3D12 device node.
+ //
+ // GL-specific enums
+ //
+ GFSDK_SSAO_GL_INVALID_TEXTURE_TARGET, // One of the input textures is not GL_TEXTURE_2D or GL_TEXTURE_2D_MULTISAMPLE
+ GFSDK_SSAO_GL_INVALID_TEXTURE_OBJECT, // One of the input texture objects has index 0
+ GFSDK_SSAO_GL_RESOURCE_CREATION_FAILED, // A GL resource-creation call has failed (running out of memory?)
+ GFSDK_SSAO_GL_NULL_FUNCTION_POINTER, // One of the provided GL function pointers is NULL
+ GFSDK_SSAO_GL_UNSUPPORTED_VIEWPORT, // A custom input viewport is enabled (not supported on GL)
+};
+
+enum GFSDK_SSAO_DepthTextureType
+{
+ GFSDK_SSAO_HARDWARE_DEPTHS, // Non-linear depths in the range [0.f,1.f]
+ GFSDK_SSAO_HARDWARE_DEPTHS_SUB_RANGE, // Non-linear depths in the range [Viewport.MinDepth,Viewport.MaxDepth]
+ GFSDK_SSAO_VIEW_DEPTHS, // Linear depths in the range [ZNear,ZFar]
+};
+
+enum GFSDK_SSAO_BlendMode
+{
+ GFSDK_SSAO_OVERWRITE_RGB, // Overwrite the destination RGB with the AO, preserving alpha
+ GFSDK_SSAO_MULTIPLY_RGB, // Multiply the AO over the destination RGB, preserving alpha
+ GFSDK_SSAO_CUSTOM_BLEND, // Composite the AO using a custom blend state
+};
+
+enum GFSDK_SSAO_DepthStencilMode
+{
+ GFSDK_SSAO_DISABLED_DEPTH_STENCIL, // Composite the AO without any depth-stencil testing
+ GFSDK_SSAO_CUSTOM_DEPTH_STENCIL, // Composite the AO with a custom depth-stencil state
+};
+
+enum GFSDK_SSAO_BlurRadius
+{
+ GFSDK_SSAO_BLUR_RADIUS_2, // Kernel radius = 2 pixels
+ GFSDK_SSAO_BLUR_RADIUS_4, // Kernel radius = 4 pixels (recommended)
+};
+
+enum GFSDK_SSAO_DepthStorage
+{
+ GFSDK_SSAO_FP16_VIEW_DEPTHS, // Store the internal view depths in FP16 (recommended)
+ GFSDK_SSAO_FP32_VIEW_DEPTHS, // Store the internal view depths in FP32 (slower)
+};
+
+enum GFSDK_SSAO_DepthClampMode
+{
+ GFSDK_SSAO_CLAMP_TO_EDGE, // Use clamp-to-edge when sampling depth (may cause false occlusion near screen borders)
+ GFSDK_SSAO_CLAMP_TO_BORDER, // Use clamp-to-border when sampling depth (may cause halos near screen borders)
+};
+
+enum GFSDK_SSAO_MatrixLayout
+{
+ GFSDK_SSAO_ROW_MAJOR_ORDER, // The matrix is stored as Row[0],Row[1],Row[2],Row[3]
+ GFSDK_SSAO_COLUMN_MAJOR_ORDER, // The matrix is stored as Col[0],Col[1],Col[2],Col[3]
+};
+
+enum GFSDK_SSAO_RenderMask
+{
+ GFSDK_SSAO_DRAW_Z = (1 << 0), // Linearize the input depths
+ GFSDK_SSAO_DRAW_AO = (1 << 1), // Render AO based on pre-linearized depths
+ GFSDK_SSAO_DRAW_DEBUG_N = (1 << 2), // Render the internal view normals (for debugging)
+ GFSDK_SSAO_DRAW_DEBUG_X = (1 << 3), // Render the X component as grayscale
+ GFSDK_SSAO_DRAW_DEBUG_Y = (1 << 4), // Render the Y component as grayscale
+ GFSDK_SSAO_DRAW_DEBUG_Z = (1 << 5), // Render the Z component as grayscale
+ GFSDK_SSAO_RENDER_AO = GFSDK_SSAO_DRAW_Z | GFSDK_SSAO_DRAW_AO,
+ GFSDK_SSAO_RENDER_DEBUG_NORMAL = GFSDK_SSAO_DRAW_Z | GFSDK_SSAO_DRAW_DEBUG_N,
+ GFSDK_SSAO_RENDER_DEBUG_NORMAL_X = GFSDK_SSAO_DRAW_Z | GFSDK_SSAO_DRAW_DEBUG_N | GFSDK_SSAO_DRAW_DEBUG_X,
+ GFSDK_SSAO_RENDER_DEBUG_NORMAL_Y = GFSDK_SSAO_DRAW_Z | GFSDK_SSAO_DRAW_DEBUG_N | GFSDK_SSAO_DRAW_DEBUG_Y,
+ GFSDK_SSAO_RENDER_DEBUG_NORMAL_Z = GFSDK_SSAO_DRAW_Z | GFSDK_SSAO_DRAW_DEBUG_N | GFSDK_SSAO_DRAW_DEBUG_Z,
+};
+
+/*====================================================================================================
+ Input/output textures.
+====================================================================================================*/
+
+struct GFSDK_SSAO_ShaderResourceView_D3D12
+{
+ GFSDK_SSAO_ShaderResourceView_D3D12()
+ : pResource(NULL)
+ , GpuHandle(0)
+ {
+ }
+ ID3D12Resource* pResource;
+ GFSDK_SSAO_UINT64 GpuHandle;
+};
+
+struct GFSDK_SSAO_RenderTargetView_D3D12
+{
+ GFSDK_SSAO_RenderTargetView_D3D12()
+ : pResource(NULL)
+ , CpuHandle(0)
+ {
+ }
+ ID3D12Resource* pResource;
+ GFSDK_SSAO_SIZE_T CpuHandle;
+};
+
+struct GFSDK_SSAO_Texture_GL
+{
+ GLenum Target; // Must be GL_TEXTURE_2D or GL_TEXTURE_2D_MULTISAMPLE
+ GLuint TextureId; // OpenGL texture object index
+
+ GFSDK_SSAO_Texture_GL()
+ : Target(0)
+ , TextureId(0)
+ {
+ }
+ GFSDK_SSAO_Texture_GL(GLenum InTarget, GLuint InTextureId)
+ : Target(InTarget)
+ , TextureId(InTextureId)
+ {
+ }
+};
+
+/*====================================================================================================
+ Input data.
+====================================================================================================*/
+
+//---------------------------------------------------------------------------------------------------
+// 4x4 Matrix.
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_Float4x4
+{
+ GFSDK_SSAO_Float4x4()
+ {
+ memset(&Array, 0, sizeof(Array));
+ }
+ GFSDK_SSAO_Float4x4(const GFSDK_SSAO_FLOAT* pMatrix)
+ {
+ memcpy(&Array, pMatrix, sizeof(Array));
+ }
+ GFSDK_SSAO_FLOAT Array[16];
+};
+
+struct GFSDK_SSAO_Matrix
+{
+ GFSDK_SSAO_Float4x4 Data; // 4x4 matrix stored as an array of 16 floats
+ GFSDK_SSAO_MatrixLayout Layout; // Memory layout of the matrix
+
+ GFSDK_SSAO_Matrix()
+ : Layout(GFSDK_SSAO_ROW_MAJOR_ORDER)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Input viewport.
+//
+// Remarks:
+// * The Viewport defines a sub-area of the input & output full-resolution textures to be sourced and rendered to.
+// Only the depth pixels within the viewport sub-area contribute to the RenderAO output.
+// * The Viewport's MinDepth and MaxDepth values are ignored except if DepthTextureType is HARDWARE_DEPTHS_SUB_RANGE.
+// * If Enable is false, a default input viewport is used with:
+// TopLeftX = 0
+// TopLeftY = 0
+// Width = InputDepthTexture.Width
+// Height = InputDepthTexture.Height
+// MinDepth = 0.f
+// MaxDepth = 1.f
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_InputViewport
+{
+ GFSDK_SSAO_BOOL Enable; // To use the provided viewport data (instead of the default viewport)
+ GFSDK_SSAO_UINT TopLeftX; // X coordinate of the top-left corner of the viewport rectangle, in pixels
+ GFSDK_SSAO_UINT TopLeftY; // Y coordinate of the top-left corner of the viewport rectangle, in pixels
+ GFSDK_SSAO_UINT Width; // The width of the viewport rectangle, in pixels
+ GFSDK_SSAO_UINT Height; // The height of the viewport rectangle, in pixels
+ GFSDK_SSAO_FLOAT MinDepth; // The minimum depth for GFSDK_SSAO_HARDWARE_DEPTHS_SUB_RANGE
+ GFSDK_SSAO_FLOAT MaxDepth; // The maximum depth for GFSDK_SSAO_HARDWARE_DEPTHS_SUB_RANGE
+
+ GFSDK_SSAO_InputViewport()
+ : Enable(false)
+ , TopLeftX(0)
+ , TopLeftY(0)
+ , Width(0)
+ , Height(0)
+ , MinDepth(0.f)
+ , MaxDepth(1.f)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// Input depth data.
+//
+// Requirements:
+// * View-space depths (linear) are required to be non-multisample.
+// * Hardware depths (non-linear) can be multisample or non-multisample.
+// * The projection matrix must have the following form, with |P23| == 1.f:
+// { P00, 0.f, 0.f, 0.f }
+// { 0.f, P11, 0.f, 0.f }
+// { P20, P21, P22, P23 }
+// { 0.f, 0.f, P32, 0.f }
+//
+// Remarks:
+// * MetersToViewSpaceUnits is used to convert the AO radius parameter from meters to view-space units,
+// as well as to convert the blur sharpness parameter from inverse meters to inverse view-space units.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_InputDepthData
+{
+ GFSDK_SSAO_DepthTextureType DepthTextureType; // HARDWARE_DEPTHS, HARDWARE_DEPTHS_SUB_RANGE or VIEW_DEPTHS
+ GFSDK_SSAO_Matrix ProjectionMatrix; // 4x4 perspective matrix from the depth generation pass
+ GFSDK_SSAO_FLOAT MetersToViewSpaceUnits; // DistanceInViewSpaceUnits = MetersToViewSpaceUnits * DistanceInMeters
+ GFSDK_SSAO_InputViewport Viewport; // Viewport from the depth generation pass
+
+ GFSDK_SSAO_InputDepthData()
+ : DepthTextureType(GFSDK_SSAO_HARDWARE_DEPTHS)
+ , MetersToViewSpaceUnits(1.f)
+ {
+ }
+};
+
+struct GFSDK_SSAO_InputDepthData_D3D12 : GFSDK_SSAO_InputDepthData
+{
+ GFSDK_SSAO_ShaderResourceView_D3D12 FullResDepthTextureSRV; // Full-resolution depth texture
+};
+
+struct GFSDK_SSAO_InputDepthData_D3D11 : GFSDK_SSAO_InputDepthData
+{
+ ID3D11ShaderResourceView* pFullResDepthTextureSRV; // Full-resolution depth texture
+
+ GFSDK_SSAO_InputDepthData_D3D11()
+ : pFullResDepthTextureSRV(NULL)
+ {
+ }
+};
+
+struct GFSDK_SSAO_InputDepthData_GL : GFSDK_SSAO_InputDepthData
+{
+ GFSDK_SSAO_Texture_GL FullResDepthTexture; // Full-resolution depth texture
+};
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Input normal data.
+//
+// Requirements:
+// * The normal texture is required to contain world-space normals in RGB.
+// * The normal texture must have the same resolution and MSAA sample count as the input depth texture.
+// * The view-space Y & Z axis are assumed to be pointing up & forward respectively (left-handed projection).
+// * The WorldToView matrix is assumed to not contain any non-uniform scaling.
+// * The WorldView matrix must have the following form:
+// { M00, M01, M02, 0.f }
+// { M10, M11, M12, 0.f }
+// { M20, M21, M22, 0.f }
+// { M30, M31, M32, M33 }
+//
+// Remarks:
+// * The actual view-space normal used for the AO rendering is:
+// N = normalize( mul( FetchedNormal.xyz * DecodeScale + DecodeBias, (float3x3)WorldToViewMatrix ) )
+// * Using bent normals as input may result in false-occlusion (overdarkening) artifacts.
+// Such artifacts may be alleviated by increasing the AO Bias parameter.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_InputNormalData
+{
+ GFSDK_SSAO_BOOL Enable; // To use the provided normals (instead of reconstructed ones)
+ GFSDK_SSAO_Matrix WorldToViewMatrix; // 4x4 WorldToView matrix from the depth generation pass
+ GFSDK_SSAO_FLOAT DecodeScale; // Optional pre-matrix scale
+ GFSDK_SSAO_FLOAT DecodeBias; // Optional pre-matrix bias
+
+ GFSDK_SSAO_InputNormalData()
+ : Enable(false)
+ , DecodeScale(1.f)
+ , DecodeBias(0.f)
+ {
+ }
+};
+
+struct GFSDK_SSAO_InputNormalData_D3D12 : GFSDK_SSAO_InputNormalData
+{
+ GFSDK_SSAO_ShaderResourceView_D3D12 FullResNormalTextureSRV; // Full-resolution world-space normal texture
+};
+
+struct GFSDK_SSAO_InputNormalData_D3D11 : GFSDK_SSAO_InputNormalData
+{
+ ID3D11ShaderResourceView* pFullResNormalTextureSRV; // Full-resolution world-space normal texture
+
+ GFSDK_SSAO_InputNormalData_D3D11()
+ : pFullResNormalTextureSRV(NULL)
+ {
+ }
+};
+
+struct GFSDK_SSAO_InputNormalData_GL : GFSDK_SSAO_InputNormalData
+{
+ GFSDK_SSAO_Texture_GL FullResNormalTexture; // Full-resolution world-space normal texture
+};
+
+//---------------------------------------------------------------------------------------------------
+// Input data.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_InputData_D3D12
+{
+ GFSDK_SSAO_InputDepthData_D3D12 DepthData; // Required
+ GFSDK_SSAO_InputNormalData_D3D12 NormalData; // Optional GBuffer normals
+};
+
+struct GFSDK_SSAO_InputData_D3D11
+{
+ GFSDK_SSAO_InputDepthData_D3D11 DepthData; // Required
+ GFSDK_SSAO_InputNormalData_D3D11 NormalData; // Optional GBuffer normals
+};
+
+struct GFSDK_SSAO_InputData_GL
+{
+ GFSDK_SSAO_InputDepthData_GL DepthData; // Required
+ GFSDK_SSAO_InputNormalData_GL NormalData; // Optional GBuffer normals
+};
+
+/*====================================================================================================
+ Parameters.
+====================================================================================================*/
+
+//---------------------------------------------------------------------------------------------------
+// When enabled, the screen-space AO kernel radius is:
+// - inversely proportional to ViewDepth for ViewDepth > ForegroundViewDepth
+// - uniform in screen-space for ViewDepth <= ForegroundViewDepth
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_ForegroundAO
+{
+ GFSDK_SSAO_BOOL Enable; // Enabling this may have a small performance impact
+ GFSDK_SSAO_FLOAT ForegroundViewDepth; // View-space depth at which the AO footprint should get clamped
+
+ GFSDK_SSAO_ForegroundAO()
+ : Enable(false)
+ , ForegroundViewDepth(0.f)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// When enabled, the screen-space AO kernel radius is:
+// - inversely proportional to ViewDepth for ViewDepth < BackgroundViewDepth
+// - uniform in screen-space for ViewDepth >= BackgroundViewDepth (instead of falling off to zero)
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_BackgroundAO
+{
+ GFSDK_SSAO_BOOL Enable; // Enabling this may have a small performance impact
+ GFSDK_SSAO_FLOAT BackgroundViewDepth; // View-space depth at which the AO footprint should stop falling off with depth
+
+ GFSDK_SSAO_BackgroundAO()
+ : Enable(false)
+ , BackgroundViewDepth(0.f)
+ {
+ }
+};
+
+struct GFSDK_SSAO_DepthThreshold
+{
+ GFSDK_SSAO_BOOL Enable; // To return white AO for ViewDepths > MaxViewDepth
+ GFSDK_SSAO_FLOAT MaxViewDepth; // Custom view-depth threshold
+ GFSDK_SSAO_FLOAT Sharpness; // The higher, the sharper are the AO-to-white transitions
+
+ GFSDK_SSAO_DepthThreshold()
+ : Enable(false)
+ , MaxViewDepth(0.f)
+ , Sharpness(100.f)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// When enabled, the actual per-pixel blur sharpness value depends on the per-pixel view depth with:
+// LerpFactor = (PixelViewDepth - ForegroundViewDepth) / (BackgroundViewDepth - ForegroundViewDepth)
+// Sharpness = lerp(Sharpness*ForegroundSharpnessScale, Sharpness, saturate(LerpFactor))
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_BlurSharpnessProfile
+{
+ GFSDK_SSAO_BOOL Enable; // To make the blur sharper in the foreground
+ GFSDK_SSAO_FLOAT ForegroundSharpnessScale; // Sharpness scale factor for ViewDepths <= ForegroundViewDepth
+ GFSDK_SSAO_FLOAT ForegroundViewDepth; // Maximum view depth of the foreground depth range
+ GFSDK_SSAO_FLOAT BackgroundViewDepth; // Minimum view depth of the background depth range
+
+ GFSDK_SSAO_BlurSharpnessProfile ()
+ : Enable(false)
+ , ForegroundSharpnessScale(4.f)
+ , ForegroundViewDepth(0.f)
+ , BackgroundViewDepth(1.f)
+ {
+ }
+};
+
+struct GFSDK_SSAO_BlurParameters
+{
+ GFSDK_SSAO_BOOL Enable; // To blur the AO with an edge-preserving blur
+ GFSDK_SSAO_BlurRadius Radius; // BLUR_RADIUS_2 or BLUR_RADIUS_4
+ GFSDK_SSAO_FLOAT Sharpness; // The higher, the more the blur preserves edges // 0.0~16.0
+ GFSDK_SSAO_BlurSharpnessProfile SharpnessProfile; // Optional depth-dependent sharpness function
+
+ GFSDK_SSAO_BlurParameters()
+ : Enable(true)
+ , Radius(GFSDK_SSAO_BLUR_RADIUS_4)
+ , Sharpness(16.f)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// Remarks:
+// * The final occlusion is a weighted sum of 2 occlusion contributions. The NearAO and FarAO parameters are the weights.
+// * Setting the DepthStorage parameter to FP16_VIEW_DEPTHS is fastest but may introduce minor false-occlusion artifacts for large depths.
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_Parameters
+{
+ GFSDK_SSAO_FLOAT Radius; // The AO radius in meters
+ GFSDK_SSAO_FLOAT Bias; // To hide low-tessellation artifacts // 0.0~0.5
+ GFSDK_SSAO_FLOAT NearAO; // Scale factor for the near-range AO, the greater the darker // 1.0~4.0
+ GFSDK_SSAO_FLOAT FarAO; // Scale factor for the far-range AO, the greater the darker // 1.0~4.0
+ GFSDK_SSAO_FLOAT PowerExponent; // The final AO output is pow(AO, powerExponent) // 1.0~8.0
+ GFSDK_SSAO_ForegroundAO ForegroundAO; // To limit the occlusion scale in the foreground
+ GFSDK_SSAO_BackgroundAO BackgroundAO; // To add larger-scale occlusion in the distance
+ GFSDK_SSAO_DepthStorage DepthStorage; // Quality / performance tradeoff
+ GFSDK_SSAO_DepthClampMode DepthClampMode; // To hide possible false-occlusion artifacts near screen borders
+ GFSDK_SSAO_DepthThreshold DepthThreshold; // Optional Z threshold, to hide possible depth-precision artifacts
+ GFSDK_SSAO_BlurParameters Blur; // Optional AO blur, to blur the AO before compositing it
+
+ GFSDK_SSAO_Parameters()
+ : Radius(1.f)
+ , Bias(0.1f)
+ , NearAO(2.f)
+ , FarAO(1.f)
+ , PowerExponent(2.f)
+ , DepthStorage(GFSDK_SSAO_FP16_VIEW_DEPTHS)
+ , DepthClampMode(GFSDK_SSAO_CLAMP_TO_EDGE)
+ {
+ }
+};
+
+/*====================================================================================================
+ Output.
+====================================================================================================*/
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Custom blend state.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_CustomBlendState_D3D12
+{
+ struct D3D12_BLEND_DESC* pBlendState;
+ const GFSDK_SSAO_FLOAT* pBlendFactor;
+
+ GFSDK_SSAO_CustomBlendState_D3D12()
+ : pBlendState(NULL)
+ , pBlendFactor(NULL)
+ {
+ }
+};
+
+struct GFSDK_SSAO_CustomBlendState_D3D11
+{
+ ID3D11BlendState* pBlendState;
+ const GFSDK_SSAO_FLOAT* pBlendFactor;
+
+ GFSDK_SSAO_CustomBlendState_D3D11()
+ : pBlendState(NULL)
+ , pBlendFactor(NULL)
+ {
+ }
+};
+
+struct GFSDK_SSAO_CustomBlendState_GL
+{
+ struct
+ {
+ GLenum ModeRGB;
+ GLenum ModeAlpha;
+ } BlendEquationSeparate;
+
+ struct
+ {
+ GLenum SrcRGB;
+ GLenum DstRGB;
+ GLenum SrcAlpha;
+ GLenum DstAlpha;
+ } BlendFuncSeparate;
+
+ struct
+ {
+ GLclampf R;
+ GLclampf G;
+ GLclampf B;
+ GLclampf A;
+ } BlendColor;
+
+ struct
+ {
+ GLboolean R;
+ GLboolean G;
+ GLboolean B;
+ GLboolean A;
+ } ColorMask;
+
+ GFSDK_SSAO_CustomBlendState_GL()
+ {
+ memset(this, 0, sizeof(*this));
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// Compositing blend state.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_BlendState_D3D12
+{
+ GFSDK_SSAO_BlendMode Mode; // OVERWRITE_RGB, MULTIPLY_RGB or CUSTOM_BLEND
+ GFSDK_SSAO_CustomBlendState_D3D12 CustomState; // Relevant only if Mode is CUSTOM_BLEND
+
+ GFSDK_SSAO_BlendState_D3D12()
+ : Mode(GFSDK_SSAO_OVERWRITE_RGB)
+ {
+ }
+};
+
+struct GFSDK_SSAO_BlendState_D3D11
+{
+ GFSDK_SSAO_BlendMode Mode; // OVERWRITE_RGB, MULTIPLY_RGB or CUSTOM_BLEND
+ GFSDK_SSAO_CustomBlendState_D3D11 CustomState; // Relevant only if Mode is CUSTOM_BLEND
+
+ GFSDK_SSAO_BlendState_D3D11()
+ : Mode(GFSDK_SSAO_OVERWRITE_RGB)
+ {
+ }
+};
+
+struct GFSDK_SSAO_BlendState_GL
+{
+ GFSDK_SSAO_BlendMode Mode; // OVERWRITE_RGB, MULTIPLY_RGB or CUSTOM_BLEND
+ GFSDK_SSAO_CustomBlendState_GL CustomState; // Relevant only if Mode is CUSTOM_BLEND
+
+ GFSDK_SSAO_BlendState_GL()
+ : Mode(GFSDK_SSAO_OVERWRITE_RGB)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Custom depth-stencil state.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_CustomDepthStencilState_D3D11
+{
+ ID3D11DepthStencilState* pDepthStencilState;
+ GFSDK_SSAO_UINT StencilRef;
+
+ GFSDK_SSAO_CustomDepthStencilState_D3D11()
+ : pDepthStencilState(NULL)
+ , StencilRef(0)
+ {
+ }
+};
+
+struct GFSDK_SSAO_DepthStencilState_D3D11
+{
+ GFSDK_SSAO_DepthStencilMode Mode; // DISABLED_DEPTH_STENCIL or CUSTOM_DEPTH_STENCIL
+ GFSDK_SSAO_CustomDepthStencilState_D3D11 CustomState; // Relevant only if Mode is CUSTOM_DEPTH_STENCIL
+
+ GFSDK_SSAO_DepthStencilState_D3D11()
+ : Mode(GFSDK_SSAO_DISABLED_DEPTH_STENCIL)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Two-pass AO compositing.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_BlendPass_D3D11
+{
+ GFSDK_SSAO_BlendState_D3D11 Blend;
+ GFSDK_SSAO_DepthStencilState_D3D11 DepthStencil;
+};
+
+//---------------------------------------------------------------------------------------------------
+// Remarks:
+// * This can be useful to use different blend states depending on the stencil value.
+// * For instance: 1) for character pixels (with Stencil==A), write AO with blending disabled,
+// 2) for other pixels (with Stencil!=A), write AO with MIN blending.
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_TwoPassBlend_D3D11
+{
+ GFSDK_SSAO_BOOL Enable; // When enabled, overrides any other compositing state
+ ID3D11DepthStencilView* pDepthStencilView; // Used to mask the pixels in each of the 2 passses
+ GFSDK_SSAO_BlendPass_D3D11 FirstPass; // Blend & depth-stencil state for the first compositing pass
+ GFSDK_SSAO_BlendPass_D3D11 SecondPass; // Blend & depth-stencil state for the second compositing pass
+
+ GFSDK_SSAO_TwoPassBlend_D3D11()
+ : Enable(false)
+ , pDepthStencilView(NULL)
+ {
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// Output render target & compositing state.
+//---------------------------------------------------------------------------------------------------
+
+struct GFSDK_SSAO_Output_D3D12
+{
+ GFSDK_SSAO_RenderTargetView_D3D12* pRenderTargetView; // Output render target of RenderAO
+ GFSDK_SSAO_BlendState_D3D12 Blend; // Blend state used when writing the AO to pRenderTargetView
+
+ GFSDK_SSAO_Output_D3D12()
+ : pRenderTargetView(NULL)
+ {
+ }
+};
+
+struct GFSDK_SSAO_Output_D3D11
+{
+ ID3D11RenderTargetView* pRenderTargetView; // Output render target of RenderAO
+ GFSDK_SSAO_BlendState_D3D11 Blend; // Blend state used when writing the AO to pRenderTargetView
+ GFSDK_SSAO_TwoPassBlend_D3D11 TwoPassBlend; // Optional two-pass compositing using depth-stencil masking
+
+ GFSDK_SSAO_Output_D3D11()
+ : pRenderTargetView(NULL)
+ {
+ }
+};
+
+struct GFSDK_SSAO_Output_GL
+{
+ GLuint OutputFBO; // Output Frame Buffer Object of RenderAO
+ GFSDK_SSAO_BlendState_GL Blend; // Blend state used when writing the AO to OutputFBO
+
+ GFSDK_SSAO_Output_GL()
+ : OutputFBO(0)
+ {
+ }
+};
+
+/*====================================================================================================
+ [Optional] Let the library allocate its memory on a custom heap.
+====================================================================================================*/
+
+struct GFSDK_SSAO_CustomHeap
+{
+ GFSDK_SSAO_CustomHeap()
+ : new_(NULL)
+ , delete_(NULL)
+ {
+ }
+ void* (*new_)(size_t);
+ void (*delete_)(void*);
+};
+
+/*====================================================================================================
+ [Optional] For debugging any issues with the input projection matrix.
+====================================================================================================*/
+
+struct GFSDK_SSAO_ProjectionMatrixDepthRange
+{
+ GFSDK_SSAO_ProjectionMatrixDepthRange()
+ : ZNear(-1.f)
+ , ZFar(-1.f)
+ {
+ }
+ GFSDK_SSAO_FLOAT ZNear;
+ GFSDK_SSAO_FLOAT ZFar;
+};
+
+/*====================================================================================================
+ Base interface.
+====================================================================================================*/
+
+class GFSDK_SSAO_Context
+{
+public:
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Returns the amount of video memory allocated by the library, in bytes.
+//---------------------------------------------------------------------------------------------------
+virtual GFSDK_SSAO_UINT GetAllocatedVideoMemoryBytes() = 0;
+
+}; //class GFSDK_SSAO_Context
+
+//---------------------------------------------------------------------------------------------------
+// [Optional] Returns the DLL version information.
+//---------------------------------------------------------------------------------------------------
+GFSDK_SSAO_DECL(GFSDK_SSAO_Status, GFSDK_SSAO_GetVersion, GFSDK_SSAO_Version* pVersion);
+
+/*====================================================================================================
+ D3D11 interface.
+====================================================================================================*/
+
+//---------------------------------------------------------------------------------------------------
+// Note: The RenderAO, PreCreateRTs and Release entry points should not be called simultaneously from different threads.
+//---------------------------------------------------------------------------------------------------
+class GFSDK_SSAO_Context_D3D11 : public GFSDK_SSAO_Context
+{
+public:
+
+ //---------------------------------------------------------------------------------------------------
+ // Renders SSAO.
+ //
+ // Remarks:
+ // * Allocates internal D3D render targets on first use, and re-allocates them when the viewport dimensions change.
+ // * All the relevant device-context states are saved and restored internally when entering and exiting the call.
+ // * Setting RenderMask = GFSDK_SSAO_RENDER_DEBUG_NORMAL_Z can be useful to visualize the normals used for the AO rendering.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_INVALID_PROJECTION_MATRIX - The projection matrix is not valid
+ // GFSDK_SSAO_INVALID_VIEWPORT_DIMENSIONS - One of the viewport dimensions (width or height) is 0
+ // GFSDK_SSAO_INVALID_VIEWPORT_DEPTH_RANGE - The viewport depth range is not a sub-range of [0.f,1.f]
+ // GFSDK_SSAO_INVALID_WORLD_TO_VIEW_MATRIX - The world-to-view matrix is not valid (transposing it may help)
+ // GFSDK_SSAO_INVALID_NORMAL_TEXTURE_RESOLUTION - The normal-texture resolution does not match the depth-texture resolution
+ // GFSDK_SSAO_INVALID_NORMAL_TEXTURE_SAMPLE_COUNT - The normal-texture sample count does not match the depth-texture sample count
+ // GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED - A D3D resource-creation call has failed (running out of memory?)
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status RenderAO(
+ ID3D11DeviceContext* pDeviceContext,
+ const GFSDK_SSAO_InputData_D3D11& InputData,
+ const GFSDK_SSAO_Parameters& Parameters,
+ const GFSDK_SSAO_Output_D3D11& Output,
+ GFSDK_SSAO_RenderMask RenderMask = GFSDK_SSAO_RENDER_AO) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // [Optional] Pre-creates all internal render targets for RenderAO.
+ //
+ // Remarks:
+ // * This call may be safely skipped since RenderAO creates its render targets on demand if they were not pre-created.
+ // * This call releases and re-creates the internal render targets if the provided resolution changes.
+ // * This call performs CreateTexture calls for all the relevant render targets.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED - A D3D resource-creation call has failed (running out of memory?)
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status PreCreateRTs(
+ const GFSDK_SSAO_Parameters& Parameters,
+ GFSDK_SSAO_UINT ViewportWidth,
+ GFSDK_SSAO_UINT ViewportHeight) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // [Optional] Gets the library-internal ZNear and ZFar values derived from the input projection matrix.
+ //
+ // Remarks:
+ // * HBAO+ supports all perspective projection matrices, with arbitrary ZNear and ZFar.
+ // * For reverse infinite projections, GetProjectionMatrixDepthRange should return ZNear=+INF and ZFar=0.f.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_INVALID_PROJECTION_MATRIX - The projection matrix is not valid
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status GetProjectionMatrixDepthRange(
+ const GFSDK_SSAO_InputData_D3D11& InputData,
+ GFSDK_SSAO_ProjectionMatrixDepthRange& OutputDepthRange) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // Releases all D3D objects created by the library (to be called right before releasing the D3D device).
+ //---------------------------------------------------------------------------------------------------
+ virtual void Release() = 0;
+
+}; //class GFSDK_SSAO_Context_D3D11
+
+//---------------------------------------------------------------------------------------------------
+// Creates a GFSDK_SSAO_Context associated with the D3D11 device.
+//
+// Remarks:
+// * Allocates D3D11 resources internally.
+// * Allocates memory using the default "::operator new", or "pCustomHeap->new_" if provided.
+//
+// Returns:
+// GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+// GFSDK_SSAO_VERSION_MISMATCH - Invalid HeaderVersion (have you set HeaderVersion = GFSDK_SSAO_Version()?)
+// GFSDK_SSAO_MEMORY_ALLOCATION_FAILED - Failed to allocate memory on the heap
+// GFSDK_SSAO_D3D_FEATURE_LEVEL_NOT_SUPPORTED - The D3D feature level of pD3DDevice is lower than 11_0
+// GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED - A resource-creation call has failed (running out of memory?)
+// GFSDK_SSAO_OK - Success
+//---------------------------------------------------------------------------------------------------
+GFSDK_SSAO_DECL(GFSDK_SSAO_Status, GFSDK_SSAO_CreateContext_D3D11,
+ ID3D11Device* pD3DDevice,
+ GFSDK_SSAO_Context_D3D11** ppContext,
+ GFSDK_SSAO_CUSTOM_HEAP_ARGUMENT,
+ GFSDK_SSAO_VERSION_ARGUMENT);
+
+/*====================================================================================================
+ GL interface.
+====================================================================================================*/
+
+//---------------------------------------------------------------------------------------------------
+// Note: The RenderAO, PreCreateFBOs and Release entry points should not be called simultaneously from different threads.
+//---------------------------------------------------------------------------------------------------
+class GFSDK_SSAO_Context_GL : public GFSDK_SSAO_Context
+{
+public:
+
+ //---------------------------------------------------------------------------------------------------
+ // Renders SSAO.
+ //
+ // Remarks:
+ // * Allocates internal GL framebuffer objects on first use, and re-allocates them when the depth-texture resolution changes.
+ // * All the relevant GL states are saved and restored internally when entering and exiting the call.
+ // * Setting RenderMask = GFSDK_SSAO_RENDER_DEBUG_NORMAL_Z can be useful to visualize the normals used for the AO rendering.
+ // * The current GL PolygonMode is assumed to be GL_FILL.
+ // * The OutputFBO cannot contain a texture bound in InputData.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_INVALID_PROJECTION_MATRIX - The projection matrix is not valid
+ // GFSDK_SSAO_INVALID_VIEWPORT_DEPTH_RANGE - The viewport depth range is not a sub-range of [0.f,1.f]
+ // GFSDK_SSAO_GL_INVALID_TEXTURE_TARGET - One of the input textures is not GL_TEXTURE_2D or GL_TEXTURE_2D_MULTISAMPLE
+ // GFSDK_SSAO_GL_INVALID_TEXTURE_OBJECT - One of the input texture objects has index 0
+ // GFSDK_SSAO_GL_RESOURCE_CREATION_FAILED - A GL resource-creation call has failed (running out of memory?)
+ // GFSDK_SSAO_GL_UNSUPPORTED_VIEWPORT - A custom input viewport is enabled (not supported on GL)
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status RenderAO(
+ const GFSDK_SSAO_InputData_GL& InputData,
+ const GFSDK_SSAO_Parameters& Parameters,
+ const GFSDK_SSAO_Output_GL& Output,
+ GFSDK_SSAO_RenderMask RenderMask = GFSDK_SSAO_RENDER_AO) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // [Optional] Pre-creates all internal FBOs for RenderAO.
+ //
+ // Remarks:
+ // * This call may be safely skipped since RenderAO creates its framebuffer objects on demand if they were not pre-created.
+ // * This call releases and re-creates the internal framebuffer objects if the provided resolution changes.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_GL_RESOURCE_CREATION_FAILED - A GL resource-creation call has failed (running out of memory?)
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status PreCreateFBOs(
+ const GFSDK_SSAO_Parameters& Parameters,
+ GFSDK_SSAO_UINT ViewportWidth,
+ GFSDK_SSAO_UINT ViewportHeight) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // [Optional] Gets the library-internal ZNear and ZFar values derived from the input projection matrix.
+ //
+ // Remarks:
+ // * HBAO+ supports all perspective projection matrices, with arbitrary ZNear and ZFar.
+ // * For reverse infinite projections, GetProjectionMatrixDepthRange should return ZNear=+INF and ZFar=0.f.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_INVALID_PROJECTION_MATRIX - The projection matrix is not valid
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status GetProjectionMatrixDepthRange(
+ const GFSDK_SSAO_InputData_GL& InputData,
+ GFSDK_SSAO_ProjectionMatrixDepthRange& OutputDepthRange) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // Releases all GL resources created by the library.
+ //---------------------------------------------------------------------------------------------------
+ virtual void Release() = 0;
+
+}; // class GFSDK_SSAO_Context_GL
+
+//---------------------------------------------------------------------------------------------------
+// GL functions used by the GL context, in alphabetic order.
+// Requires GL 3.2 (Core Profile) or above.
+//---------------------------------------------------------------------------------------------------
+struct GFSDK_SSAO_GLFunctions
+{
+ void (GFSDK_SSAO_STDCALL* glActiveTexture) (GLenum texture);
+ void (GFSDK_SSAO_STDCALL* glAttachShader) (GLuint program, GLuint shader);
+ void (GFSDK_SSAO_STDCALL* glBindBuffer) (GLenum target, GLuint buffer);
+ void (GFSDK_SSAO_STDCALL* glBindBufferBase) (GLenum target, GLuint index, GLuint buffer);
+ void (GFSDK_SSAO_STDCALL* glBindFramebuffer) (GLenum target, GLuint framebuffer);
+ void (GFSDK_SSAO_STDCALL* glBindFragDataLocation) (GLuint, GLuint, const GLchar*);
+ void (GFSDK_SSAO_STDCALL* glBindTexture) (GLenum target, GLuint texture);
+ void (GFSDK_SSAO_STDCALL* glBindVertexArray) (GLuint array);
+ void (GFSDK_SSAO_STDCALL* glBlendColor) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+ void (GFSDK_SSAO_STDCALL* glBlendEquationSeparate) (GLenum modeRGB, GLenum modeAlpha);
+ void (GFSDK_SSAO_STDCALL* glBlendFuncSeparate) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+ void (GFSDK_SSAO_STDCALL* glBufferData) (GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage);
+ void (GFSDK_SSAO_STDCALL* glBufferSubData) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+ void (GFSDK_SSAO_STDCALL* glColorMaski) (GLuint, GLboolean, GLboolean, GLboolean, GLboolean);
+ void (GFSDK_SSAO_STDCALL* glCompileShader) (GLuint shader);
+ GLuint (GFSDK_SSAO_STDCALL* glCreateShader) (GLenum type);
+ GLuint (GFSDK_SSAO_STDCALL* glCreateProgram) (void);
+ void (GFSDK_SSAO_STDCALL* glDeleteBuffers) (GLsizei n, const GLuint* buffers);
+ void (GFSDK_SSAO_STDCALL* glDeleteFramebuffers) (GLsizei n, const GLuint* framebuffers);
+ void (GFSDK_SSAO_STDCALL* glDeleteProgram) (GLuint program);
+ void (GFSDK_SSAO_STDCALL* glDeleteShader) (GLuint shader);
+ void (GFSDK_SSAO_STDCALL* glDeleteTextures) (GLsizei n, const GLuint *textures);
+ void (GFSDK_SSAO_STDCALL* glDeleteVertexArrays) (GLsizei n, const GLuint* arrays);
+ void (GFSDK_SSAO_STDCALL* glDisable) (GLenum cap);
+ void (GFSDK_SSAO_STDCALL* glDrawBuffers) (GLsizei n, const GLenum* bufs);
+ void (GFSDK_SSAO_STDCALL* glEnable) (GLenum cap);
+ void (GFSDK_SSAO_STDCALL* glDrawArrays) (GLenum mode, GLint first, GLsizei count);
+ void (GFSDK_SSAO_STDCALL* glFramebufferTexture) (GLenum, GLenum, GLuint, GLint);
+ void (GFSDK_SSAO_STDCALL* glFramebufferTexture2D) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+ void (GFSDK_SSAO_STDCALL* glFramebufferTextureLayer) (GLenum target,GLenum attachment, GLuint texture,GLint level,GLint layer);
+ void (GFSDK_SSAO_STDCALL* glGenBuffers) (GLsizei n, GLuint* buffers);
+ void (GFSDK_SSAO_STDCALL* glGenFramebuffers) (GLsizei n, GLuint* framebuffers);
+ void (GFSDK_SSAO_STDCALL* glGenTextures) (GLsizei n, GLuint *textures);
+ void (GFSDK_SSAO_STDCALL* glGenVertexArrays) (GLsizei n, GLuint* arrays);
+ GLenum (GFSDK_SSAO_STDCALL* glGetError) (void);
+ void (GFSDK_SSAO_STDCALL* glGetBooleani_v) (GLenum, GLuint, GLboolean*);
+ void (GFSDK_SSAO_STDCALL* glGetFloatv) (GLenum pname, GLfloat *params);
+ void (GFSDK_SSAO_STDCALL* glGetIntegerv) (GLenum pname, GLint *params);
+ void (GFSDK_SSAO_STDCALL* glGetIntegeri_v) (GLenum target, GLuint index, GLint* data);
+ void (GFSDK_SSAO_STDCALL* glGetProgramiv) (GLuint program, GLenum pname, GLint* param);
+ void (GFSDK_SSAO_STDCALL* glGetProgramInfoLog) (GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog);
+ void (GFSDK_SSAO_STDCALL* glGetShaderiv) (GLuint shader, GLenum pname, GLint* param);
+ void (GFSDK_SSAO_STDCALL* glGetShaderInfoLog) (GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog);
+ const GLubyte* (GFSDK_SSAO_STDCALL* glGetString) (GLenum name);
+ GLuint (GFSDK_SSAO_STDCALL* glGetUniformBlockIndex) (GLuint program, const GLchar* uniformBlockName);
+ GLint (GFSDK_SSAO_STDCALL* glGetUniformLocation) (GLuint program, const GLchar* name);
+ void (GFSDK_SSAO_STDCALL* glGetTexLevelParameteriv) (GLenum target, GLint level, GLenum pname, GLint *params);
+ GLboolean (GFSDK_SSAO_STDCALL* glIsEnabled) (GLenum cap);
+ GLboolean (GFSDK_SSAO_STDCALL* glIsEnabledi) (GLenum, GLuint);
+ void (GFSDK_SSAO_STDCALL* glLinkProgram) (GLuint program);
+ void (GFSDK_SSAO_STDCALL* glPolygonOffset) (GLfloat factor, GLfloat units);
+ void (GFSDK_SSAO_STDCALL* glShaderSource) (GLuint shader, GLsizei count, const GLchar* const* strings, const GLint* lengths);
+ void (GFSDK_SSAO_STDCALL* glTexImage2D) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+ void (GFSDK_SSAO_STDCALL* glTexImage3D) (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+ void (GFSDK_SSAO_STDCALL* glTexParameteri) (GLenum target, GLenum pname, GLint param);
+ void (GFSDK_SSAO_STDCALL* glTexParameterfv) (GLenum target, GLenum pname, const GLfloat *params);
+ void (GFSDK_SSAO_STDCALL* glUniform1i) (GLint location, GLint v0);
+ void (GFSDK_SSAO_STDCALL* glUniformBlockBinding) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+ void (GFSDK_SSAO_STDCALL* glUseProgram) (GLuint program);
+ void (GFSDK_SSAO_STDCALL* glViewport) (GLint x, GLint y, GLsizei width, GLsizei height);
+ typedef void (GFSDK_SSAO_STDCALL* glShaderSourceGLESType) (GLuint shader, GLsizei count, const GLchar* const* strings, const GLint* lengths);
+
+ GFSDK_SSAO_GLFunctions()
+ {
+ memset(this, 0, sizeof(*this));
+ }
+};
+
+//---------------------------------------------------------------------------------------------------
+// Helper macro to initialize all the GL function pointers.
+//---------------------------------------------------------------------------------------------------
+#define GFSDK_SSAO_INIT_GL_FUNCTIONS(GL)\
+{\
+ GL.glActiveTexture = glActiveTexture;\
+ GL.glAttachShader = glAttachShader;\
+ GL.glBindBuffer = glBindBuffer;\
+ GL.glBindBufferBase = glBindBufferBase;\
+ GL.glBindFramebuffer = glBindFramebuffer;\
+ GL.glBindFragDataLocation = glBindFragDataLocation;\
+ GL.glBindTexture = glBindTexture;\
+ GL.glBindVertexArray = glBindVertexArray;\
+ GL.glBlendColor = glBlendColor;\
+ GL.glBlendEquationSeparate = glBlendEquationSeparate;\
+ GL.glBlendFuncSeparate = glBlendFuncSeparate;\
+ GL.glBufferData = glBufferData;\
+ GL.glBufferSubData = glBufferSubData;\
+ GL.glColorMaski = glColorMaski;\
+ GL.glCompileShader = glCompileShader;\
+ GL.glCreateShader = glCreateShader;\
+ GL.glCreateProgram = glCreateProgram;\
+ GL.glDeleteBuffers = glDeleteBuffers;\
+ GL.glDeleteFramebuffers = glDeleteFramebuffers;\
+ GL.glDeleteProgram = glDeleteProgram;\
+ GL.glDeleteShader = glDeleteShader;\
+ GL.glDeleteTextures = glDeleteTextures;\
+ GL.glDeleteVertexArrays = glDeleteVertexArrays;\
+ GL.glDisable = glDisable;\
+ GL.glDrawBuffers = glDrawBuffers;\
+ GL.glEnable = glEnable;\
+ GL.glDrawArrays = glDrawArrays;\
+ GL.glFramebufferTexture = glFramebufferTexture;\
+ GL.glFramebufferTexture2D = glFramebufferTexture2D;\
+ GL.glFramebufferTextureLayer = glFramebufferTextureLayer;\
+ GL.glGenBuffers = glGenBuffers;\
+ GL.glGenFramebuffers = glGenFramebuffers;\
+ GL.glGenTextures = glGenTextures;\
+ GL.glGenVertexArrays = glGenVertexArrays;\
+ GL.glGetError = glGetError;\
+ GL.glGetBooleani_v = glGetBooleani_v;\
+ GL.glGetFloatv = glGetFloatv;\
+ GL.glGetIntegerv = glGetIntegerv;\
+ GL.glGetIntegeri_v = glGetIntegeri_v;\
+ GL.glGetProgramiv = glGetProgramiv;\
+ GL.glGetProgramInfoLog = glGetProgramInfoLog;\
+ GL.glGetShaderiv = glGetShaderiv;\
+ GL.glGetShaderInfoLog = glGetShaderInfoLog;\
+ GL.glGetString = glGetString;\
+ GL.glGetUniformBlockIndex = glGetUniformBlockIndex;\
+ GL.glGetUniformLocation = glGetUniformLocation;\
+ GL.glGetTexLevelParameteriv = glGetTexLevelParameteriv;\
+ GL.glIsEnabled = glIsEnabled;\
+ GL.glIsEnabledi = glIsEnabledi;\
+ GL.glLinkProgram = glLinkProgram;\
+ GL.glPolygonOffset = glPolygonOffset;\
+ GL.glShaderSource = (GFSDK_SSAO_GLFunctions::glShaderSourceGLESType)glShaderSource;\
+ GL.glTexImage2D = glTexImage2D;\
+ GL.glTexImage3D = glTexImage3D;\
+ GL.glTexParameteri = glTexParameteri;\
+ GL.glTexParameterfv = glTexParameterfv;\
+ GL.glUniform1i = glUniform1i;\
+ GL.glUniformBlockBinding = glUniformBlockBinding;\
+ GL.glUseProgram = glUseProgram;\
+ GL.glViewport = glViewport;\
+}
+
+//---------------------------------------------------------------------------------------------------
+// Creates a GFSDK_SSAO_Context_GL associated with the current GL context.
+//
+// Remarks:
+// * Requires GL Core 3.2 or above.
+// * Allocates GL resources internally.
+// * Allocates memory using the default "::operator new", or "pCustomHeap->new_" if provided.
+//
+// Returns:
+// GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+// GFSDK_SSAO_VERSION_MISMATCH - Invalid HeaderVersion (have you set HeaderVersion = GFSDK_SSAO_Version()?)
+// GFSDK_SSAO_GL_RESOURCE_CREATION_FAILED - A GL resource-creation call has failed (running out of memory?)
+// GFSDK_SSAO_GL_NULL_FUNCTION_POINTER, - One of the provided GL function pointers is NULL
+// GFSDK_SSAO_OK - Success
+//---------------------------------------------------------------------------------------------------
+GFSDK_SSAO_DECL(GFSDK_SSAO_Status, GFSDK_SSAO_CreateContext_GL,
+ GFSDK_SSAO_Context_GL** ppContext,
+ const GFSDK_SSAO_GLFunctions* pGLFunctions,
+ GFSDK_SSAO_CUSTOM_HEAP_ARGUMENT,
+ GFSDK_SSAO_VERSION_ARGUMENT);
+
+/*====================================================================================================
+ D3D12 interface.
+====================================================================================================*/
+
+//---------------------------------------------------------------------------------------------------
+// Note: The RenderAO, PreCreateRTs and Release entry points should not be called simultaneously from different threads.
+//---------------------------------------------------------------------------------------------------
+class GFSDK_SSAO_Context_D3D12 : public GFSDK_SSAO_Context
+{
+public:
+
+ //---------------------------------------------------------------------------------------------------
+ // Renders SSAO.
+ //
+ // Remarks:
+ // * Allocates internal D3D render targets on first use, and re-allocates them when the viewport dimensions change.
+ // * Setting RenderMask = GFSDK_SSAO_RENDER_DEBUG_NORMAL_Z can be useful to visualize the normals used for the AO rendering.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_INVALID_PROJECTION_MATRIX - The projection matrix is not valid
+ // GFSDK_SSAO_INVALID_VIEWPORT_DIMENSIONS - One of the viewport dimensions (width or height) is 0
+ // GFSDK_SSAO_INVALID_VIEWPORT_DEPTH_RANGE - The viewport depth range is not a sub-range of [0.f,1.f]
+ // GFSDK_SSAO_INVALID_WORLD_TO_VIEW_MATRIX - The world-to-view matrix is not valid (transposing it may help)
+ // GFSDK_SSAO_INVALID_NORMAL_TEXTURE_RESOLUTION - The normal-texture resolution does not match the depth-texture resolution
+ // GFSDK_SSAO_INVALID_NORMAL_TEXTURE_SAMPLE_COUNT - The normal-texture sample count does not match the depth-texture sample count
+ // GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED - A D3D resource-creation call has failed (running out of memory?)
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status RenderAO(
+ ID3D12CommandQueue* pCmdQueue,
+ ID3D12GraphicsCommandList* pCmdList,
+ const GFSDK_SSAO_InputData_D3D12& InputData,
+ const GFSDK_SSAO_Parameters& Parameters,
+ const GFSDK_SSAO_Output_D3D12& Output,
+ GFSDK_SSAO_RenderMask RenderMask = GFSDK_SSAO_RENDER_AO) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // [Optional] Pre-creates all internal render targets for RenderAO.
+ //
+ // Remarks:
+ // * This call may be safely skipped since RenderAO creates its render targets on demand if they were not pre-created.
+ // * This call releases and re-creates the internal render targets if the provided resolution changes.
+ // * This call performs CreateCommittedResource calls for all the relevant render targets.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED - A D3D resource-creation call has failed (running out of memory?)
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status PreCreateRTs(
+ ID3D12CommandQueue* pCmdQueue,
+ const GFSDK_SSAO_Parameters& Parameters,
+ GFSDK_SSAO_UINT ViewportWidth,
+ GFSDK_SSAO_UINT ViewportHeight) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // [Optional] Gets the library-internal ZNear and ZFar values derived from the input projection matrix.
+ //
+ // Remarks:
+ // * HBAO+ supports all perspective projection matrices, with arbitrary ZNear and ZFar.
+ // * For reverse infinite projections, GetProjectionMatrixDepthRange should return ZNear=+INF and ZFar=0.f.
+ //
+ // Returns:
+ // GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+ // GFSDK_SSAO_INVALID_PROJECTION_MATRIX - The projection matrix is not valid
+ // GFSDK_SSAO_OK - Success
+ //---------------------------------------------------------------------------------------------------
+ virtual GFSDK_SSAO_Status GetProjectionMatrixDepthRange(
+ const GFSDK_SSAO_InputData_D3D12& InputData,
+ GFSDK_SSAO_ProjectionMatrixDepthRange& OutputDepthRange) = 0;
+
+ //---------------------------------------------------------------------------------------------------
+ // Releases all D3D objects created by the library (to be called right before releasing the D3D device).
+ //---------------------------------------------------------------------------------------------------
+ virtual void Release() = 0;
+
+}; //class GFSDK_SSAO_Context_D3D12
+
+//---------------------------------------------------------------------------------------------------
+//
+// Remark:
+// * Describes the D3D12 descriptor heap space that is passed to the library
+//
+//---------------------------------------------------------------------------------------------------
+#define GFSDK_SSAO_NUM_DESCRIPTORS_RTV_HEAP_D3D12 38 // Number of required descriptors for RTV heap type
+#define GFSDK_SSAO_NUM_DESCRIPTORS_CBV_SRV_UAV_HEAP_D3D12 57 // Number of required descriptors for CBV/SRV/UAV heap type
+
+struct GFSDK_SSAO_DescriptorHeapRange_D3D12
+{
+ ID3D12DescriptorHeap* pDescHeap; // Pointer to the descriptor heap
+ GFSDK_SSAO_UINT BaseIndex; // The base index that can be used as a start index of the pDescHeap
+ GFSDK_SSAO_UINT NumDescriptors; // The maximum number of descriptors that are allowed to be used in the library
+
+ GFSDK_SSAO_DescriptorHeapRange_D3D12()
+ : pDescHeap(NULL)
+ , BaseIndex(0)
+ , NumDescriptors(0)
+ {
+ }
+};
+
+struct GFSDK_SSAO_DescriptorHeaps_D3D12
+{
+ GFSDK_SSAO_DescriptorHeapRange_D3D12 CBV_SRV_UAV;
+ GFSDK_SSAO_DescriptorHeapRange_D3D12 RTV;
+};
+
+//---------------------------------------------------------------------------------------------------
+// Creates a GFSDK_SSAO_Context associated with the D3D12 device.
+//
+// Remarks:
+// * Allocates D3D12 resources internally.
+// * Allocates memory using the default "::operator new", or "pCustomHeap->new_" if provided.
+//
+// Returns:
+// GFSDK_SSAO_NULL_ARGUMENT - One of the required argument pointers is NULL
+// GFSDK_SSAO_VERSION_MISMATCH - Invalid HeaderVersion (have you set HeaderVersion = GFSDK_SSAO_Version()?)
+// GFSDK_SSAO_MEMORY_ALLOCATION_FAILED - Failed to allocate memory on the heap
+// GFSDK_SSAO_D3D_FEATURE_LEVEL_NOT_SUPPORTED - The D3D feature level of pD3DDevice is lower than 11_0
+// GFSDK_SSAO_D3D_RESOURCE_CREATION_FAILED - A resource-creation call has failed (running out of memory?)
+// GFSDK_SSAO_D3D12_INVALID_HEAP_TYPE - One of the heaps provided to GFSDK_SSAO_CreateContext_D3D12 has an unexpected type
+// GFSDK_SSAO_D3D12_INSUFFICIENT_DESCRIPTORS - One of the heaps described in pHeapInfo has insufficient descriptors
+// GFSDK_SSAO_D3D12_INVALID_NODE_MASK - NodeMask has more than one bit set, or is zero
+// GFSDK_SSAO_OK - Success
+//---------------------------------------------------------------------------------------------------
+GFSDK_SSAO_DECL(GFSDK_SSAO_Status, GFSDK_SSAO_CreateContext_D3D12,
+ ID3D12Device* pD3DDevice,
+ GFSDK_SSAO_UINT NodeMask,
+ const GFSDK_SSAO_DescriptorHeaps_D3D12& DescriptorHeaps,
+ GFSDK_SSAO_Context_D3D12** ppContext,
+ GFSDK_SSAO_CUSTOM_HEAP_ARGUMENT,
+ GFSDK_SSAO_VERSION_ARGUMENT);
+
+#pragma pack(pop)
diff --git a/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.dll b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.dll
new file mode 100644
index 0000000..f707257
--- /dev/null
+++ b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.dll
Binary files differ
diff --git a/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.lib b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.lib
new file mode 100644
index 0000000..6fe0c1c
--- /dev/null
+++ b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win32.lib
Binary files differ
diff --git a/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.dll b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.dll
new file mode 100644
index 0000000..4383da2
--- /dev/null
+++ b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.dll
Binary files differ
diff --git a/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.lib b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.lib
new file mode 100644
index 0000000..b9d974e
--- /dev/null
+++ b/NvCloth/samples/external/hbao/GFSDK_SSAO_D3D11.win64.lib
Binary files differ
diff --git a/NvCloth/samples/external/imgui/1.49/.travis.yml b/NvCloth/samples/external/imgui/1.49/.travis.yml
new file mode 100644
index 0000000..616d727
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/.travis.yml
@@ -0,0 +1,18 @@
+language: cpp
+
+os:
+ - linux
+ - osx
+
+compiler:
+ - gcc
+ - clang
+
+before_install:
+ - if [ $TRAVIS_OS_NAME == linux ]; then sudo add-apt-repository -y ppa:pyglfw/pyglfw && sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends libglfw3-dev libxrandr-dev libxi-dev libxxf86vm-dev; fi
+ - if [ $TRAVIS_OS_NAME == osx ]; then brew update && brew install glfw3; fi
+
+script:
+ - make -C examples/opengl_example
+ - make -C examples/opengl3_example
+
diff --git a/NvCloth/samples/external/imgui/1.49/LICENSE b/NvCloth/samples/external/imgui/1.49/LICENSE
new file mode 100644
index 0000000..b28ef22
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2015 Omar Cornut and ImGui contributors
+
+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/NvCloth/samples/external/imgui/1.49/README.md b/NvCloth/samples/external/imgui/1.49/README.md
new file mode 100644
index 0000000..9e32e9e
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/README.md
@@ -0,0 +1,184 @@
+dear imgui,
+=====
+[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui)
+[![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720)
+
+(This library is free and will stay free, but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you work for a company using ImGui or have the means to do so, please consider financial support)
+
+[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
+
+dear imgui (AKA ImGui), is a bloat-free graphical user interface library for C++. It outputs vertex buffers that you can render in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies).
+
+ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries.
+
+ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard.
+
+ImGui is self-contained within a few files that you can easily copy and compile into your application/engine:
+
+ - imgui.cpp
+ - imgui.h
+ - imgui_demo.cpp
+ - imgui_draw.cpp
+ - imgui_internal.h
+ - imconfig.h (empty by default, user-editable)
+ - stb_rect_pack.h
+ - stb_textedit.h
+ - stb_truetype.h
+
+No specific build process is required. You can add the .cpp files to your project or #include them from an existing file.
+
+Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example:
+
+![screenshot of sample code alongside its output with ImGui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png)
+
+ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase.
+
+ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc.
+
+Demo
+----
+
+You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at the features of ImGui, you can download Windows binaries of the demo app here.
+- [imgui-demo-binaries-20160410.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20160410.zip) (Windows binaries, ImGui 1.48+ 2016/04/10, 4 executables, 534 KB)
+
+
+Gallery
+-------
+
+See the [Screenshots Thread](https://github.com/ocornut/imgui/issues/123) for some user creations.
+
+![screenshot 1](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_01.png)
+![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_02.png)
+
+[![profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler-880.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler.png)
+
+![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_01.png)
+![screenshot 3](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_02.png)
+![screenshot 4](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_03.png)
+![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v140/test_window_05_menus.png)
+![screenshot 6](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/skinning_sample_02.png)
+![screenshot 7](https://cloud.githubusercontent.com/assets/8225057/7903336/96f0fb7c-07d0-11e5-95d6-41c6a1595e5a.png)
+
+ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with:
+```
+ImGuiIO& io = ImGui::GetIO();
+io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+
+// For Microsoft IME, pass your HWND to enable IME positioning:
+io.ImeWindowHandle = my_hwnd;
+```
+![Japanese screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01_jp.png)
+
+References
+----------
+
+The Immediate Mode GUI paradigm may at first appear unusual to some users. This is mainly because "Retained Mode" GUIs have been so widespread and predominant. The following links can give you a better understanding about how Immediate Mode GUIs works.
+- [Johannes 'johno' Norneby's article](http://www.johno.se/book/imgui.html).
+- [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf).
+- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/).
+- [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861).
+
+See the [Links page](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to different languages and frameworks.
+
+Frequently Asked Question (FAQ)
+-------------------------------
+
+<b>Where is the documentation?</b>
+
+- The documentation is at the top of imgui.cpp + effectively imgui.h.
+- Example code is in imgui_demo.cpp and particularly the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output.
+- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder.
+- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort.
+
+<b>Why the odd dual naming, "dear imgui" vs "ImGui"?</b>
+
+The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations.
+
+<b>How do I update to a newer version of ImGui?</b>
+<br><b>What is ImTextureID and how do I display an image?</b>
+<br><b>I integrated ImGui in my engine and the text or lines are blurry..</b>
+<br><b>I integrated ImGui in my engine and some elements are disappearing when I move windows around..</b>
+<br><b>How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs.</b>
+<br><b>How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?</b>
+<br><b>How can I load a different font than the default?</b>
+<br><b>How can I load multiple fonts?</b>
+<br><b>How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?</b>
+<br><b>How can I use the drawing facilities without an ImGui window? (using ImDrawList API)</b>
+
+See the FAQ in imgui.cpp for answers.
+
+<b>How do you use ImGui on a platform that may not have a mouse or keyboard?</b>
+
+I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/synergy/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate.
+
+<b>Can you create elaborate/serious tools with ImGui?</b>
+
+Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools).
+
+ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Many programmers have unfortunately been taught by their environment to make unnecessarily complicated things. ImGui is about making things that are simple, efficient and powerful.
+
+<b>Is ImGui fast?</b>
+
+Probably fast enough for most uses. Down to the fundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it.
+
+Mileage may vary but the following screenshot can give you a rough idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup are likely to be the bottleneck. Testing performance as part of a real application is recommended).
+
+![performance screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v138/performance_01.png)
+
+This is showing framerate for the full application loop on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M with an optimized executable. In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint.
+
+If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem.
+
+<b>Can you reskin the look of ImGui?</b>
+
+You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface.
+
+This is [LumixEngine](https://github.com/nem0/LumixEngine) with a minor skinning hack + a docking/tabs extension (both of which you can find in the Issues section and will eventually be merged).
+
+[![Skinning in LumixEngine](https://cloud.githubusercontent.com/assets/8225057/13198792/92808c5c-d812-11e5-9507-16b63918b05b.jpg)](https://cloud.githubusercontent.com/assets/8225057/13044612/59f07aec-d3cf-11e5-8ccb-39adf2e13e69.png)
+
+<b>Why using C++ (as opposed to C)?</b>
+
+ImGui takes advantage of a few C++ features for convenience but nothing anywhere Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed.
+
+There is an unofficial but reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly. I would suggest using your target language functionality to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. It was really designed with C++ in mind and may not make the same amount of sense with another language. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages.
+
+Donate
+------
+
+<b>Can I donate to support the development of ImGui?</b>
+
+[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
+
+I'm currently an independent developer and your contributions are useful. I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated. I am available for hire to work on or with ImGui. Thanks!
+
+Credits
+-------
+
+Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com).
+
+I first discovered imgui principles at [Q-Games](http://www.q-games.com) where Atman had dropped his own simple imgui implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating on it.
+
+Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license).
+
+Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain).
+
+Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub.
+
+Ongoing ImGui development is financially supported on [**Patreon**](http://www.patreon.com/imgui).
+
+Double-chocolate sponsors:
+- Media Molecule, Mobigame
+
+Salty caramel supporters:
+- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Stefano Cristiano, Chris Genova, ikrima
+
+Caramel supporters:
+- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm, Farhan Wali, Jeff Roberts, Matt Reyer, Colin Riley.
+
+And other supporters; thanks!
+
+License
+-------
+
+Dear ImGui is licensed under the MIT License, see LICENSE for more information.
diff --git a/NvCloth/samples/external/imgui/1.49/examples/directx11_example/build_win32.bat b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/build_win32.bat
new file mode 100644
index 0000000..2d1c40f
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/build_win32.bat
@@ -0,0 +1,4 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
+mkdir Debug
+cl /nologo /Zi /MD /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" /D UNICODE /D _UNICODE *.cpp ..\..\*.cpp /FeDebug/directx11_example.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib
+
diff --git a/NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj
new file mode 100644
index 0000000..944c8e8
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj
@@ -0,0 +1,159 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{9F316E83-5AE5-4939-A723-305A94F48005}</ProjectGuid>
+ <RootNamespace>directx11_example</RootNamespace>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>Application</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <OutDir>$(ProjectDir)$(Configuration)\</OutDir>
+ <IntDir>$(ProjectDir)$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <OutDir>$(ProjectDir)$(Configuration)\</OutDir>
+ <IntDir>$(ProjectDir)$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <OutDir>$(ProjectDir)$(Configuration)\</OutDir>
+ <IntDir>$(ProjectDir)$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <OutDir>$(ProjectDir)$(Configuration)\</OutDir>
+ <IntDir>$(ProjectDir)$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <WarningLevel>Level4</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;</AdditionalIncludeDirectories>
+ </ClCompile>
+ <Link>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <AdditionalDependencies>d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalLibraryDirectories>$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <SubSystem>Console</SubSystem>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <WarningLevel>Level4</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;</AdditionalIncludeDirectories>
+ </ClCompile>
+ <Link>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <AdditionalDependencies>d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalLibraryDirectories>$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <SubSystem>Console</SubSystem>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <WarningLevel>Level4</WarningLevel>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <AdditionalIncludeDirectories>..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;</AdditionalIncludeDirectories>
+ </ClCompile>
+ <Link>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ <AdditionalDependencies>d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalLibraryDirectories>$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <SubSystem>Console</SubSystem>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <WarningLevel>Level4</WarningLevel>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <AdditionalIncludeDirectories>..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;</AdditionalIncludeDirectories>
+ </ClCompile>
+ <Link>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ <AdditionalDependencies>d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalLibraryDirectories>$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <SubSystem>Console</SubSystem>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClInclude Include="..\..\imconfig.h" />
+ <ClInclude Include="..\..\imgui.h" />
+ <ClInclude Include="..\..\imgui_internal.h" />
+ <ClInclude Include="imgui_impl_dx11.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="..\..\imgui.cpp" />
+ <ClCompile Include="..\..\imgui_demo.cpp" />
+ <ClCompile Include="..\..\imgui_draw.cpp" />
+ <ClCompile Include="imgui_impl_dx11.cpp" />
+ <ClCompile Include="main.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="..\README.txt" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project> \ No newline at end of file
diff --git a/NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj.filters b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj.filters
new file mode 100644
index 0000000..5cd0ca4
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/directx11_example.vcxproj.filters
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="imgui">
+ <UniqueIdentifier>{0587d7a3-f2ce-4d56-b84f-a0005d3bfce6}</UniqueIdentifier>
+ </Filter>
+ <Filter Include="sources">
+ <UniqueIdentifier>{08e36723-ce4f-4cff-9662-c40801cf1acf}</UniqueIdentifier>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="..\..\imconfig.h">
+ <Filter>imgui</Filter>
+ </ClInclude>
+ <ClInclude Include="..\..\imgui.h">
+ <Filter>imgui</Filter>
+ </ClInclude>
+ <ClInclude Include="imgui_impl_dx11.h">
+ <Filter>sources</Filter>
+ </ClInclude>
+ <ClInclude Include="..\..\imgui_internal.h">
+ <Filter>imgui</Filter>
+ </ClInclude>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="..\..\imgui.cpp">
+ <Filter>imgui</Filter>
+ </ClCompile>
+ <ClCompile Include="main.cpp">
+ <Filter>sources</Filter>
+ </ClCompile>
+ <ClCompile Include="imgui_impl_dx11.cpp">
+ <Filter>sources</Filter>
+ </ClCompile>
+ <ClCompile Include="..\..\imgui_demo.cpp">
+ <Filter>imgui</Filter>
+ </ClCompile>
+ <ClCompile Include="..\..\imgui_draw.cpp">
+ <Filter>imgui</Filter>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="..\README.txt" />
+ </ItemGroup>
+</Project> \ No newline at end of file
diff --git a/NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.cpp b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.cpp
new file mode 100644
index 0000000..11f66f0
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.cpp
@@ -0,0 +1,583 @@
+// ImGui Win32 + DirectX11 binding
+// In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+
+// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
+// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// https://github.com/ocornut/imgui
+
+#include <imgui.h>
+#include "imgui_impl_dx11.h"
+
+// DirectX
+#include <d3d11.h>
+#include <d3dcompiler.h>
+#define DIRECTINPUT_VERSION 0x0800
+#include <dinput.h>
+
+// Data
+static INT64 g_Time = 0;
+static INT64 g_TicksPerSecond = 0;
+
+static HWND g_hWnd = 0;
+static ID3D11Device* g_pd3dDevice = NULL;
+static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
+static ID3D11Buffer* g_pVB = NULL;
+static ID3D11Buffer* g_pIB = NULL;
+static ID3D10Blob * g_pVertexShaderBlob = NULL;
+static ID3D11VertexShader* g_pVertexShader = NULL;
+static ID3D11InputLayout* g_pInputLayout = NULL;
+static ID3D11Buffer* g_pVertexConstantBuffer = NULL;
+static ID3D10Blob * g_pPixelShaderBlob = NULL;
+static ID3D11PixelShader* g_pPixelShader = NULL;
+static ID3D11SamplerState* g_pFontSampler = NULL;
+static ID3D11ShaderResourceView*g_pFontTextureView = NULL;
+static ID3D11RasterizerState* g_pRasterizerState = NULL;
+static ID3D11BlendState* g_pBlendState = NULL;
+static ID3D11DepthStencilState* g_pDepthStencilState = NULL;
+static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000;
+
+struct VERTEX_CONSTANT_BUFFER
+{
+ float mvp[4][4];
+};
+
+// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
+// If text or lines are blurry when integrating ImGui in your engine:
+// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
+void ImGui_ImplDX11_RenderDrawLists(ImDrawData* draw_data)
+{
+ ID3D11DeviceContext* ctx = g_pd3dDeviceContext;
+
+ // Create and grow vertex/index buffers if needed
+ if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount)
+ {
+ if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
+ g_VertexBufferSize = draw_data->TotalVtxCount + 5000;
+ D3D11_BUFFER_DESC desc;
+ memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert);
+ desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ desc.MiscFlags = 0;
+ if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0)
+ return;
+ }
+ if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount)
+ {
+ if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
+ g_IndexBufferSize = draw_data->TotalIdxCount + 10000;
+ D3D11_BUFFER_DESC desc;
+ memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx);
+ desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0)
+ return;
+ }
+
+ // Copy and convert all vertices into a single contiguous buffer
+ D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
+ if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
+ return;
+ if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
+ return;
+ ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
+ ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
+ {
+ const ImDrawList* cmd_list = draw_data->CmdLists[n];
+ memcpy(vtx_dst, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
+ memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
+ vtx_dst += cmd_list->VtxBuffer.size();
+ idx_dst += cmd_list->IdxBuffer.size();
+ }
+ ctx->Unmap(g_pVB, 0);
+ ctx->Unmap(g_pIB, 0);
+
+ // Setup orthographic projection matrix into our constant buffer
+ {
+ D3D11_MAPPED_SUBRESOURCE mapped_resource;
+ if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
+ return;
+ VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
+ float L = 0.0f;
+ float R = ImGui::GetIO().DisplaySize.x;
+ float B = ImGui::GetIO().DisplaySize.y;
+ float T = 0.0f;
+ float mvp[4][4] =
+ {
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
+ { 0.0f, 0.0f, 0.5f, 0.0f },
+ { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
+ };
+ memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
+ ctx->Unmap(g_pVertexConstantBuffer, 0);
+ }
+
+ // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
+ struct BACKUP_DX11_STATE
+ {
+ UINT ScissorRectsCount, ViewportsCount;
+ D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
+ D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
+ ID3D11RasterizerState* RS;
+ ID3D11BlendState* BlendState;
+ FLOAT BlendFactor[4];
+ UINT SampleMask;
+ UINT StencilRef;
+ ID3D11DepthStencilState* DepthStencilState;
+ ID3D11ShaderResourceView* PSShaderResource;
+ ID3D11SamplerState* PSSampler;
+ ID3D11PixelShader* PS;
+ ID3D11VertexShader* VS;
+ UINT PSInstancesCount, VSInstancesCount;
+ ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
+ D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
+ ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
+ UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
+ DXGI_FORMAT IndexBufferFormat;
+ ID3D11InputLayout* InputLayout;
+ };
+ BACKUP_DX11_STATE old;
+ old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
+ ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
+ ctx->RSGetViewports(&old.ViewportsCount, old.Viewports);
+ ctx->RSGetState(&old.RS);
+ ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
+ ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
+ ctx->PSGetShaderResources(0, 1, &old.PSShaderResource);
+ ctx->PSGetSamplers(0, 1, &old.PSSampler);
+ old.PSInstancesCount = old.VSInstancesCount = 256;
+ ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
+ ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
+ ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
+ ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology);
+ ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
+ ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
+ ctx->IAGetInputLayout(&old.InputLayout);
+
+ // Setup viewport
+ D3D11_VIEWPORT vp;
+ memset(&vp, 0, sizeof(D3D11_VIEWPORT));
+ vp.Width = ImGui::GetIO().DisplaySize.x;
+ vp.Height = ImGui::GetIO().DisplaySize.y;
+ vp.MinDepth = 0.0f;
+ vp.MaxDepth = 1.0f;
+ vp.TopLeftX = vp.TopLeftY = 0.0f;
+ ctx->RSSetViewports(1, &vp);
+
+ // Bind shader and vertex buffers
+ unsigned int stride = sizeof(ImDrawVert);
+ unsigned int offset = 0;
+ ctx->IASetInputLayout(g_pInputLayout);
+ ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset);
+ ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
+ ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ ctx->VSSetShader(g_pVertexShader, NULL, 0);
+ ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer);
+ ctx->PSSetShader(g_pPixelShader, NULL, 0);
+ ctx->PSSetSamplers(0, 1, &g_pFontSampler);
+
+ // Setup render state
+ const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
+ ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff);
+ ctx->OMSetDepthStencilState(g_pDepthStencilState, 0);
+ ctx->RSSetState(g_pRasterizerState);
+
+ // Render command lists
+ int vtx_offset = 0;
+ int idx_offset = 0;
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
+ {
+ const ImDrawList* cmd_list = draw_data->CmdLists[n];
+ 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
+ {
+ const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
+ ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
+ ctx->RSSetScissorRects(1, &r);
+ ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
+ }
+ idx_offset += pcmd->ElemCount;
+ }
+ vtx_offset += cmd_list->VtxBuffer.size();
+ }
+
+ // Restore modified DX state
+ ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
+ ctx->RSSetViewports(old.ViewportsCount, old.Viewports);
+ ctx->RSSetState(old.RS); if (old.RS) old.RS->Release();
+ ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
+ ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
+ ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
+ ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
+ ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
+ for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
+ ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
+ ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
+ for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
+ ctx->IASetPrimitiveTopology(old.PrimitiveTopology);
+ ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
+ ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
+ ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
+}
+
+IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ ImGuiIO& io = ImGui::GetIO();
+ switch (msg)
+ {
+ case WM_LBUTTONDOWN:
+ io.MouseDown[0] = true;
+ return true;
+ case WM_LBUTTONUP:
+ io.MouseDown[0] = false;
+ return true;
+ case WM_RBUTTONDOWN:
+ io.MouseDown[1] = true;
+ return true;
+ case WM_RBUTTONUP:
+ io.MouseDown[1] = false;
+ return true;
+ case WM_MBUTTONDOWN:
+ io.MouseDown[2] = true;
+ return true;
+ case WM_MBUTTONUP:
+ io.MouseDown[2] = false;
+ return true;
+ case WM_MOUSEWHEEL:
+ io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
+ return true;
+ case WM_MOUSEMOVE:
+ io.MousePos.x = (signed short)(lParam);
+ io.MousePos.y = (signed short)(lParam >> 16);
+ return true;
+ case WM_KEYDOWN:
+ if (wParam < 256)
+ io.KeysDown[wParam] = 1;
+ return true;
+ case WM_KEYUP:
+ if (wParam < 256)
+ io.KeysDown[wParam] = 0;
+ return true;
+ case WM_CHAR:
+ // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
+ if (wParam > 0 && wParam < 0x10000)
+ io.AddInputCharacter((unsigned short)wParam);
+ return true;
+ }
+ return 0;
+}
+
+static void ImGui_ImplDX11_CreateFontsTexture()
+{
+ // Build texture atlas
+ ImGuiIO& io = ImGui::GetIO();
+ unsigned char* pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
+
+ // Upload texture to graphics system
+ {
+ D3D11_TEXTURE2D_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Width = width;
+ desc.Height = height;
+ desc.MipLevels = 1;
+ desc.ArraySize = 1;
+ desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ desc.SampleDesc.Count = 1;
+ desc.Usage = D3D11_USAGE_DEFAULT;
+ desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ desc.CPUAccessFlags = 0;
+
+ ID3D11Texture2D *pTexture = NULL;
+ D3D11_SUBRESOURCE_DATA subResource;
+ subResource.pSysMem = pixels;
+ subResource.SysMemPitch = desc.Width * 4;
+ subResource.SysMemSlicePitch = 0;
+ g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
+
+ // Create texture view
+ D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
+ ZeroMemory(&srvDesc, sizeof(srvDesc));
+ srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
+ srvDesc.Texture2D.MipLevels = desc.MipLevels;
+ srvDesc.Texture2D.MostDetailedMip = 0;
+ g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView);
+ pTexture->Release();
+ }
+
+ // Store our identifier
+ io.Fonts->TexID = (void *)g_pFontTextureView;
+
+ // Create texture sampler
+ {
+ D3D11_SAMPLER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
+ desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
+ desc.MipLODBias = 0.f;
+ desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
+ desc.MinLOD = 0.f;
+ desc.MaxLOD = 0.f;
+ g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler);
+ }
+}
+
+bool ImGui_ImplDX11_CreateDeviceObjects()
+{
+ if (!g_pd3dDevice)
+ return false;
+ if (g_pFontSampler)
+ ImGui_ImplDX11_InvalidateDeviceObjects();
+
+ // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
+ // If you would like to use this DX11 sample code but remove this dependency you can:
+ // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [prefered solution]
+ // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
+ // See https://github.com/ocornut/imgui/pull/638 for sources and details.
+
+ // Create the vertex shader
+ {
+ static const char* vertexShader =
+ "cbuffer vertexBuffer : register(b0) \
+ {\
+ float4x4 ProjectionMatrix; \
+ };\
+ struct VS_INPUT\
+ {\
+ float2 pos : POSITION;\
+ float4 col : COLOR0;\
+ float2 uv : TEXCOORD0;\
+ };\
+ \
+ struct PS_INPUT\
+ {\
+ float4 pos : SV_POSITION;\
+ float4 col : COLOR0;\
+ float2 uv : TEXCOORD0;\
+ };\
+ \
+ PS_INPUT main(VS_INPUT input)\
+ {\
+ PS_INPUT output;\
+ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
+ output.col = input.col;\
+ output.uv = input.uv;\
+ return output;\
+ }";
+
+ D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL);
+ if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
+ return false;
+ if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK)
+ return false;
+
+ // Create the input layout
+ D3D11_INPUT_ELEMENT_DESC local_layout[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ };
+ if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK)
+ return false;
+
+ // Create the constant buffer
+ {
+ D3D11_BUFFER_DESC desc;
+ desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
+ desc.Usage = D3D11_USAGE_DYNAMIC;
+ desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ desc.MiscFlags = 0;
+ g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer);
+ }
+ }
+
+ // Create the pixel shader
+ {
+ static const char* pixelShader =
+ "struct PS_INPUT\
+ {\
+ float4 pos : SV_POSITION;\
+ float4 col : COLOR0;\
+ float2 uv : TEXCOORD0;\
+ };\
+ sampler sampler0;\
+ Texture2D texture0;\
+ \
+ float4 main(PS_INPUT input) : SV_Target\
+ {\
+ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
+ return out_col; \
+ }";
+
+ D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL);
+ if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
+ return false;
+ if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK)
+ return false;
+ }
+
+ // Create the blending setup
+ {
+ D3D11_BLEND_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.AlphaToCoverageEnable = false;
+ desc.RenderTarget[0].BlendEnable = true;
+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
+ g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState);
+ }
+
+ // Create the rasterizer state
+ {
+ D3D11_RASTERIZER_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.FillMode = D3D11_FILL_SOLID;
+ desc.CullMode = D3D11_CULL_NONE;
+ desc.ScissorEnable = true;
+ desc.DepthClipEnable = true;
+ g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState);
+ }
+
+ // Create depth-stencil State
+ {
+ D3D11_DEPTH_STENCIL_DESC desc;
+ ZeroMemory(&desc, sizeof(desc));
+ desc.DepthEnable = false;
+ desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
+ desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
+ desc.StencilEnable = false;
+ desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
+ desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
+ desc.BackFace = desc.FrontFace;
+ g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState);
+ }
+
+ ImGui_ImplDX11_CreateFontsTexture();
+
+ return true;
+}
+
+void ImGui_ImplDX11_InvalidateDeviceObjects()
+{
+ if (!g_pd3dDevice)
+ return;
+
+ if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
+ if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = 0; }
+ if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
+ if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
+
+ if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; }
+ if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; }
+ if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; }
+ if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; }
+ if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; }
+ if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; }
+ if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; }
+ if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; }
+ if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; }
+}
+
+bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context)
+{
+ g_hWnd = (HWND)hwnd;
+ g_pd3dDevice = device;
+ g_pd3dDeviceContext = device_context;
+
+ if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
+ return false;
+ if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
+ return false;
+
+ ImGuiIO& io = ImGui::GetIO();
+ io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime.
+ io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
+ io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
+ io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
+ io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
+ io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
+ io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
+ io.KeyMap[ImGuiKey_Home] = VK_HOME;
+ io.KeyMap[ImGuiKey_End] = VK_END;
+ io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
+ io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
+ io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
+ io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
+ io.KeyMap[ImGuiKey_A] = 'A';
+ io.KeyMap[ImGuiKey_C] = 'C';
+ io.KeyMap[ImGuiKey_V] = 'V';
+ io.KeyMap[ImGuiKey_X] = 'X';
+ io.KeyMap[ImGuiKey_Y] = 'Y';
+ io.KeyMap[ImGuiKey_Z] = 'Z';
+
+ io.RenderDrawListsFn = ImGui_ImplDX11_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
+ io.ImeWindowHandle = g_hWnd;
+
+ return true;
+}
+
+void ImGui_ImplDX11_Shutdown()
+{
+ ImGui_ImplDX11_InvalidateDeviceObjects();
+ ImGui::Shutdown();
+ g_pd3dDevice = NULL;
+ g_pd3dDeviceContext = NULL;
+ g_hWnd = (HWND)0;
+}
+
+void ImGui_ImplDX11_NewFrame()
+{
+ if (!g_pFontSampler)
+ ImGui_ImplDX11_CreateDeviceObjects();
+
+ ImGuiIO& io = ImGui::GetIO();
+
+ // Setup display size (every frame to accommodate for window resizing)
+ RECT rect;
+ GetClientRect(g_hWnd, &rect);
+ io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
+
+ // Setup time step
+ INT64 current_time;
+ QueryPerformanceCounter((LARGE_INTEGER *)&current_time);
+ io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
+ g_Time = current_time;
+
+ // Read keyboard modifiers inputs
+ io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
+ io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
+ io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0;
+ io.KeySuper = false;
+ // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events
+ // io.MousePos : filled by WM_MOUSEMOVE events
+ // io.MouseDown : filled by WM_*BUTTON* events
+ // io.MouseWheel : filled by WM_MOUSEWHEEL events
+
+ // Hide OS mouse cursor if ImGui is drawing it
+ SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));
+
+ // Start the frame
+ ImGui::NewFrame();
+}
diff --git a/NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.h b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.h
new file mode 100644
index 0000000..7d6f710
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/imgui_impl_dx11.h
@@ -0,0 +1,25 @@
+// ImGui Win32 + DirectX11 binding
+// In this binding, ImTextureID is used to store a 'ID3D11ShaderResourceView*' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+
+// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
+// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// https://github.com/ocornut/imgui
+
+struct ID3D11Device;
+struct ID3D11DeviceContext;
+
+IMGUI_API bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context);
+IMGUI_API void ImGui_ImplDX11_Shutdown();
+IMGUI_API void ImGui_ImplDX11_NewFrame();
+
+// Use if you want to reset your rendering device without losing ImGui state.
+IMGUI_API void ImGui_ImplDX11_InvalidateDeviceObjects();
+IMGUI_API bool ImGui_ImplDX11_CreateDeviceObjects();
+
+// Handler for Win32 messages, update mouse/keyboard data.
+// You may or not need this for your implementation, but it can serve as reference for handling inputs.
+// Commented out to avoid dragging dependencies on <windows.h> types. You can copy the extern declaration in your code.
+/*
+IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+*/
diff --git a/NvCloth/samples/external/imgui/1.49/examples/directx11_example/main.cpp b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/main.cpp
new file mode 100644
index 0000000..e3fe5aa
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/examples/directx11_example/main.cpp
@@ -0,0 +1,197 @@
+// ImGui - standalone example application for DirectX 11
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+
+#include <imgui.h>
+#include "imgui_impl_dx11.h"
+#include <d3d11.h>
+#define DIRECTINPUT_VERSION 0x0800
+#include <dinput.h>
+#include <tchar.h>
+
+// Data
+static ID3D11Device* g_pd3dDevice = NULL;
+static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
+static IDXGISwapChain* g_pSwapChain = NULL;
+static ID3D11RenderTargetView* g_mainRenderTargetView = NULL;
+
+void CreateRenderTarget()
+{
+ DXGI_SWAP_CHAIN_DESC sd;
+ g_pSwapChain->GetDesc(&sd);
+
+ // Create the render target
+ ID3D11Texture2D* pBackBuffer;
+ D3D11_RENDER_TARGET_VIEW_DESC render_target_view_desc;
+ ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
+ render_target_view_desc.Format = sd.BufferDesc.Format;
+ render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
+ g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
+ g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
+ g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
+ pBackBuffer->Release();
+}
+
+void CleanupRenderTarget()
+{
+ if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
+}
+
+HRESULT CreateDeviceD3D(HWND hWnd)
+{
+ // Setup swap chain
+ DXGI_SWAP_CHAIN_DESC sd;
+ {
+ ZeroMemory(&sd, sizeof(sd));
+ sd.BufferCount = 2;
+ sd.BufferDesc.Width = 0;
+ sd.BufferDesc.Height = 0;
+ sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ sd.BufferDesc.RefreshRate.Numerator = 60;
+ sd.BufferDesc.RefreshRate.Denominator = 1;
+ sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
+ sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
+ sd.OutputWindow = hWnd;
+ sd.SampleDesc.Count = 1;
+ sd.SampleDesc.Quality = 0;
+ sd.Windowed = TRUE;
+ sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
+ }
+
+ UINT createDeviceFlags = 0;
+ //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
+ D3D_FEATURE_LEVEL featureLevel;
+ const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
+ if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
+ return E_FAIL;
+
+ CreateRenderTarget();
+
+ return S_OK;
+}
+
+void CleanupDeviceD3D()
+{
+ CleanupRenderTarget();
+ if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
+ if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
+ if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
+}
+
+extern LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ if (ImGui_ImplDX11_WndProcHandler(hWnd, msg, wParam, lParam))
+ return true;
+
+ switch (msg)
+ {
+ case WM_SIZE:
+ if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
+ {
+ ImGui_ImplDX11_InvalidateDeviceObjects();
+ CleanupRenderTarget();
+ g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
+ CreateRenderTarget();
+ ImGui_ImplDX11_CreateDeviceObjects();
+ }
+ return 0;
+ case WM_SYSCOMMAND:
+ if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
+ return 0;
+ break;
+ case WM_DESTROY:
+ PostQuitMessage(0);
+ return 0;
+ }
+ return DefWindowProc(hWnd, msg, wParam, lParam);
+}
+
+int main(int, char**)
+{
+ // Create application window
+ WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, _T("ImGui Example"), NULL };
+ RegisterClassEx(&wc);
+ HWND hwnd = CreateWindow(_T("ImGui Example"), _T("ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
+
+ // Initialize Direct3D
+ if (CreateDeviceD3D(hwnd) < 0)
+ {
+ CleanupDeviceD3D();
+ UnregisterClass(_T("ImGui Example"), wc.hInstance);
+ return 1;
+ }
+
+ // Show the window
+ ShowWindow(hwnd, SW_SHOWDEFAULT);
+ UpdateWindow(hwnd);
+
+ // Setup ImGui binding
+ ImGui_ImplDX11_Init(hwnd, g_pd3dDevice, g_pd3dDeviceContext);
+
+ // Load Fonts
+ // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ //ImGuiIO& io = ImGui::GetIO();
+ //io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
+ //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+
+ bool show_test_window = true;
+ bool show_another_window = false;
+ ImVec4 clear_col = ImColor(114, 144, 154);
+
+ // Main loop
+ MSG msg;
+ ZeroMemory(&msg, sizeof(msg));
+ while (msg.message != WM_QUIT)
+ {
+ if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
+ {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ continue;
+ }
+ ImGui_ImplDX11_NewFrame();
+
+ // 1. Show a simple window
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ {
+ static float f = 0.0f;
+ ImGui::Text("Hello, world!");
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
+ ImGui::ColorEdit3("clear color", (float*)&clear_col);
+ if (ImGui::Button("Test Window")) show_test_window ^= 1;
+ if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
+ }
+
+ // 2. Show another simple window, this time using an explicit Begin/End pair
+ if (show_another_window)
+ {
+ ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
+ ImGui::Begin("Another Window", &show_another_window);
+ ImGui::Text("Hello");
+ ImGui::End();
+ }
+
+ // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
+ if (show_test_window)
+ {
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowTestWindow(&show_test_window);
+ }
+
+ // Rendering
+ g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_col);
+ ImGui::Render();
+ g_pSwapChain->Present(0, 0);
+ }
+
+ ImGui_ImplDX11_Shutdown();
+ CleanupDeviceD3D();
+ UnregisterClass(_T("ImGui Example"), wc.hInstance);
+
+ return 0;
+}
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/Cousine-Regular.ttf b/NvCloth/samples/external/imgui/1.49/extra_fonts/Cousine-Regular.ttf
new file mode 100644
index 0000000..70a0bf9
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/Cousine-Regular.ttf
Binary files differ
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/DroidSans.ttf b/NvCloth/samples/external/imgui/1.49/extra_fonts/DroidSans.ttf
new file mode 100644
index 0000000..767c63a
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/DroidSans.ttf
Binary files differ
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/Karla-Regular.ttf b/NvCloth/samples/external/imgui/1.49/extra_fonts/Karla-Regular.ttf
new file mode 100644
index 0000000..81b3de6
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/Karla-Regular.ttf
Binary files differ
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyClean.ttf b/NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyClean.ttf
new file mode 100644
index 0000000..0270cdf
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyClean.ttf
Binary files differ
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyTiny.ttf b/NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyTiny.ttf
new file mode 100644
index 0000000..1c4312c
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/ProggyTiny.ttf
Binary files differ
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/README.txt b/NvCloth/samples/external/imgui/1.49/extra_fonts/README.txt
new file mode 100644
index 0000000..1e9bc13
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/README.txt
@@ -0,0 +1,151 @@
+
+ The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' that you can use without any external files.
+ The files in this folder are only provided as a convenience, you can use any of your own .TTF files.
+
+ Fonts are rasterized in a single texture at the time of calling either of io.Fonts.GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build().
+
+ If you want to use icons in ImGui, a good idea is to merge an icon font within your main font, and refer to icons directly in your strings.
+ You can use headers files with definitions for popular icon fonts codepoints, by Juliette Foucaut, at https://github.com/juliettef/IconFontCppHeaders
+
+
+---------------------------------
+ LOADING INSTRUCTIONS
+---------------------------------
+
+ Load default font with:
+
+ ImGuiIO& io = ImGui::GetIO();
+ io.Fonts->AddFontDefault();
+
+ Load .TTF file with:
+
+ ImGuiIO& io = ImGui::GetIO();
+ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
+
+ Detailed options:
+
+ ImFontConfig config;
+ config.OversampleH = 3;
+ config.OversampleV = 1;
+ config.GlyphExtraSpacing.x = 1.0f;
+ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config);
+
+ If you have very large number of glyphs or multiple fonts:
+
+ - Mind the fact that some graphics drivers have texture size limitation.
+ - Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function).
+ - You may reduce oversampling, e.g. config.OversampleH = 2 or 1.
+ - Reduce glyphs ranges, consider calculating them based on your source data if this is possible.
+
+ Combine two fonts into one:
+
+ // Load a first font
+ io.Fonts->AddFontDefault();
+
+ // Add character ranges and merge into the previous font
+ // The ranges array is not copied by the AddFont* functions and is used lazily
+ // so ensure it is available for duration of font usage
+ static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // will not be copied by AddFont* so keep in scope.
+ ImFontConfig config;
+ config.MergeMode = true;
+ io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese());
+ io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges);
+
+ Add a fourth parameter to bake specific font ranges only:
+
+ // Basic Latin, Extended Latin
+ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault());
+
+ // Include full set of about 21000 CJK Unified Ideographs
+ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
+
+ // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
+ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChinese());
+
+ Offset font vertically by altering the io.Font->DisplayOffset value:
+
+ ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
+ font->DisplayOffset.y += 1; // Render 1 pixel down
+
+
+---------------------------------
+ REMAP CODEPOINTS
+---------------------------------
+
+ All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese CP-1251 for Cyrillic) will not work.
+ In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
+ You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
+
+
+---------------------------------
+ EMBED A FONT IN SOURCE CODE
+---------------------------------
+
+ Compile and use 'binary_to_compressed_c.cpp' to create a compressed C style array. Then load the font with:
+
+ ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
+
+ Or
+
+ ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
+
+
+---------------------------------
+ FONT FILES INCLUDED IN THIS FOLDER
+---------------------------------
+
+ Cousine-Regular.ttf
+ Digitized data copyright (c) 2010 Google Corporation.
+ Licensed under the SIL Open Font License, Version 1.1
+
+ DroidSans.ttf
+ Copyright (c) Steve Matteson
+ Apache License, version 2.0
+ http://www.google.com/fonts/specimen/Droid+Sans
+
+ ProggyClean.ttf
+ Copyright (c) 2004, 2005 Tristan Grimmer
+ MIT License
+ recommended loading setting in ImGui: Size = 13.0, DisplayOffset.Y = +1
+
+ ProggyTiny.ttf
+ Copyright (c) 2004, 2005 Tristan Grimmer
+ MIT License
+ recommended loading setting in ImGui: Size = 10.0, DisplayOffset.Y = +1
+
+ Karla-Regular
+ Copyright (c) 2012, Jonathan Pinhorn
+ SIL OPEN FONT LICENSE Version 1.1
+
+
+---------------------------------
+ LINKS
+---------------------------------
+
+ Icon fonts
+ https://fortawesome.github.io/Font-Awesome/
+ https://github.com/SamBrishes/kenney-icon-font
+ https://design.google.com/icons/
+
+ Typefaces for source code beautification
+ https://github.com/chrissimpkins/codeface
+
+ Programmation fonts
+ http://s9w.github.io/font_compare/
+
+ Proggy Programming Fonts
+ http://upperbounds.net
+
+ Inconsolata
+ http://www.levien.com/type/myfonts/inconsolata.html
+
+ Adobe Source Code Pro: Monospaced font family for user interface and coding environments
+ https://github.com/adobe-fonts/source-code-pro
+
+ Monospace/Fixed Width Programmer's Fonts
+ http://www.lowing.org/fonts/
+
+ (Japanese) M+ fonts by Coji Morishita are free and include most useful Kanjis you would need.
+ http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html
+
+ Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing).
diff --git a/NvCloth/samples/external/imgui/1.49/extra_fonts/binary_to_compressed_c.cpp b/NvCloth/samples/external/imgui/1.49/extra_fonts/binary_to_compressed_c.cpp
new file mode 100644
index 0000000..57b2407
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/extra_fonts/binary_to_compressed_c.cpp
@@ -0,0 +1,368 @@
+// ImGui - binary_to_compressed_c.cpp
+// Helper tool to turn a file into a C array.
+// The data is first compressed with stb_compress() to reduce source code size.
+// Then encoded in Base85 to fit in a string so we can fit roughly 4 bytes of compressed data into 5 bytes of source code (suggested by @mmalex)
+// (If we used 32-bits constants it would require take 11 bytes of source code to encode 4 bytes.)
+// Useful if you want to embed fonts into your code.
+// Note that even with compression, the output array is likely to be bigger than the binary file..
+// Load compressed TTF fonts with ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF()
+
+#define _CRT_SECURE_NO_WARNINGS
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+
+// stb_compress* from stb.h - declaration
+typedef unsigned int stb_uint;
+typedef unsigned char stb_uchar;
+stb_uint stb_compress(stb_uchar *out,stb_uchar *in,stb_uint len);
+
+static bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression);
+
+int main(int argc, char** argv)
+{
+ if (argc < 3)
+ {
+ printf("Syntax: %s [-base85] [-nocompress] <inputfile> <symbolname>\n", argv[0]);
+ return 0;
+ }
+
+ int argn = 1;
+ bool use_base85_encoding = false;
+ bool use_compression = true;
+ if (argv[argn][0] == '-')
+ {
+ if (strcmp(argv[argn], "-base85") == 0) { use_base85_encoding = true; argn++; }
+ else if (strcmp(argv[argn], "-nocompress") == 0) { use_compression = false; argn++; }
+ else
+ {
+ printf("Unknown argument: '%s'\n", argv[argn]);
+ return 1;
+ }
+ }
+
+ binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression);
+ return 1;
+}
+
+char Encode85Byte(unsigned int x)
+{
+ x = (x % 85) + 35;
+ return (x>='\\') ? x+1 : x;
+}
+
+bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression)
+{
+ // Read file
+ FILE* f = fopen(filename, "rb");
+ if (!f) return false;
+ int data_sz;
+ if (fseek(f, 0, SEEK_END) || (data_sz = (int)ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return false; }
+ char* data = new char[data_sz+4];
+ if (fread(data, 1, data_sz, f) != (size_t)data_sz) { fclose(f); delete[] data; return false; }
+ memset((void *)(((char*)data) + data_sz), 0, 4);
+ fclose(f);
+
+ // Compress
+ int maxlen = data_sz + 512 + (data_sz >> 2) + sizeof(int); // total guess
+ char* compressed = use_compression ? new char[maxlen] : data;
+ int compressed_sz = use_compression ? stb_compress((stb_uchar*)compressed, (stb_uchar*)data, data_sz) : data_sz;
+ if (use_compression)
+ memset(compressed + compressed_sz, 0, maxlen - compressed_sz);
+
+ // Output as Base85 encoded
+ FILE* out = stdout;
+ fprintf(out, "// File: '%s' (%d bytes)\n", filename, (int)data_sz);
+ fprintf(out, "// Exported using binary_to_compressed_c.cpp\n");
+ const char* compressed_str = use_compression ? "compressed_" : "";
+ if (use_base85_encoding)
+ {
+ fprintf(out, "static const char %s_%sdata_base85[%d+1] =\n \"", symbol, compressed_str, (int)((compressed_sz+3)/4)*5);
+ for (int i = 0; i < compressed_sz; i += 4)
+ {
+ unsigned int d = *(unsigned int*)(compressed + i);
+ fprintf(out, "%c%c%c%c%c", Encode85Byte(d), Encode85Byte(d/85), Encode85Byte(d/7225), Encode85Byte(d/614125), Encode85Byte(d/52200625));
+ if ((i % 112) == 112-4)
+ fprintf(out, "\"\n \"");
+ }
+ fprintf(out, "\";\n\n");
+ }
+ else
+ {
+ fprintf(out, "static const unsigned int %s_%ssize = %d;\n", symbol, compressed_str, (int)compressed_sz);
+ fprintf(out, "static const unsigned int %s_%sdata[%d/4] =\n{", symbol, compressed_str, (int)((compressed_sz+3)/4)*4);
+ int column = 0;
+ for (int i = 0; i < compressed_sz; i += 4)
+ {
+ unsigned int d = *(unsigned int*)(compressed + i);
+ if ((column++ % 12) == 0)
+ fprintf(out, "\n 0x%08x, ", d);
+ else
+ fprintf(out, "0x%08x, ", d);
+ }
+ fprintf(out, "\n};\n\n");
+ }
+
+ // Cleanup
+ delete[] data;
+ if (use_compression)
+ delete[] compressed;
+ return true;
+}
+
+// stb_compress* from stb.h - definition
+
+//////////////////// compressor ///////////////////////
+
+static stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint 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 (s2 << 16) + s1;
+}
+
+static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)
+{
+ stb_uint i;
+ for (i=0; i < maxlen; ++i)
+ if (m1[i] != m2[i]) return i;
+ return i;
+}
+
+// simple implementation that just takes the source data in a big block
+
+static stb_uchar *stb__out;
+static FILE *stb__outfile;
+static stb_uint stb__outbytes;
+
+static void stb__write(unsigned char v)
+{
+ fputc(v, stb__outfile);
+ ++stb__outbytes;
+}
+
+#define stb_out(v) (stb__out ? *stb__out++ = (stb_uchar) (v) : stb__write((stb_uchar) (v)))
+
+static void stb_out2(stb_uint v)
+{
+ stb_out(v >> 8);
+ stb_out(v);
+}
+
+static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }
+static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16);
+stb_out(v >> 8 ); stb_out(v); }
+
+static void outliterals(stb_uchar *in, int numlit)
+{
+ while (numlit > 65536) {
+ outliterals(in,65536);
+ in += 65536;
+ numlit -= 65536;
+ }
+
+ if (numlit == 0) ;
+ else if (numlit <= 32) stb_out (0x000020 + numlit-1);
+ else if (numlit <= 2048) stb_out2(0x000800 + numlit-1);
+ else /* numlit <= 65536) */ stb_out3(0x070000 + numlit-1);
+
+ if (stb__out) {
+ memcpy(stb__out,in,numlit);
+ stb__out += numlit;
+ } else
+ fwrite(in, 1, numlit, stb__outfile);
+}
+
+static int stb__window = 0x40000; // 256K
+
+static int stb_not_crap(int best, int dist)
+{
+ return ((best > 2 && dist <= 0x00100)
+ || (best > 5 && dist <= 0x04000)
+ || (best > 7 && dist <= 0x80000));
+}
+
+static stb_uint stb__hashsize = 32768;
+
+// note that you can play with the hashing functions all you
+// want without needing to change the decompressor
+#define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c])
+#define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])
+#define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e])
+
+static unsigned int stb__running_adler;
+
+static int stb_compress_chunk(stb_uchar *history,
+ stb_uchar *start,
+ stb_uchar *end,
+ int length,
+ int *pending_literals,
+ stb_uchar **chash,
+ stb_uint mask)
+{
+ (void)history;
+ int window = stb__window;
+ stb_uint match_max;
+ stb_uchar *lit_start = start - *pending_literals;
+ stb_uchar *q = start;
+
+#define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask)
+
+ // stop short of the end so we don't scan off the end doing
+ // the hashing; this means we won't compress the last few bytes
+ // unless they were part of something longer
+ while (q < start+length && q+12 < end) {
+ int m;
+ stb_uint h1,h2,h3,h4, h;
+ stb_uchar *t;
+ int best = 2, dist=0;
+
+ if (q+65536 > end)
+ match_max = end-q;
+ else
+ match_max = 65536;
+
+#define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap(b,d)))
+
+#define STB__TRY(t,p) /* avoid retrying a match we already tried */ \
+ if (p ? dist != q-t : 1) \
+ if ((m = stb_matchlen(t, q, match_max)) > best) \
+ if (stb__nc(m,q-(t))) \
+ best = m, dist = q - (t)
+
+ // rather than search for all matches, only try 4 candidate locations,
+ // chosen based on 4 different hash functions of different lengths.
+ // this strategy is inspired by LZO; hashing is unrolled here using the
+ // 'hc' macro
+ h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);
+ t = chash[h1]; if (t) STB__TRY(t,0);
+ h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);
+ h = stb__hc2(q,h, 5, 6); t = chash[h2]; if (t) STB__TRY(t,1);
+ h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);
+ h = stb__hc2(q,h, 9,10); t = chash[h3]; if (t) STB__TRY(t,1);
+ h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);
+ t = chash[h4]; if (t) STB__TRY(t,1);
+
+ // because we use a shared hash table, can only update it
+ // _after_ we've probed all of them
+ chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;
+
+ if (best > 2)
+ assert(dist > 0);
+
+ // see if our best match qualifies
+ if (best < 3) { // fast path literals
+ ++q;
+ } else if (best > 2 && best <= 0x80 && dist <= 0x100) {
+ outliterals(lit_start, q-lit_start); lit_start = (q += best);
+ stb_out(0x80 + best-1);
+ stb_out(dist-1);
+ } else if (best > 5 && best <= 0x100 && dist <= 0x4000) {
+ outliterals(lit_start, q-lit_start); lit_start = (q += best);
+ stb_out2(0x4000 + dist-1);
+ stb_out(best-1);
+ } else if (best > 7 && best <= 0x100 && dist <= 0x80000) {
+ outliterals(lit_start, q-lit_start); lit_start = (q += best);
+ stb_out3(0x180000 + dist-1);
+ stb_out(best-1);
+ } else if (best > 8 && best <= 0x10000 && dist <= 0x80000) {
+ outliterals(lit_start, q-lit_start); lit_start = (q += best);
+ stb_out3(0x100000 + dist-1);
+ stb_out2(best-1);
+ } else if (best > 9 && dist <= 0x1000000) {
+ if (best > 65536) best = 65536;
+ outliterals(lit_start, q-lit_start); lit_start = (q += best);
+ if (best <= 0x100) {
+ stb_out(0x06);
+ stb_out3(dist-1);
+ stb_out(best-1);
+ } else {
+ stb_out(0x04);
+ stb_out3(dist-1);
+ stb_out2(best-1);
+ }
+ } else { // fallback literals if no match was a balanced tradeoff
+ ++q;
+ }
+ }
+
+ // if we didn't get all the way, add the rest to literals
+ if (q-start < length)
+ q = start+length;
+
+ // the literals are everything from lit_start to q
+ *pending_literals = (q - lit_start);
+
+ stb__running_adler = stb_adler32(stb__running_adler, start, q - start);
+ return q - start;
+}
+
+static int stb_compress_inner(stb_uchar *input, stb_uint length)
+{
+ int literals = 0;
+ stb_uint len,i;
+
+ stb_uchar **chash;
+ chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));
+ if (chash == NULL) return 0; // failure
+ for (i=0; i < stb__hashsize; ++i)
+ chash[i] = NULL;
+
+ // stream signature
+ stb_out(0x57); stb_out(0xbc);
+ stb_out2(0);
+
+ stb_out4(0); // 64-bit length requires 32-bit leading 0
+ stb_out4(length);
+ stb_out4(stb__window);
+
+ stb__running_adler = 1;
+
+ len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);
+ assert(len == length);
+
+ outliterals(input+length - literals, literals);
+
+ free(chash);
+
+ stb_out2(0x05fa); // end opcode
+
+ stb_out4(stb__running_adler);
+
+ return 1; // success
+}
+
+stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)
+{
+ stb__out = out;
+ stb__outfile = NULL;
+
+ stb_compress_inner(input, length);
+
+ return stb__out - out;
+}
diff --git a/NvCloth/samples/external/imgui/1.49/imconfig.h b/NvCloth/samples/external/imgui/1.49/imconfig.h
new file mode 100644
index 0000000..33cbadd
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/imconfig.h
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------------
+// USER IMPLEMENTATION
+// This file contains compile-time options for ImGui.
+// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO().
+//-----------------------------------------------------------------------------
+
+#pragma once
+
+//---- Define assertion handler. Defaults to calling assert().
+//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
+
+//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
+//#define IMGUI_API __declspec( dllexport )
+//#define IMGUI_API __declspec( dllimport )
+
+//---- Include imgui_user.h at the end of imgui.h
+//#define IMGUI_INCLUDE_IMGUI_USER_H
+
+//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions)
+//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS
+//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS
+
+//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty)
+//#define IMGUI_DISABLE_TEST_WINDOWS
+
+//---- Don't define obsolete functions names
+//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
+//---- Implement STB libraries in a namespace to avoid conflicts
+//#define IMGUI_STB_NAMESPACE ImGuiStb
+
+//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
+/*
+#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); }
+*/
+
+//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
+//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers.
+/*
+namespace ImGui
+{
+ void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL);
+}
+*/
+
diff --git a/NvCloth/samples/external/imgui/1.49/imgui.cpp b/NvCloth/samples/external/imgui/1.49/imgui.cpp
new file mode 100644
index 0000000..89fac50
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/imgui.cpp
@@ -0,0 +1,9724 @@
+// dear imgui, v1.49
+// (main code and documentation)
+
+// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code.
+// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase.
+// Get latest version at https://github.com/ocornut/imgui
+// Releases change-log at https://github.com/ocornut/imgui/releases
+// 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, e.g: https://www.patreon.com/imgui
+
+/*
+
+ Index
+ - MISSION STATEMENT
+ - END-USER GUIDE
+ - PROGRAMMER GUIDE (read me!)
+ - API BREAKING CHANGES (read me when you update!)
+ - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
+ - How can I help?
+ - How do I update to a newer version of ImGui?
+ - What is ImTextureID and how do I display an image?
+ - I integrated ImGui in my engine and the text or lines are blurry..
+ - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs.
+ - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
+ - How can I load a different font than the default?
+ - 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)
+ - ISSUES & TODO-LIST
+ - CODE
+
+
+ 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 (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything)
+ - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html
+
+ 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
+ - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction.
+
+
+ END-USER GUIDE
+ ==============
+
+ - double-click 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
+ - click and drag on any empty space to move window
+ - double-click/double-tap on lower right corner grip to auto-fit to content
+ - TAB/SHIFT+TAB to cycle through keyboard editable fields
+ - use mouse wheel to scroll
+ - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true)
+ - CTRL+Click on a slider or drag box to input value as text
+ - 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!)
+
+
+ PROGRAMMER GUIDE
+ ================
+
+ - read the FAQ below this section!
+ - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs.
+ - call and read ImGui::ShowTestWindow() for demo code demonstrating most features.
+ - see examples/ folder for standalone sample applications. Prefer reading examples/opengl_example/ first as it is the simplest.
+ you may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
+ - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme).
+
+ - getting started:
+ - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'.
+ - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory.
+ - every frame:
+ 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input'
+ 2/ call ImGui::NewFrame() as early as you can!
+ 3/ use any ImGui function you want between NewFrame() and Render()
+ 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure.
+ (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.)
+ - all rendering information are stored into command-lists until ImGui::Render() is called.
+ - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler 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.
+ - refer to the examples applications in the examples/ folder for instruction on how to setup your code.
+ - a typical application skeleton may be:
+
+ // Application init
+ ImGuiIO& io = ImGui::GetIO();
+ io.DisplaySize.x = 1920.0f;
+ io.DisplaySize.y = 1280.0f;
+ io.IniFilename = "imgui.ini";
+ io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data.
+ // TODO: Fill others settings of the io structure
+
+ // Load texture atlas
+ // There is a default font so you don't need to care about choosing a font yet
+ unsigned char* pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
+ // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system
+ // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'
+
+ // Application main loop
+ while (true)
+ {
+ // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.)
+ // TODO: fill all fields of IO structure and call NewFrame
+ ImGuiIO& io = ImGui::GetIO();
+ io.DeltaTime = 1.0f/60.0f;
+ io.MousePos = mouse_pos;
+ io.MouseDown[0] = mouse_button_0;
+ io.MouseDown[1] = mouse_button_1;
+ io.KeysDown[i] = ...
+
+ // 2) call NewFrame(), after this point you can use ImGui::* functions anytime
+ ImGui::NewFrame();
+
+ // 3) most of your application code here
+ ImGui::Begin("My window");
+ ImGui::Text("Hello, world.");
+ ImGui::End();
+ MyGameUpdate(); // may use ImGui functions
+ MyGameRender(); // may use ImGui functions
+
+ // 4) render & swap video buffers
+ ImGui::Render();
+ SwapBuffers();
+ }
+
+ - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your
+ inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information.
+
+
+ API BREAKING CHANGES
+ ====================
+
+ Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
+ Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
+ Also read releases logs https://github.com/ocornut/imgui/releases for more details.
+
+ - 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.
+ However 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 ImDraw::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!
+ ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
+ became:
+ ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
+ argument 'cmd_lists' -> 'draw_data->CmdLists'
+ argument 'cmd_lists_count' -> 'draw_data->CmdListsCount'
+ ImDrawList 'commands' -> 'CmdBuffer'
+ ImDrawList 'vtx_buffer' -> 'VtxBuffer'
+ ImDrawList n/a -> 'IdxBuffer' (new)
+ ImDrawCmd 'vtx_count' -> 'ElemCount'
+ ImDrawCmd 'clip_rect' -> 'ClipRect'
+ ImDrawCmd 'user_callback' -> 'UserCallback'
+ ImDrawCmd 'texture_id' -> '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 (will obsolete).
+ - 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 (will obsolete).
+ - 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 (will obsolete).
+ - 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 (will obsolete).
+ - 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.
+ this sequence:
+ const void* png_data;
+ unsigned int png_size;
+ ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
+ // <Copy to GPU>
+ became:
+ unsigned char* pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
+ // <Copy to GPU>
+ io.Fonts->TexID = (your_texture_identifier);
+ you now have much 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 help?
+ A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help!
+ - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time.
+
+ Q: How do I update to a newer version of ImGui?
+ A: Overwrite the following files:
+ imgui.cpp
+ imgui.h
+ imgui_demo.cpp
+ imgui_draw.cpp
+ imgui_internal.h
+ stb_rect_pack.h
+ stb_textedit.h
+ stb_truetype.h
+ Don't overwrite imconfig.h if you have made modification to your copy.
+ Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name
+ in the code, there will likely be a comment about it. Please report any issue to the GitHub page!
+
+
+ Q: What is ImTextureID and how do I display an image?
+ A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
+ ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
+ It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
+ At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
+ Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
+ (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
+ To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
+ ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
+ It is your responsibility to get textures uploaded to your GPU.
+
+ Q: I integrated 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 ImGui in my engine and some elements are clipping or disappearing when I move windows around..
+ A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1,y1,x2,y2) and NOT as (x1,y1,width,height).
+
+ Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)
+ A: Yes. A primer on the use of labels/IDs in ImGui..
+
+ - Elements that are not clickable, such as Text() items don't need an ID.
+
+ - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget).
+ to do so they need an unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
+
+ 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. so no conflict can happen if you have two buttons called "OK" in two different windows
+ or in two different locations of a tree.
+
+ - If you have a same ID twice in the same location, you'll have a conflict:
+
+ Button("OK");
+ Button("OK"); // ID collision! Both buttons will be treated as the same.
+
+ Fear not! this is easy to solve and there are many ways to solve it!
+
+ - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases.
+ use "##" to pass a complement to the ID that won't be visible to the end-user:
+
+ Button("Play"); // Label = "Play", ID = hash of "Play"
+ Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
+ Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
+
+ - If you want to completely hide the label, but still need an ID:
+
+ Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
+
+ - 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 (and windows are uniquely identified by their ID.. obviously)
+ 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)
+
+ sprintf(buf, "My game (%f FPS)###MyGame");
+ Begin(buf); // Variable label, ID = hash of "MyGame"
+
+ - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
+ This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
+ You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack!
+
+ for (int i = 0; i < 100; i++)
+ {
+ PushID(i);
+ Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
+ PopID();
+ }
+
+ for (int i = 0; i < 100; i++)
+ {
+ MyObject* obj = Objects[i];
+ PushID(obj);
+ Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
+ PopID();
+ }
+
+ for (int i = 0; i < 100; i++)
+ {
+ MyObject* obj = Objects[i];
+ PushID(obj->Name);
+ Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
+ PopID();
+ }
+
+ - 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" + 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 displaying a single object that may change over time (1-1 relationship), 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. experiment and see what makes more sense!
+
+ Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
+ A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame.
+ When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
+ When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available.
+ ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow().
+
+ Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
+ A: Use the font atlas to load the TTF file you want:
+
+ ImGuiIO& io = ImGui::GetIO();
+ io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
+ io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
+
+ Q: How can I load multiple fonts?
+ A: Use the font atlas to pack them into a single texture:
+ (Read extra_fonts/README.txt 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.GlyphExtraSpacing.x = 1.0f;
+ io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
+
+ // Combine multiple fonts into one
+ ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
+ ImFontConfig config;
+ config.MergeMode = true;
+ io.Fonts->AddFontDefault();
+ io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges);
+ io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese());
+
+ 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.
+ All your strings needs to use UTF-8 encoding. 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.
+ In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
+ You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
+
+ io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters
+ io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
+ io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application
+
+ As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that.
+
+ Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
+ A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha,
+ then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
+
+ - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will 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 create widgets without a Begin()/End() block, they will go in an implicit window called "Debug"
+ - 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 call Render() multiple times (e.g for VR renders).
+ - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui!
+
+
+ ISSUES & TODO-LIST
+ ==================
+ Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues
+ The list below consist mostly of notes of things to do before they are requested/discussed by users (at that point it usually happens on the github)
+
+ - doc: add a proper documentation+regression testing system (#435)
+ - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
+ - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis).
+ - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify.
+ - window: allow resizing of child windows (possibly given min/max for each axis?)
+ - window: background options for child windows, border option (disable rounding)
+ - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip)
+ - window: resizing from any sides? + mouse cursor directives for app.
+!- window: begin with *p_open == false should return false.
+ - window: get size/pos helpers given names (see discussion in #249)
+ - window: a collapsed window can be stuck behind the main menu bar?
+ - window: when window is small, prioritize resize button over close button.
+ - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later.
+ - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic.
+ - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd.
+ - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command).
+!- scrolling: allow immediately effective change of scroll if we haven't appended items yet
+ - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
+ - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc.
+ - widgets: clean up widgets internal toward exposing everything.
+ - widgets: add disabled and read-only modes (#211)
+ - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them.
+!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows).
+ - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
+ - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
+ - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now.
+ - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541)
+ - input text: flag to disable live update of the user buffer (also applies to float/int text input)
+ - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text?
+ - input text: add ImGuiInputTextFlags_EnterToApply? (off #218)
+ - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc).
+ - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200)
+ - input text multi-line: line numbers? status bar? (follow up on #200)
+ - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position.
+ - input number: optional range min/max for Input*() functions
+ - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled)
+ - input number: use mouse wheel to step up/down
+ - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack.
+ - button: provide a button that looks framed.
+ - text: proper alignment options
+ - image/image button: misalignment on padded/bordered button?
+ - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that?
+ - layout: horizontal layout helper (#97)
+ - layout: horizontal flow until no space left (#404)
+ - layout: more generic alignment state (left/right/centered) for single items?
+ - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding.
+ - layout: BeginGroup() needs a border option.
+ - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125)
+ - columns: add a conditional parameter to SetColumnOffset() (#513, #125)
+ - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125)
+ - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125)
+ - columns: user specify columns size (#513, #125)
+ - columns: flag to add horizontal separator above/below?
+ - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets)
+ - combo: sparse combo boxes (via function call?) / iterators
+ - combo: contents should extends to fit label if combo widget is small
+ - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203)
+ - listbox: multiple selection
+ - listbox: user may want to initial scroll to focus on the one selected value?
+ - listbox: keyboard navigation.
+ - listbox: scrolling should track modified selection.
+!- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402)
+ - popups: add variant using global identifier similar to Begin/End (#402)
+ - popups: border options. richer api like BeginChild() perhaps? (#197)
+ - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last prefered button" and may teleport when moving mouse
+ - menus: local shortcuts, global shortcuts (#456, #126)
+ - menus: icons
+ - menus: menubars: some sort of priority / effect of main menu-bar on desktop size?
+ - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely
+ - statusbar: add a per-window status bar helper similar to what menubar does.
+ - tabs (#261, #351)
+ - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y)
+!- color: the color helpers/typing is a mess and needs sorting out.
+ - color: add a better color picker (#346)
+ - node/graph editor (#306)
+ - pie menus patterns (#434)
+ - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479)
+ - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals)
+ - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots)
+ - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value)
+ - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
+ - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
+ - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar).
+ - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate.
+ - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign)
+ - slider & drag: int data passing through a float
+ - drag float: up/down axis
+ - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits)
+ - tree node / optimization: avoid formatting when clipped.
+ - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling.
+ - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings?
+ - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits?
+ - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer)
+ - tree node: tweak color scheme to distinguish headers from selected tree node (#581)
+ - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249)
+ - settings: write more decent code to allow saving/loading new fields
+ - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file
+ - style: add window shadows.
+ - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding.
+ - style: color-box not always square?
+ - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc.
+ - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation).
+ - style/opt: PopStyleVar could be optimized by having GetStyleVar returns the type, using a table mapping stylevar enum to data type.
+ - style: global scale setting.
+ - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle
+ - text: simple markup language for color change?
+ - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
+ - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance
+ - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback.
+ - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize)
+ - font: fix AddRemapChar() to work before font has been built.
+ - log: LogButtons() options for specifying depth and/or hiding depth slider
+ - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
+ - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard)
+ - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs.
+ - filters: set a current filter that tree node can automatically query to hide themselves
+ - filters: handle wildcards (with implicit leading/trailing *), regexps
+ - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus)
+!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing
+ - keyboard: full keyboard navigation and focus. (#323)
+ - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622)
+ - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame)
+ - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71)
+ - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style).
+ - input: support track pad style scrolling & slider edit.
+ - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL)
+ - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon?
+ - misc: provide HoveredTime and ActivatedTime to ease the creation of animations.
+ - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438)
+ - style editor: color child window height expressed in multiple of line height.
+ - remote: make a system like RemoteImGui first-class citizen/project (#75)
+ - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?)
+ - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack.
+ - examples: directx9: save/restore device state more thoroughly.
+ - examples: window minimize, maximize (#583)
+ - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335)
+ - optimization: use another hash function than crc32, e.g. FNV1a
+ - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)?
+ - optimization: turn some the various stack vectors into statically-sized arrays
+ - optimization: better clipping for multi-component widgets
+*/
+
+#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "imgui.h"
+#define IMGUI_DEFINE_MATH_OPERATORS
+#define IMGUI_DEFINE_PLACEMENT_NEW
+#include "imgui_internal.h"
+
+#include <ctype.h> // toupper, isprint
+#include <math.h> // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf
+#include <stdlib.h> // NULL, malloc, free, qsort, atoi
+#include <stdio.h> // vsnprintf, sscanf, printf
+#include <limits.h> // INT_MIN, INT_MAX
+#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
+#include <stddef.h> // intptr_t
+#else
+#include <stdint.h> // intptr_t
+#endif
+
+#ifdef _MSC_VER
+#pragma warning (disable: 4127) // condition expression is constant
+#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 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 "-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 "-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
+#endif
+
+//-------------------------------------------------------------------------
+// Forward Declarations
+//-------------------------------------------------------------------------
+
+static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
+
+static void PushMultiItemsWidths(int components, float w_full = 0.0f);
+static float GetDraggedColumnOffset(int column_index);
+
+static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
+
+static void SetCurrentFont(ImFont* font);
+static void SetCurrentWindow(ImGuiWindow* window);
+static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
+static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond);
+static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond);
+static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond);
+static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
+static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
+static inline bool IsWindowContentHoverable(ImGuiWindow* window);
+static void ClearSetNextWindowData();
+static void CheckStacksSize(ImGuiWindow* window, bool write);
+static void Scrollbar(ImGuiWindow* window, bool horizontal);
+
+static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list);
+static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window);
+static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window);
+
+static ImGuiIniData* FindWindowSettings(const char* name);
+static ImGuiIniData* AddWindowSettings(const char* name);
+static void LoadSettings();
+static void SaveSettings();
+static void MarkSettingsDirty();
+
+static void PushColumnClipRect(int column_index = -1);
+static ImRect GetVisibleRect();
+
+static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags);
+static void CloseInactivePopups();
+static void ClosePopupToLevel(int remaining);
+static void ClosePopup(ImGuiID id);
+static bool IsPopupOpen(ImGuiID id);
+static ImGuiWindow* GetFrontMostModalRootWindow();
+static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid);
+
+static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback 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);
+
+static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
+static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
+static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
+static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
+
+//-----------------------------------------------------------------------------
+// Platform dependent default implementations
+//-----------------------------------------------------------------------------
+
+static const char* GetClipboardTextFn_DefaultImpl();
+static void SetClipboardTextFn_DefaultImpl(const char* text);
+static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
+
+//-----------------------------------------------------------------------------
+// Context
+//-----------------------------------------------------------------------------
+
+// Default context, default font atlas.
+// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable.
+static ImGuiContext GImDefaultContext;
+static ImFontAtlas GImDefaultFontAtlas;
+
+// Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext()
+// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by (A) having two instances of the ImGui code under different namespaces or (B) change this variable to be TLS. Further development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
+ImGuiContext* GImGui = &GImDefaultContext;
+
+//-----------------------------------------------------------------------------
+// User facing structures
+//-----------------------------------------------------------------------------
+
+ImGuiStyle::ImGuiStyle()
+{
+ Alpha = 1.0f; // Global alpha applies to everything in ImGui
+ WindowPadding = ImVec2(8,8); // Padding within a window
+ WindowMinSize = ImVec2(32,32); // Minimum window size
+ WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
+ WindowTitleAlign = ImGuiAlign_Left; // Alignment for title bar text
+ ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
+ 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).
+ 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.
+ DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
+ DisplaySafeAreaPadding = ImVec2(4,4); // 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.
+ AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
+ AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
+ CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
+
+ 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_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
+ Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f);
+ Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
+ Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
+ Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
+ Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
+ Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
+ Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
+ 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.80f, 0.50f, 0.50f, 0.40f);
+ Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
+ 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.80f, 0.50f, 0.50f, 1.00f);
+ Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
+ Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f);
+ Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 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_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
+ Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f);
+ Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f);
+ Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
+ Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
+ Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
+ Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
+ Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
+ Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
+ 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_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
+}
+
+ImGuiIO::ImGuiIO()
+{
+ // Most fields are initialized with zero
+ memset(this, 0, sizeof(*this));
+
+ DisplaySize = ImVec2(-1.0f, -1.0f);
+ DeltaTime = 1.0f/60.0f;
+ IniSavingRate = 5.0f;
+ IniFilename = "imgui.ini";
+ LogFilename = "imgui_log.txt";
+ Fonts = &GImDefaultFontAtlas;
+ FontGlobalScale = 1.0f;
+ DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
+ MousePos = ImVec2(-1,-1);
+ MousePosPrev = ImVec2(-1,-1);
+ MouseDoubleClickTime = 0.30f;
+ MouseDoubleClickMaxDist = 6.0f;
+ 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 < ImGuiKey_COUNT; i++)
+ KeyMap[i] = -1;
+ KeyRepeatDelay = 0.250f;
+ KeyRepeatRate = 0.050f;
+ UserData = NULL;
+
+ // User functions
+ RenderDrawListsFn = NULL;
+ MemAllocFn = malloc;
+ MemFreeFn = free;
+ GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
+ SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
+ ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
+
+ // Set OS X style defaults based on __APPLE__ compile time flag
+#ifdef __APPLE__
+ WordMovementUsesAltKey = true; // OS X style: Text editing cursor movement using Alt instead of Ctrl
+ ShortcutsUseSuperKey = true; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
+ DoubleClickSelectsWord = true; // OS X style: Double click selects by word instead of selecting whole text
+ MultiSelectUsesSuperKey = true; // OS X style: Multi-selection in lists uses Cmd/Super instead of Ctrl
+#endif
+}
+
+// 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]);
+}
+
+//-----------------------------------------------------------------------------
+// HELPERS
+//-----------------------------------------------------------------------------
+
+#define IM_F32_TO_INT8(_VAL) ((int)((_VAL) * 255.0f + 0.5f))
+
+// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
+#ifdef _WIN32
+#define IM_NEWLINE "\r\n"
+#else
+#define IM_NEWLINE "\n"
+#endif
+
+bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c)
+{
+ 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));
+}
+
+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, int count)
+{
+ int d = 0;
+ while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
+ return d;
+}
+
+char* ImStrdup(const char *str)
+{
+ size_t len = strlen(str) + 1;
+ void* buff = ImGui::MemAlloc(len);
+ return (char*)memcpy(buff, (const void*)str, len);
+}
+
+int ImStrlenW(const ImWchar* str)
+{
+ int n = 0;
+ while (*str++) n++;
+ return n;
+}
+
+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;
+}
+
+int ImFormatString(char* buf, int buf_size, const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ int w = vsnprintf(buf, buf_size, fmt, args);
+ va_end(args);
+ buf[buf_size-1] = 0;
+ return (w == -1) ? buf_size : w;
+}
+
+int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args)
+{
+ int w = vsnprintf(buf, buf_size, fmt, args);
+ buf[buf_size-1] = 0;
+ return (w == -1) ? buf_size : w;
+}
+
+// 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;
+}
+
+//-----------------------------------------------------------------------------
+// ImText* helpers
+//-----------------------------------------------------------------------------
+
+// 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;
+ }
+}
+
+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;
+}
+
+ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
+{
+ float s = 1.0f/255.0f;
+ return ImVec4((in & 0xFF) * s, ((in >> 8) & 0xFF) * s, ((in >> 16) & 0xFF) * s, (in >> 24) * s);
+}
+
+ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
+{
+ ImU32 out;
+ out = ((ImU32)IM_F32_TO_INT8(ImSaturate(in.x)));
+ out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.y))) << 8;
+ out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.z))) << 16;
+ out |= ((ImU32)IM_F32_TO_INT8(ImSaturate(in.w))) << 24;
+ 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)
+ {
+ const float tmp = g; g = b; b = tmp;
+ K = -1.f;
+ }
+ if (r < g)
+ {
+ const float tmp = r; r = g; g = tmp;
+ K = -2.f / 6.f - K;
+ }
+
+ const float chroma = r - (g < b ? g : b);
+ out_h = fabsf(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 = fmodf(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;
+ }
+}
+
+// Load file content into memory
+// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
+void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
+{
+ IM_ASSERT(filename && file_open_mode);
+ if (out_file_size)
+ *out_file_size = 0;
+
+ FILE* f;
+ if ((f = fopen(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;
+ }
+
+ int file_size = (int)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, (size_t)file_size, f) != (size_t)file_size)
+ {
+ fclose(f);
+ ImGui::MemFree(file_data);
+ return NULL;
+ }
+ if (padding_bytes > 0)
+ memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
+
+ fclose(f);
+ if (out_file_size)
+ *out_file_size = file_size;
+
+ return file_data;
+}
+
+//-----------------------------------------------------------------------------
+// ImGuiStorage
+//-----------------------------------------------------------------------------
+
+// Helper: Key->value storage
+void ImGuiStorage::Clear()
+{
+ Data.clear();
+}
+
+// std::lower_bound but without the bullshit
+static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImU32 key)
+{
+ ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
+ ImVector<ImGuiStorage::Pair>::iterator last = data.end();
+ int count = (int)(last - first);
+ while (count > 0)
+ {
+ int count2 = count / 2;
+ ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
+ if (mid->key < key)
+ {
+ first = ++mid;
+ count -= count2 + 1;
+ }
+ else
+ {
+ count = count2;
+ }
+ }
+ return first;
+}
+
+int ImGuiStorage::GetInt(ImU32 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(ImU32 key, bool default_val) const
+{
+ return GetInt(key, default_val ? 1 : 0) != 0;
+}
+
+float ImGuiStorage::GetFloat(ImU32 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(ImU32 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(ImU32 key, bool val)
+{
+ SetInt(key, val ? 1 : 0);
+}
+
+void ImGuiStorage::SetFloat(ImU32 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(ImU32 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;
+}
+
+//-----------------------------------------------------------------------------
+// ImGuiTextFilter
+//-----------------------------------------------------------------------------
+
+// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
+ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
+{
+ if (default_filter)
+ {
+ ImFormatString(InputBuf, IM_ARRAYSIZE(InputBuf), "%s", default_filter);
+ 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)
+{
+ 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++)
+ {
+ Filters[i].trim_blanks();
+ if (Filters[i].empty())
+ continue;
+ if (Filters[i].front() != '-')
+ 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.front() == '-')
+ {
+ // 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;
+}
+
+//-----------------------------------------------------------------------------
+// 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
+#define va_copy(dest, src) (dest = src)
+#endif
+
+// Helper: Text buffer for logging/accumulating text
+void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
+{
+ va_list args_copy;
+ va_copy(args_copy, args);
+
+ int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
+ if (len <= 0)
+ return;
+
+ const int write_off = Buf.Size;
+ 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, len+1, fmt, args_copy);
+}
+
+void ImGuiTextBuffer::append(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ appendv(fmt, args);
+ va_end(args);
+}
+
+//-----------------------------------------------------------------------------
+// ImGuiSimpleColumns
+//-----------------------------------------------------------------------------
+
+ImGuiSimpleColumns::ImGuiSimpleColumns()
+{
+ Count = 0;
+ Spacing = Width = NextWidth = 0.0f;
+ memset(Pos, 0, sizeof(Pos));
+ memset(NextWidths, 0, sizeof(NextWidths));
+}
+
+void ImGuiSimpleColumns::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 ImGuiSimpleColumns::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 ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
+{
+ return ImMax(0.0f, avail_w - Width);
+}
+
+//-----------------------------------------------------------------------------
+// ImGuiListClipper
+//-----------------------------------------------------------------------------
+
+static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
+{
+ // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
+ // 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.
+ ImGui::SetCursorPosY(pos_y);
+ ImGuiWindow* window = ImGui::GetCurrentWindow();
+ window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;
+ window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y);
+}
+
+// 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
+ ImGui::SetCursorPosY(StartPosY); // Rewind cursor so we can Begin() again, this time with a known height.
+ Begin(ItemsCount, items_height);
+ 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;
+}
+
+//-----------------------------------------------------------------------------
+// ImGuiWindow
+//-----------------------------------------------------------------------------
+
+ImGuiWindow::ImGuiWindow(const char* name)
+{
+ Name = ImStrdup(name);
+ ID = ImHash(name, 0);
+ IDStack.push_back(ID);
+ MoveID = GetID("#MOVE");
+
+ Flags = 0;
+ IndexWithinParent = 0;
+ PosFloat = 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);
+ Scroll = ImVec2(0.0f, 0.0f);
+ ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
+ ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
+ ScrollbarX = ScrollbarY = false;
+ ScrollbarSizes = ImVec2(0.0f, 0.0f);
+ BorderSize = 0.0f;
+ Active = WasActive = false;
+ Accessed = false;
+ Collapsed = false;
+ SkipItems = false;
+ BeginCount = 0;
+ PopupID = 0;
+ AutoFitFramesX = AutoFitFramesY = -1;
+ AutoFitOnlyGrows = false;
+ AutoPosLastDirection = -1;
+ HiddenFrames = 0;
+ SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing;
+ SetWindowPosCenterWanted = false;
+
+ LastFrameActive = -1;
+ ItemWidthDefault = 0.0f;
+ FontWindowScale = 1.0f;
+
+ DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList));
+ IM_PLACEMENT_NEW(DrawList) ImDrawList();
+ DrawList->_OwnerName = Name;
+ RootWindow = NULL;
+ RootNonPopupWindow = NULL;
+ ParentWindow = NULL;
+
+ FocusIdxAllCounter = FocusIdxTabCounter = -1;
+ FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
+ FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
+}
+
+ImGuiWindow::~ImGuiWindow()
+{
+ DrawList->~ImDrawList();
+ ImGui::MemFree(DrawList);
+ DrawList = NULL;
+ ImGui::MemFree(Name);
+ Name = NULL;
+}
+
+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;
+}
+
+//-----------------------------------------------------------------------------
+// Internal API exposed in imgui_internal.h
+//-----------------------------------------------------------------------------
+
+static void SetCurrentWindow(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ g.CurrentWindow = window;
+ if (window)
+ g.FontSize = window->CalcFontSize();
+}
+
+ImGuiWindow* ImGui::GetParentWindow()
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.CurrentWindowStack.Size >= 2);
+ return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2];
+}
+
+void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window = NULL)
+{
+ ImGuiContext& g = *GImGui;
+ g.ActiveId = id;
+ g.ActiveIdAllowOverlap = false;
+ g.ActiveIdIsJustActivated = true;
+ g.ActiveIdWindow = window;
+}
+
+void ImGui::SetHoveredID(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ g.HoveredId = id;
+ g.HoveredIdAllowOverlap = false;
+}
+
+void ImGui::KeepAliveID(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.ActiveId == id)
+ g.ActiveIdIsAlive = true;
+}
+
+// Advance cursor given item size for layout.
+void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ // Always align ourselves on pixel boundaries
+ ImGuiContext& g = *GImGui;
+ const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
+ const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
+ 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.IndentX + window->DC.ColumnsOffsetX), (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);
+
+ //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug
+
+ window->DC.PrevLineHeight = line_height;
+ window->DC.PrevLineTextBaseOffset = text_base_offset;
+ window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
+}
+
+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
+// declares 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, const ImGuiID* id)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.LastItemID = id ? *id : 0;
+ window->DC.LastItemRect = bb;
+ window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
+ if (IsClippedEx(bb, id, false))
+ return false;
+
+ // This is a sensible default, but widgets are free to override it after calling ItemAdd()
+ ImGuiContext& g = *GImGui;
+ if (IsMouseHoveringRect(bb.Min, bb.Max))
+ {
+ // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background)
+ // So that clicking on items with no active id such as Text() still returns true with IsItemHovered()
+ window->DC.LastItemHoveredRect = true;
+ if (g.HoveredRootWindow == window->RootWindow)
+ if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveID))
+ if (IsWindowContentHoverable(window))
+ window->DC.LastItemHoveredAndUsable = true;
+ }
+
+ return true;
+}
+
+bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindowRead();
+
+ if (!bb.Overlaps(window->ClipRect))
+ if (!id || *id != GImGui->ActiveId)
+ if (clip_even_when_logged || !g.LogEnabled)
+ return true;
+ return false;
+}
+
+// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic.
+bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap)
+ {
+ ImGuiWindow* window = GetCurrentWindowRead();
+ if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow))
+ if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max))
+ if (IsWindowContentHoverable(g.HoveredRootWindow))
+ return true;
+ }
+ return false;
+}
+
+bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop)
+{
+ ImGuiContext& g = *GImGui;
+
+ const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus;
+ window->FocusIdxAllCounter++;
+ if (allow_keyboard_focus)
+ window->FocusIdxTabCounter++;
+
+ // Process keyboard input at this point: TAB, Shift-TAB switch focus
+ // We can always TAB out of a widget that doesn't allow tabbing in.
+ if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab))
+ {
+ // Modulo on index will be applied at the end of frame once we've got the total counter of items.
+ window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1);
+ }
+
+ if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
+ return true;
+
+ if (allow_keyboard_focus)
+ if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
+ 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
+
+ const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f;
+ return wrap_width;
+}
+
+//-----------------------------------------------------------------------------
+
+void* ImGui::MemAlloc(size_t sz)
+{
+ GImGui->IO.MetricsAllocs++;
+ return GImGui->IO.MemAllocFn(sz);
+}
+
+void ImGui::MemFree(void* ptr)
+{
+ if (ptr) GImGui->IO.MetricsAllocs--;
+ return GImGui->IO.MemFreeFn(ptr);
+}
+
+const char* ImGui::GetClipboardText()
+{
+ return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn() : "";
+}
+
+void ImGui::SetClipboardText(const char* text)
+{
+ if (GImGui->IO.SetClipboardTextFn)
+ GImGui->IO.SetClipboardTextFn(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)
+{
+ GImGui = ctx;
+}
+
+ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*))
+{
+ if (!malloc_fn) malloc_fn = malloc;
+ ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext));
+ IM_PLACEMENT_NEW(ctx) ImGuiContext();
+ ctx->IO.MemAllocFn = malloc_fn;
+ ctx->IO.MemFreeFn = free_fn ? free_fn : free;
+ return ctx;
+}
+
+void ImGui::DestroyContext(ImGuiContext* ctx)
+{
+ void (*free_fn)(void*) = ctx->IO.MemFreeFn;
+ ctx->~ImGuiContext();
+ free_fn(ctx);
+ if (GImGui == ctx)
+ GImGui = NULL;
+}
+
+ImGuiIO& ImGui::GetIO()
+{
+ return GImGui->IO;
+}
+
+ImGuiStyle& ImGui::GetStyle()
+{
+ return GImGui->Style;
+}
+
+// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
+ImDrawData* ImGui::GetDrawData()
+{
+ return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
+}
+
+float ImGui::GetTime()
+{
+ return GImGui->Time;
+}
+
+int ImGui::GetFrameCount()
+{
+ return GImGui->FrameCount;
+}
+
+void ImGui::NewFrame()
+{
+ ImGuiContext& g = *GImGui;
+
+ // Check user data
+ 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);
+ IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
+ IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
+ IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting
+
+ if (!g.Initialized)
+ {
+ // Initialize on first frame
+ g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer));
+ IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer();
+
+ IM_ASSERT(g.Settings.empty());
+ LoadSettings();
+ g.Initialized = true;
+ }
+
+ SetCurrentFont(g.IO.Fonts->Fonts[0]);
+
+ g.Time += g.IO.DeltaTime;
+ g.FrameCount += 1;
+ g.Tooltip[0] = '\0';
+ g.OverlayDrawList.Clear();
+ g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
+ g.OverlayDrawList.PushClipRectFullScreen();
+ g.OverlayDrawList.AddDrawCmd();
+
+ // Mark rendering data as invalid to prevent user who may have a handle on it to use it
+ g.RenderDrawData.Valid = false;
+ g.RenderDrawData.CmdLists = NULL;
+ g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
+
+ // Update inputs state
+ if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0)
+ g.IO.MousePos = ImVec2(-9999.0f, -9999.0f);
+ if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta
+ g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
+ else
+ g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
+ 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 (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
+ {
+ if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < 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.MouseDragMaxDistanceSqr[i] = 0.0f;
+ }
+ else if (g.IO.MouseDown[i])
+ {
+ g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]));
+ }
+ }
+ 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;
+
+ // 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 = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
+
+ // Clear reference to active widget if the widget isn't alive anymore
+ g.HoveredIdPreviousFrame = g.HoveredId;
+ g.HoveredId = 0;
+ g.HoveredIdAllowOverlap = false;
+ if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
+ SetActiveID(0);
+ g.ActiveIdPreviousFrame = g.ActiveId;
+ g.ActiveIdIsAlive = false;
+ g.ActiveIdIsJustActivated = false;
+
+ // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
+ if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId)
+ {
+ KeepAliveID(g.MovedWindowMoveId);
+ IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow);
+ IM_ASSERT(g.MovedWindow->RootWindow->MoveID == g.MovedWindowMoveId);
+ if (g.IO.MouseDown[0])
+ {
+ if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove))
+ {
+ g.MovedWindow->PosFloat += g.IO.MouseDelta;
+ if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings))
+ MarkSettingsDirty();
+ }
+ FocusWindow(g.MovedWindow);
+ }
+ else
+ {
+ SetActiveID(0);
+ g.MovedWindow = NULL;
+ g.MovedWindowMoveId = 0;
+ }
+ }
+ else
+ {
+ g.MovedWindow = NULL;
+ g.MovedWindowMoveId = 0;
+ }
+
+ // Delay saving settings so we don't spam disk too much
+ if (g.SettingsDirtyTimer > 0.0f)
+ {
+ g.SettingsDirtyTimer -= g.IO.DeltaTime;
+ if (g.SettingsDirtyTimer <= 0.0f)
+ SaveSettings();
+ }
+
+ // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow
+ g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false);
+ if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow))
+ g.HoveredRootWindow = g.HoveredWindow->RootWindow;
+ else
+ g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true);
+
+ if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow())
+ {
+ g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
+ ImGuiWindow* window = g.HoveredRootWindow;
+ while (window && window != modal_window)
+ window = window->ParentWindow;
+ if (!window)
+ g.HoveredRootWindow = g.HoveredWindow = NULL;
+ }
+ else
+ {
+ g.ModalWindowDarkeningRatio = 0.0f;
+ }
+
+ // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application.
+ // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
+ 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[mouse_earliest_button_down] > g.IO.MouseClickedTime[i])
+ mouse_earliest_button_down = i;
+ }
+ bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
+ if (g.CaptureMouseNextFrame != -1)
+ g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0);
+ else
+ g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty());
+ g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0);
+ g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId);
+ g.MouseCursor = ImGuiMouseCursor_Arrow;
+ g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1;
+ g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
+
+ // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
+ if (!mouse_avail_to_imgui)
+ g.HoveredWindow = g.HoveredRootWindow = NULL;
+
+ // Scale & Scrolling
+ if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
+ {
+ ImGuiWindow* window = g.HoveredWindow;
+ if (g.IO.KeyCtrl)
+ {
+ if (g.IO.FontAllowUserScaling)
+ {
+ // Zoom / Scale window
+ float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
+ 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->PosFloat += offset;
+ window->Size *= scale;
+ window->SizeFull *= scale;
+ }
+ }
+ else
+ {
+ // Scroll
+ if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
+ {
+ const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5;
+ SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines);
+ }
+ }
+ }
+
+ // Pressing TAB activate widget focus
+ // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus.
+ if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
+ g.FocusedWindow->FocusIdxTabRequestNext = 0;
+
+ // Mark all windows as not visible
+ for (int i = 0; i != g.Windows.Size; i++)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ window->WasActive = window->Active;
+ window->Active = false;
+ window->Accessed = false;
+ }
+
+ // 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);
+ CloseInactivePopups();
+
+ // Create implicit window - we will only render it if the user has added something to it.
+ ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver);
+ ImGui::Begin("Debug");
+}
+
+// NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations.
+void ImGui::Shutdown()
+{
+ ImGuiContext& g = *GImGui;
+
+ // 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)
+ if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
+ g.IO.Fonts->Clear();
+
+ // Cleanup of other data are conditional on actually having used ImGui.
+ if (!g.Initialized)
+ return;
+
+ SaveSettings();
+
+ for (int i = 0; i < g.Windows.Size; i++)
+ {
+ g.Windows[i]->~ImGuiWindow();
+ ImGui::MemFree(g.Windows[i]);
+ }
+ g.Windows.clear();
+ g.WindowsSortBuffer.clear();
+ g.CurrentWindowStack.clear();
+ g.FocusedWindow = NULL;
+ g.HoveredWindow = NULL;
+ g.HoveredRootWindow = NULL;
+ for (int i = 0; i < g.Settings.Size; i++)
+ ImGui::MemFree(g.Settings[i].Name);
+ g.Settings.clear();
+ g.ColorModifiers.clear();
+ g.StyleModifiers.clear();
+ g.FontStack.clear();
+ g.OpenPopupStack.clear();
+ g.CurrentPopupStack.clear();
+ for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
+ g.RenderDrawLists[i].clear();
+ g.OverlayDrawList.ClearFreeMemory();
+ g.ColorEditModeStorage.Clear();
+ if (g.PrivateClipboard)
+ {
+ ImGui::MemFree(g.PrivateClipboard);
+ g.PrivateClipboard = NULL;
+ }
+ g.InputTextState.Text.clear();
+ g.InputTextState.InitialText.clear();
+ g.InputTextState.TempTextBuffer.clear();
+
+ if (g.LogFile && g.LogFile != stdout)
+ {
+ fclose(g.LogFile);
+ g.LogFile = NULL;
+ }
+ if (g.LogClipboard)
+ {
+ g.LogClipboard->~ImGuiTextBuffer();
+ ImGui::MemFree(g.LogClipboard);
+ }
+
+ g.Initialized = false;
+}
+
+static ImGuiIniData* FindWindowSettings(const char* name)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiID id = ImHash(name, 0);
+ for (int i = 0; i != g.Settings.Size; i++)
+ {
+ ImGuiIniData* ini = &g.Settings[i];
+ if (ini->ID == id)
+ return ini;
+ }
+ return NULL;
+}
+
+static ImGuiIniData* AddWindowSettings(const char* name)
+{
+ GImGui->Settings.resize(GImGui->Settings.Size + 1);
+ ImGuiIniData* ini = &GImGui->Settings.back();
+ ini->Name = ImStrdup(name);
+ ini->ID = ImHash(name, 0);
+ ini->Collapsed = false;
+ ini->Pos = ImVec2(FLT_MAX,FLT_MAX);
+ ini->Size = ImVec2(0,0);
+ return ini;
+}
+
+// Zero-tolerance, poor-man .ini parsing
+// FIXME: Write something less rubbish
+static void LoadSettings()
+{
+ ImGuiContext& g = *GImGui;
+ const char* filename = g.IO.IniFilename;
+ if (!filename)
+ return;
+
+ int file_size;
+ char* file_data = (char*)ImLoadFileToMemory(filename, "rb", &file_size, 1);
+ if (!file_data)
+ return;
+
+ ImGuiIniData* settings = NULL;
+ const char* buf_end = file_data + file_size;
+ for (const char* line_start = file_data; line_start < buf_end; )
+ {
+ const char* line_end = line_start;
+ while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
+ line_end++;
+
+ if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
+ {
+ char name[64];
+ ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1);
+ settings = FindWindowSettings(name);
+ if (!settings)
+ settings = AddWindowSettings(name);
+ }
+ else if (settings)
+ {
+ float x, y;
+ int i;
+ if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2)
+ settings->Pos = ImVec2(x, y);
+ else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2)
+ settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
+ else if (sscanf(line_start, "Collapsed=%d", &i) == 1)
+ settings->Collapsed = (i != 0);
+ }
+
+ line_start = line_end+1;
+ }
+
+ ImGui::MemFree(file_data);
+}
+
+static void SaveSettings()
+{
+ ImGuiContext& g = *GImGui;
+ const char* filename = g.IO.IniFilename;
+ if (!filename)
+ return;
+
+ // Gather data from windows that were active during this session
+ for (int i = 0; i != g.Windows.Size; i++)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
+ continue;
+ ImGuiIniData* settings = FindWindowSettings(window->Name);
+ settings->Pos = window->Pos;
+ settings->Size = window->SizeFull;
+ settings->Collapsed = window->Collapsed;
+ }
+
+ // Write .ini file
+ // If a window wasn't opened in this session we preserve its settings
+ FILE* f = fopen(filename, "wt");
+ if (!f)
+ return;
+ for (int i = 0; i != g.Settings.Size; i++)
+ {
+ const ImGuiIniData* settings = &g.Settings[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;
+ fprintf(f, "[%s]\n", name);
+ fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
+ fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
+ fprintf(f, "Collapsed=%d\n", settings->Collapsed);
+ fprintf(f, "\n");
+ }
+
+ fclose(f);
+}
+
+static void MarkSettingsDirty()
+{
+ ImGuiContext& g = *GImGui;
+ if (g.SettingsDirtyTimer <= 0.0f)
+ g.SettingsDirtyTimer = g.IO.IniSavingRate;
+}
+
+// FIXME: Add a more explicit sort order in the window structure.
+static int ChildWindowComparer(const void* lhs, const void* rhs)
+{
+ const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
+ const ImGuiWindow* b = *(const ImGuiWindow**)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;
+ if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox))
+ return d;
+ return (a->IndexWithinParent - b->IndexWithinParent);
+}
+
+static void AddWindowToSortedBuffer(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)
+ qsort(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)
+ AddWindowToSortedBuffer(out_sorted_windows, child);
+ }
+ }
+}
+
+static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_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.
+ IM_ASSERT(draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
+ IM_ASSERT(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 = 2 bytes = 64K vertices)
+ // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly.
+ IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above.
+
+ out_render_list.push_back(draw_list);
+ GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
+ GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
+}
+
+static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window)
+{
+ AddDrawListToRenderList(out_render_list, window->DrawList);
+ for (int i = 0; i < window->DC.ChildWindows.Size; i++)
+ {
+ ImGuiWindow* child = window->DC.ChildWindows[i];
+ if (!child->Active) // clipped children may have been marked not active
+ continue;
+ if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
+ continue;
+ AddWindowToRenderList(out_render_list, child);
+ }
+}
+
+// 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); // Forgot to call ImGui::NewFrame()
+ IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again
+
+ // Render tooltip
+ if (g.Tooltip[0])
+ {
+ ImGui::BeginTooltip();
+ ImGui::TextUnformatted(g.Tooltip);
+ ImGui::EndTooltip();
+ }
+
+ // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
+ if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
+ {
+ g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
+ g.OsImePosSet = g.OsImePosRequest;
+ }
+
+ // Hide implicit "Debug" window if it hasn't been used
+ IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
+ if (g.CurrentWindow && !g.CurrentWindow->Accessed)
+ g.CurrentWindow->Active = false;
+ ImGui::End();
+
+ // Click to focus window and start moving (after we're done with all our widgets)
+ if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0])
+ {
+ if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear
+ {
+ if (g.HoveredRootWindow != NULL)
+ {
+ FocusWindow(g.HoveredWindow);
+ if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove))
+ {
+ g.MovedWindow = g.HoveredWindow;
+ g.MovedWindowMoveId = g.HoveredRootWindow->MoveID;
+ SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow);
+ }
+ }
+ else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL)
+ {
+ // Clicking on void disable focus
+ FocusWindow(NULL);
+ }
+ }
+ }
+
+ // 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;
+ AddWindowToSortedBuffer(g.WindowsSortBuffer, window);
+ }
+ IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
+ g.Windows.swap(g.WindowsSortBuffer);
+
+ // Clear Input data for next frame
+ g.IO.MouseWheel = 0.0f;
+ memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
+
+ g.FrameCountEnded = g.FrameCount;
+}
+
+void ImGui::Render()
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
+
+ if (g.FrameCountEnded != g.FrameCount)
+ ImGui::EndFrame();
+ g.FrameCountRendered = g.FrameCount;
+
+ // Skip render altogether if alpha is 0.0
+ // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false.
+ if (g.Style.Alpha > 0.0f)
+ {
+ // Gather windows to render
+ g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
+ for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
+ g.RenderDrawLists[i].resize(0);
+ for (int i = 0; i != g.Windows.Size; i++)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
+ {
+ // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
+ g.IO.MetricsActiveWindows++;
+ if (window->Flags & ImGuiWindowFlags_Popup)
+ AddWindowToRenderList(g.RenderDrawLists[1], window);
+ else if (window->Flags & ImGuiWindowFlags_Tooltip)
+ AddWindowToRenderList(g.RenderDrawLists[2], window);
+ else
+ AddWindowToRenderList(g.RenderDrawLists[0], window);
+ }
+ }
+
+ // Flatten layers
+ int n = g.RenderDrawLists[0].Size;
+ int flattened_size = n;
+ for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
+ flattened_size += g.RenderDrawLists[i].Size;
+ g.RenderDrawLists[0].resize(flattened_size);
+ for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
+ {
+ ImVector<ImDrawList*>& layer = g.RenderDrawLists[i];
+ if (layer.empty())
+ continue;
+ memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
+ n += layer.Size;
+ }
+
+ // Draw software mouse cursor if requested
+ if (g.IO.MouseDrawCursor)
+ {
+ const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
+ const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
+ const ImVec2 size = cursor_data.Size;
+ const ImTextureID tex_id = g.IO.Fonts->TexID;
+ g.OverlayDrawList.PushTextureID(tex_id);
+ g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow
+ g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow
+ g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border
+ g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill
+ g.OverlayDrawList.PopTextureID();
+ }
+ if (!g.OverlayDrawList.VtxBuffer.empty())
+ AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
+
+ // Setup draw data
+ g.RenderDrawData.Valid = true;
+ g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
+ g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
+ g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
+ g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
+
+ // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
+ if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
+ g.IO.RenderDrawListsFn(&g.RenderDrawData);
+ }
+}
+
+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;
+}
+
+// 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->appendv(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
+static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = ImGui::GetCurrentWindowRead();
+
+ if (!text_end)
+ text_end = ImGui::FindRenderedTextEnd(text, text_end);
+
+ const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1;
+ 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_end = text_remaining;
+ while (line_end < text_end)
+ if (*line_end == '\n')
+ break;
+ else
+ line_end++;
+ if (line_end >= text_end)
+ line_end = NULL;
+
+ const bool is_first_line = (text == text_remaining);
+ bool is_last_line = false;
+ if (line_end == NULL)
+ {
+ is_last_line = true;
+ line_end = text_end;
+ }
+ if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
+ {
+ const int char_count = (int)(line_end - text_remaining);
+ if (log_new_line || !is_first_line)
+ ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
+ else
+ ImGui::LogText(" %.*s", char_count, text_remaining);
+ }
+
+ if (is_last_line)
+ break;
+ text_remaining = line_end + 1;
+ }
+}
+
+// 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 = GetCurrentWindow();
+
+ // 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;
+ }
+
+ const int text_len = (int)(text_display_end - text);
+ if (text_len > 0)
+ {
+ 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 = GetCurrentWindow();
+
+ if (!text_end)
+ text_end = text + strlen(text); // FIXME-OPT
+
+ const int text_len = (int)(text_end - text);
+ if (text_len > 0)
+ {
+ window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
+ if (g.LogEnabled)
+ LogRenderedText(pos, text, text_end);
+ }
+}
+
+// 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, ImGuiAlign align, const ImVec2* clip_min, const ImVec2* clip_max)
+{
+ // 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 = GetCurrentWindow();
+
+ // 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);
+
+ if (!clip_max) clip_max = &pos_max;
+ bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
+ if (!clip_min) clip_min = &pos_min; else need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
+
+ // Align
+ if (align & ImGuiAlign_Center) pos.x = ImMax(pos.x, (pos.x + pos_max.x - text_size.x) * 0.5f);
+ else if (align & ImGuiAlign_Right) pos.x = ImMax(pos.x, pos_max.x - text_size.x);
+ if (align & ImGuiAlign_VCenter) pos.y = ImMax(pos.y, (pos.y + pos_max.y - text_size.y) * 0.5f);
+
+ // 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)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+
+ window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
+ if (border && (window->Flags & ImGuiWindowFlags_ShowBorders))
+ {
+ window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding);
+ window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
+ }
+}
+
+// Render a triangle to denote expanded/collapsed state
+void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale, bool shadow)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+
+ const float h = g.FontSize * 1.00f;
+ const float r = h * 0.40f * scale;
+ ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale);
+
+ ImVec2 a, b, c;
+ if (is_open)
+ {
+ center.y -= r*0.25f;
+ a = center + ImVec2(0,1)*r;
+ b = center + ImVec2(-0.866f,-0.5f)*r;
+ c = center + ImVec2(0.866f,-0.5f)*r;
+ }
+ else
+ {
+ a = center + ImVec2(1,0)*r;
+ b = center + ImVec2(-0.500f,0.866f)*r;
+ c = center + ImVec2(-0.500f,-0.866f)*r;
+ }
+
+ if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0)
+ window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), GetColorU32(ImGuiCol_BorderShadow));
+ window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text));
+}
+
+void ImGui::RenderBullet(ImVec2 pos)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
+}
+
+void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+
+ ImVec2 a, b, c;
+ float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f);
+ float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f);
+ a.x = pos.x + 0.5f + start_x;
+ b.x = a.x + rem_third;
+ c.x = a.x + rem_third * 3.0f;
+ b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y);
+ a.y = b.y - rem_third;
+ c.y = b.y - rem_third * 2.0f;
+
+ window->DrawList->PathLineTo(a);
+ window->DrawList->PathLineTo(b);
+ window->DrawList->PathLineTo(c);
+ window->DrawList->PathStroke(col, false);
+}
+
+// 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->XAdvance 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 = GetCurrentWindowRead();
+ 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;
+ }
+
+ const ImVec2 pos = window->DC.CursorPos;
+ int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
+ int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
+ 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 a lag here because WindowRectClipped is updated in Begin() so windows moved by user via 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 thankfully isn't affected.
+static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
+{
+ ImGuiContext& g = *GImGui;
+ for (int i = g.Windows.Size-1; i >= 0; i--)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ if (!window->Active)
+ continue;
+ if (window->Flags & ImGuiWindowFlags_NoInputs)
+ continue;
+ if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0)
+ continue;
+
+ // Using the clipped AABB so a child window will typically be clipped by its parent.
+ ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
+ if (bb.Contains(pos))
+ return window;
+ }
+ return 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;
+ ImGuiWindow* window = GetCurrentWindowRead();
+
+ // Clip
+ ImRect rect_clipped(r_min, r_max);
+ if (clip)
+ rect_clipped.Clip(window->ClipRect);
+
+ // Expand for touch input
+ const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
+ return rect_for_touch.Contains(g.IO.MousePos);
+}
+
+bool ImGui::IsMouseHoveringWindow()
+{
+ ImGuiContext& g = *GImGui;
+ return g.HoveredWindow == g.CurrentWindow;
+}
+
+bool ImGui::IsMouseHoveringAnyWindow()
+{
+ ImGuiContext& g = *GImGui;
+ return g.HoveredWindow != NULL;
+}
+
+bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos)
+{
+ return FindHoveredWindow(pos, false) != NULL;
+}
+
+static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
+{
+ const int key_index = GImGui->IO.KeyMap[key];
+ return ImGui::IsKeyPressed(key_index, repeat);
+}
+
+int ImGui::GetKeyIndex(ImGuiKey key)
+{
+ IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT);
+ return GImGui->IO.KeyMap[key];
+}
+
+bool ImGui::IsKeyDown(int key_index)
+{
+ if (key_index < 0) return false;
+ IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
+ return GImGui->IO.KeysDown[key_index];
+}
+
+bool ImGui::IsKeyPressed(int key_index, bool repeat)
+{
+ 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];
+ if (t == 0.0f)
+ return true;
+
+ if (repeat && t > g.IO.KeyRepeatDelay)
+ {
+ float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
+ if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
+ return true;
+ }
+ return false;
+}
+
+bool ImGui::IsKeyReleased(int key_index)
+{
+ ImGuiContext& g = *GImGui;
+ if (key_index < 0) return false;
+ IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
+ if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index])
+ return true;
+ return false;
+}
+
+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::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 ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(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].MousePosOnOpen;
+ return g.IO.MousePos;
+}
+
+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->CaptureKeyboardNextFrame = capture ? 1 : 0;
+}
+
+void ImGui::CaptureMouseFromApp(bool capture)
+{
+ GImGui->CaptureMouseNextFrame = capture ? 1 : 0;
+}
+
+bool ImGui::IsItemHovered()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->DC.LastItemHoveredAndUsable;
+}
+
+bool ImGui::IsItemHoveredRect()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->DC.LastItemHoveredRect;
+}
+
+bool ImGui::IsItemActive()
+{
+ ImGuiContext& g = *GImGui;
+ if (g.ActiveId)
+ {
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return g.ActiveId == window->DC.LastItemID;
+ }
+ return false;
+}
+
+bool ImGui::IsItemClicked(int mouse_button)
+{
+ return IsMouseClicked(mouse_button) && IsItemHovered();
+}
+
+bool ImGui::IsAnyItemHovered()
+{
+ return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0;
+}
+
+bool ImGui::IsAnyItemActive()
+{
+ return GImGui->ActiveId != 0;
+}
+
+bool ImGui::IsItemVisible()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImRect r(window->ClipRect);
+ return r.Overlaps(window->DC.LastItemRect);
+}
+
+// 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();
+}
+
+ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImRect rect = window->DC.LastItemRect;
+ rect.Expand(outward);
+ return rect.GetClosestPoint(pos, on_edge);
+}
+
+// Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value.
+void ImGui::SetTooltipV(const char* fmt, va_list args)
+{
+ ImGuiContext& g = *GImGui;
+ ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args);
+}
+
+void ImGui::SetTooltip(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ SetTooltipV(fmt, args);
+ va_end(args);
+}
+
+static ImRect GetVisibleRect()
+{
+ 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);
+}
+
+void ImGui::BeginTooltip()
+{
+ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
+ ImGui::Begin("##Tooltip", NULL, flags);
+}
+
+void ImGui::EndTooltip()
+{
+ IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
+ ImGui::End();
+}
+
+static bool IsPopupOpen(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ const bool is_open = g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupID == id;
+ return is_open;
+}
+
+// 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(const char* str_id, bool reopen_existing)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiID id = window->GetID(str_id);
+ int current_stack_size = g.CurrentPopupStack.Size;
+ ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here)
+ if (g.OpenPopupStack.Size < current_stack_size + 1)
+ g.OpenPopupStack.push_back(popup_ref);
+ else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupID != id)
+ {
+ g.OpenPopupStack.resize(current_stack_size+1);
+ g.OpenPopupStack[current_stack_size] = popup_ref;
+ }
+}
+
+void ImGui::OpenPopup(const char* str_id)
+{
+ ImGui::OpenPopupEx(str_id, false);
+}
+
+static void CloseInactivePopups()
+{
+ 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 (g.FocusedWindow)
+ {
+ 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;
+
+ 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 == g.FocusedWindow->RootWindow);
+ if (!has_focus)
+ break;
+ }
+ }
+ if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below
+ g.OpenPopupStack.resize(n);
+}
+
+static ImGuiWindow* GetFrontMostModalRootWindow()
+{
+ ImGuiContext& g = *GImGui;
+ for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
+ if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window)
+ if (front_most_popup->Flags & ImGuiWindowFlags_Modal)
+ return front_most_popup;
+ return NULL;
+}
+
+static void ClosePopupToLevel(int remaining)
+{
+ ImGuiContext& g = *GImGui;
+ if (remaining > 0)
+ ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window);
+ else
+ ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow);
+ g.OpenPopupStack.resize(remaining);
+}
+
+static void 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);
+}
+
+static inline void ClearSetNextWindowData()
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
+ g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false;
+}
+
+static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ const ImGuiID id = window->GetID(str_id);
+ if (!IsPopupOpen(id))
+ {
+ ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ return false;
+ }
+
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
+ ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
+
+ char name[32];
+ if (flags & ImGuiWindowFlags_ChildMenu)
+ ImFormatString(name, 20, "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth
+ else
+ ImFormatString(name, 20, "##popup_%08x", id); // Not recycling, so we can close/open during the same frame
+
+ bool is_open = ImGui::Begin(name, NULL, flags);
+ if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
+ g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders;
+ if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
+ ImGui::EndPopup();
+
+ return is_open;
+}
+
+bool ImGui::BeginPopup(const char* str_id)
+{
+ if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance
+ {
+ ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ return false;
+ }
+ return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders);
+}
+
+bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ const ImGuiID id = window->GetID(name);
+ if (!IsPopupOpen(id))
+ {
+ ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ return false;
+ }
+
+ ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings;
+ bool is_open = ImGui::Begin(name, p_open, flags);
+ if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
+ {
+ ImGui::EndPopup();
+ if (is_open)
+ ClosePopup(id);
+ return false;
+ }
+
+ return is_open;
+}
+
+void ImGui::EndPopup()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
+ IM_ASSERT(GImGui->CurrentPopupStack.Size > 0);
+ ImGui::End();
+ if (!(window->Flags & ImGuiWindowFlags_Modal))
+ ImGui::PopStyleVar();
+}
+
+// This is a helper to handle the most simple case of associating one named popup to one given widget.
+// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling
+// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers.
+// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect()
+// and passing true to the OpenPopupEx().
+// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that
+// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu
+// driven by click position.
+bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
+{
+ if (IsItemHovered() && IsMouseClicked(mouse_button))
+ OpenPopupEx(str_id, false);
+ return BeginPopup(str_id);
+}
+
+bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button)
+{
+ if (!str_id) str_id = "window_context_menu";
+ if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button))
+ if (also_over_items || !IsAnyItemHovered())
+ OpenPopupEx(str_id, true);
+ return BeginPopup(str_id);
+}
+
+bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
+{
+ if (!str_id) str_id = "void_context_menu";
+ if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button))
+ OpenPopupEx(str_id, true);
+ return BeginPopup(str_id);
+}
+
+bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
+
+ const ImVec2 content_avail = GetContentRegionAvail();
+ ImVec2 size = ImFloor(size_arg);
+ if (size.x <= 0.0f)
+ {
+ if (size.x == 0.0f)
+ flags |= ImGuiWindowFlags_ChildWindowAutoFitX;
+ size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues)
+ }
+ if (size.y <= 0.0f)
+ {
+ if (size.y == 0.0f)
+ flags |= ImGuiWindowFlags_ChildWindowAutoFitY;
+ size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y);
+ }
+ if (border)
+ flags |= ImGuiWindowFlags_ShowBorders;
+ flags |= extra_flags;
+
+ char title[256];
+ ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id);
+
+ bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags);
+
+ if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
+ GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders;
+
+ return ret;
+}
+
+bool ImGui::BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags)
+{
+ char str_id[32];
+ ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%08x", id);
+ bool ret = ImGui::BeginChild(str_id, size, border, extra_flags);
+ return ret;
+}
+
+void ImGui::EndChild()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
+ if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1)
+ {
+ ImGui::End();
+ }
+ else
+ {
+ // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
+ ImVec2 sz = GetWindowSize();
+ if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // 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->Flags & ImGuiWindowFlags_ChildWindowAutoFitY)
+ sz.y = ImMax(4.0f, sz.y);
+
+ ImGui::End();
+
+ window = GetCurrentWindow();
+ ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz);
+ ItemSize(sz);
+ ItemAdd(bb, NULL);
+ }
+}
+
+// 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;
+ ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]);
+ ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
+ return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
+}
+
+void ImGui::EndChildFrame()
+{
+ ImGui::EndChild();
+ ImGui::PopStyleVar(2);
+ ImGui::PopStyleColor();
+}
+
+// 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 Mismatch!"); p_backup++; } // User forgot PopID()
+ { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // User forgot 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++; }// User forgot EndPopup()/EndMenu()
+ { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // User forgot PopStyleColor()
+ { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // User forgot PopStyleVar()
+ { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // User forgot PopFont()
+ IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
+}
+
+static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner)
+{
+ const ImGuiStyle& style = GImGui->Style;
+
+ // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it.
+ ImVec2 safe_padding = style.DisplaySafeAreaPadding;
+ ImRect r_outer(GetVisibleRect());
+ r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f));
+ ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size);
+
+ for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction).
+ {
+ const int dir = (n == -1) ? *last_dir : n;
+ ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y);
+ if (rect.GetWidth() < size.x || rect.GetHeight() < size.y)
+ continue;
+ *last_dir = dir;
+ return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y);
+ }
+
+ // Fallback, try to keep within display
+ *last_dir = -1;
+ ImVec2 pos = base_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;
+}
+
+ImGuiWindow* ImGui::FindWindowByName(const char* name)
+{
+ // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block
+ ImGuiContext& g = *GImGui;
+ ImGuiID id = ImHash(name, 0);
+ for (int i = 0; i < g.Windows.Size; i++)
+ if (g.Windows[i]->ID == id)
+ return g.Windows[i];
+ return NULL;
+}
+
+static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+
+ // Create window the first time
+ ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow));
+ IM_PLACEMENT_NEW(window) ImGuiWindow(name);
+ window->Flags = flags;
+
+ if (flags & ImGuiWindowFlags_NoSavedSettings)
+ {
+ // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
+ window->Size = window->SizeFull = size;
+ }
+ else
+ {
+ // Retrieve settings from .ini file
+ // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
+ window->PosFloat = ImVec2(60, 60);
+ window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+
+ ImGuiIniData* settings = FindWindowSettings(name);
+ if (!settings)
+ {
+ settings = AddWindowSettings(name);
+ }
+ else
+ {
+ window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver;
+ window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver;
+ window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver;
+ }
+
+ if (settings->Pos.x != FLT_MAX)
+ {
+ window->PosFloat = settings->Pos;
+ window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Collapsed = settings->Collapsed;
+ }
+
+ if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize))
+ size = settings->Size;
+ window->Size = window->SizeFull = size;
+ }
+
+ 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);
+ }
+
+ if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
+ g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
+ else
+ g.Windows.push_back(window);
+ return window;
+}
+
+static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.SetNextWindowSizeConstraint)
+ {
+ // Using -1,-1 on either X/Y axis to preserve the current size.
+ ImRect cr = g.SetNextWindowSizeConstraintRect;
+ 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.SetNextWindowSizeConstraintCallback)
+ {
+ ImGuiSizeConstraintCallbackData data;
+ data.UserData = g.SetNextWindowSizeConstraintCallbackUserData;
+ data.Pos = window->Pos;
+ data.CurrentSize = window->SizeFull;
+ data.DesiredSize = new_size;
+ g.SetNextWindowSizeConstraintCallback(&data);
+ new_size = data.DesiredSize;
+ }
+ }
+ if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
+ new_size = ImMax(new_size, g.Style.WindowMinSize);
+ window->SizeFull = new_size;
+}
+
+// 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.
+// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation.
+// - 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.
+// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin().
+bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
+{
+ return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags);
+}
+
+bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ const ImGuiStyle& style = g.Style;
+ IM_ASSERT(name != NULL); // Window name required
+ IM_ASSERT(g.Initialized); // 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
+
+ if (flags & ImGuiWindowFlags_NoInputs)
+ flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
+
+ // Find or create
+ bool window_is_new = false;
+ ImGuiWindow* window = FindWindowByName(name);
+ if (!window)
+ {
+ window = CreateNewWindow(name, size_on_first_use, flags);
+ window_is_new = true;
+ }
+
+ const int current_frame = ImGui::GetFrameCount();
+ 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;
+
+ // Add to stack
+ ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL;
+ g.CurrentWindowStack.push_back(window);
+ SetCurrentWindow(window);
+ CheckStacksSize(window, true);
+ IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
+
+ bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
+ if (flags & ImGuiWindowFlags_Popup)
+ {
+ ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
+ window_was_active &= (window->PopupID == popup_ref.PopupID);
+ window_was_active &= (window == popup_ref.Window);
+ popup_ref.Window = window;
+ g.CurrentPopupStack.push_back(popup_ref);
+ window->PopupID = popup_ref.PopupID;
+ }
+
+ const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1);
+
+ // Process SetNextWindow***() calls
+ bool window_pos_set_by_api = false, window_size_set_by_api = false;
+ if (g.SetNextWindowPosCond)
+ {
+ const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that.
+ if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing;
+ window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
+ if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f)
+ {
+ window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size
+ window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+ }
+ else
+ {
+ SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
+ }
+ window->DC.CursorPos = backup_cursor_pos;
+ g.SetNextWindowPosCond = 0;
+ }
+ if (g.SetNextWindowSizeCond)
+ {
+ if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing;
+ window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0;
+ SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
+ g.SetNextWindowSizeCond = 0;
+ }
+ if (g.SetNextWindowContentSizeCond)
+ {
+ window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
+ g.SetNextWindowContentSizeCond = 0;
+ }
+ else if (first_begin_of_the_frame)
+ {
+ window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
+ }
+ if (g.SetNextWindowCollapsedCond)
+ {
+ if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing;
+ SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
+ g.SetNextWindowCollapsedCond = 0;
+ }
+ if (g.SetNextWindowFocus)
+ {
+ ImGui::SetWindowFocus();
+ g.SetNextWindowFocus = false;
+ }
+
+ // Update known root window (if we are a child window, otherwise window == window->RootWindow)
+ int root_idx, root_non_popup_idx;
+ for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--)
+ if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow))
+ break;
+ for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--)
+ if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
+ break;
+ window->ParentWindow = parent_window;
+ window->RootWindow = g.CurrentWindowStack[root_idx];
+ window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color.
+
+ // When reusing window again multiple times a frame, just append content (don't need to setup again)
+ if (first_begin_of_the_frame)
+ {
+ window->Active = true;
+ window->IndexWithinParent = 0;
+ window->BeginCount = 0;
+ window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
+ window->LastFrameActive = current_frame;
+ window->IDStack.resize(1);
+
+ // Clear draw list, setup texture, outer clipping rectangle
+ window->DrawList->Clear();
+ window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
+ ImRect fullscreen_rect(GetVisibleRect());
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup)))
+ PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
+ else
+ PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
+
+ // New windows appears in front
+ if (!window_was_active)
+ {
+ window->AutoPosLastDirection = -1;
+
+ if (!(flags & ImGuiWindowFlags_NoFocusOnAppearing))
+ if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
+ FocusWindow(window);
+
+ // Popup first latch mouse position, will position itself when it appears next frame
+ if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
+ window->PosFloat = g.IO.MousePos;
+ }
+
+ // 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))
+ {
+ ImRect title_bar_rect = window->TitleBarRect();
+ if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
+ {
+ window->Collapsed = !window->Collapsed;
+ if (!(flags & ImGuiWindowFlags_NoSavedSettings))
+ MarkSettingsDirty();
+ FocusWindow(window);
+ }
+ }
+ else
+ {
+ window->Collapsed = false;
+ }
+
+ // SIZE
+
+ // Save contents size from last frame for auto-fitting (unless explicitly specified)
+ window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x));
+ window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y));
+
+ // Hide popup/tooltip window when first appearing while we measure size (because we recycle them)
+ if (window->HiddenFrames > 0)
+ window->HiddenFrames--;
+ if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active)
+ {
+ window->HiddenFrames = 1;
+ if (flags & ImGuiWindowFlags_AlwaysAutoResize)
+ {
+ if (!window_size_set_by_api)
+ window->Size = window->SizeFull = ImVec2(0.f, 0.f);
+ window->SizeContents = ImVec2(0.f, 0.f);
+ }
+ }
+
+ // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects.
+ window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding;
+
+ // Calculate auto-fit size
+ ImVec2 size_auto_fit;
+ if ((flags & ImGuiWindowFlags_Tooltip) != 0)
+ {
+ // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
+ size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y);
+ }
+ else
+ {
+ size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
+
+ // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
+ if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
+ size_auto_fit.y += style.ScrollbarSize;
+ if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
+ size_auto_fit.x += style.ScrollbarSize;
+ size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f);
+ }
+
+ // Handle automatic resize
+ if (window->Collapsed)
+ {
+ // We still process initial auto-fit on collapsed windows to get a window width,
+ // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
+ if (window->AutoFitFramesX > 0)
+ window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
+ if (window->AutoFitFramesY > 0)
+ window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
+ }
+ else
+ {
+ if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api)
+ {
+ window->SizeFull = size_auto_fit;
+ }
+ else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api)
+ {
+ // Auto-fit only grows during the first few frames
+ if (window->AutoFitFramesX > 0)
+ window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
+ if (window->AutoFitFramesY > 0)
+ window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
+ if (!(flags & ImGuiWindowFlags_NoSavedSettings))
+ MarkSettingsDirty();
+ }
+ }
+
+ // Apply minimum/maximum window size constraints and final size
+ ApplySizeFullWithConstraint(window, window->SizeFull);
+ window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull;
+
+ // POSITION
+
+ // Position child window
+ if (flags & ImGuiWindowFlags_ChildWindow)
+ {
+ window->IndexWithinParent = parent_window->DC.ChildWindows.Size;
+ parent_window->DC.ChildWindows.push_back(window);
+ }
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
+ {
+ window->Pos = window->PosFloat = parent_window->DC.CursorPos;
+ window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin().
+ }
+
+ bool window_pos_center = false;
+ window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0);
+ window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden);
+ if (window_pos_center)
+ {
+ // Center (any sort of window)
+ SetWindowPos(ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f));
+ }
+ else if (flags & ImGuiWindowFlags_ChildMenu)
+ {
+ IM_ASSERT(window_pos_set_by_api);
+ ImRect rect_to_avoid;
+ if (parent_window->DC.MenuBarAppending)
+ rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
+ else
+ rect_to_avoid = ImRect(parent_window->Pos.x + style.ItemSpacing.x, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - style.ItemSpacing.x - parent_window->ScrollbarSizes.x, FLT_MAX); // We want some overlap to convey the relative depth of each popup (here hard-coded to 4)
+ window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
+ }
+ else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden)
+ {
+ ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
+ window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
+ }
+
+ // Position tooltip (always follows mouse)
+ if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
+ {
+ ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead?
+ window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
+ if (window->AutoPosLastDirection == -1)
+ window->PosFloat = g.IO.MousePos + 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.
+ }
+
+ // Clamp position so it stays visible
+ if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
+ {
+ 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->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
+ window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
+ }
+ }
+ window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+
+ // 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);
+
+ // Prepare for 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
+ if (window->ScrollTarget.x < FLT_MAX)
+ {
+ window->Scroll.x = window->ScrollTarget.x;
+ window->ScrollTarget.x = FLT_MAX;
+ }
+ if (window->ScrollTarget.y < FLT_MAX)
+ {
+ float center_ratio = window->ScrollTargetCenterRatio.y;
+ window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * window->TitleBarHeight()) - (center_ratio * window->SizeFull.y);
+ window->ScrollTarget.y = FLT_MAX;
+ }
+ window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f));
+ if (!window->Collapsed && !window->SkipItems)
+ window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes));
+
+ // Modal window darkens what is behind them
+ if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
+ window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
+
+ // Draw window + handle manual resize
+ ImRect title_bar_rect = window->TitleBarRect();
+ const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
+ if (window->Collapsed)
+ {
+ // Draw title bar only
+ RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
+ }
+ else
+ {
+ ImU32 resize_col = 0;
+ const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
+ if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
+ {
+ // Manual resize
+ const ImVec2 br = window->Rect().GetBR();
+ const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br);
+ const ImGuiID resize_id = window->GetID("#RESIZE");
+ bool hovered, held;
+ ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds);
+ resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
+
+ if (hovered || held)
+ g.MouseCursor = ImGuiMouseCursor_ResizeNWSE;
+
+ if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0])
+ {
+ // Manual auto-fit when double-clicking
+ ApplySizeFullWithConstraint(window, size_auto_fit);
+ if (!(flags & ImGuiWindowFlags_NoSavedSettings))
+ MarkSettingsDirty();
+ SetActiveID(0);
+ }
+ else if (held)
+ {
+ // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
+ ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos);
+ if (!(flags & ImGuiWindowFlags_NoSavedSettings))
+ MarkSettingsDirty();
+ }
+
+ window->Size = window->SizeFull;
+ title_bar_rect = window->TitleBarRect();
+ }
+
+ // Scrollbars
+ window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar));
+ window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
+ window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
+ window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f;
+
+ // Window background
+ // Default alpha
+ ImGuiCol bg_color_idx = ImGuiCol_WindowBg;
+ if ((flags & ImGuiWindowFlags_ComboBox) != 0)
+ bg_color_idx = ImGuiCol_ComboBg;
+ else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0)
+ bg_color_idx = ImGuiCol_PopupBg;
+ else if ((flags & ImGuiWindowFlags_ChildWindow) != 0)
+ bg_color_idx = ImGuiCol_ChildWindowBg;
+ ImVec4 bg_color = style.Colors[bg_color_idx];
+ if (bg_alpha >= 0.0f)
+ bg_color.w = bg_alpha;
+ bg_color.w *= style.Alpha;
+ if (bg_color.w > 0.0f)
+ window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 15 : 4|8);
+
+ // Title bar
+ if (!(flags & ImGuiWindowFlags_NoTitleBar))
+ window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, 1|2);
+
+ // Menu bar
+ if (flags & ImGuiWindowFlags_MenuBar)
+ {
+ ImRect menu_bar_rect = window->MenuBarRect();
+ window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, 1|2);
+ if (flags & ImGuiWindowFlags_ShowBorders)
+ window->DrawList->AddLine(menu_bar_rect.GetBL()-ImVec2(0,0), menu_bar_rect.GetBR()-ImVec2(0,0), GetColorU32(ImGuiCol_Border));
+ }
+
+ // Scrollbars
+ if (window->ScrollbarX)
+ Scrollbar(window, true);
+ if (window->ScrollbarY)
+ Scrollbar(window, false);
+
+ // Render resize grip
+ // (after the input handling so we don't have a frame of latency)
+ if (!(flags & ImGuiWindowFlags_NoResize))
+ {
+ const ImVec2 br = window->Rect().GetBR();
+ window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize));
+ window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size));
+ window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3);
+ window->DrawList->PathFill(resize_col);
+ }
+
+ // Borders
+ if (flags & ImGuiWindowFlags_ShowBorders)
+ {
+ window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding);
+ window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding);
+ if (!(flags & ImGuiWindowFlags_NoTitleBar))
+ window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border));
+ }
+ }
+
+ // Update ContentsRegionMax. All the variable it depends on are set above in this function.
+ window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
+ window->ContentsRegionRect.Min.x = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
+ window->ContentsRegionRect.Max.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->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
+
+ // Setup drawing context
+ window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
+ window->DC.ColumnsOffsetX = 0.0f;
+ window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, 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.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
+ window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
+ window->DC.MenuBarAppending = false;
+ window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
+ window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
+ window->DC.ChildWindows.resize(0);
+ window->DC.LayoutType = ImGuiLayoutType_Vertical;
+ window->DC.ItemWidth = window->ItemWidthDefault;
+ window->DC.TextWrapPos = -1.0f; // disabled
+ window->DC.AllowKeyboardFocus = true;
+ window->DC.ButtonRepeat = false;
+ window->DC.ItemWidthStack.resize(0);
+ window->DC.TextWrapPosStack.resize(0);
+ window->DC.AllowKeyboardFocusStack.resize(0);
+ window->DC.ButtonRepeatStack.resize(0);
+ window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect;
+ window->DC.ColumnsCurrent = 0;
+ window->DC.ColumnsCount = 1;
+ window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
+ window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY;
+ window->DC.TreeDepth = 0;
+ window->DC.StateStorage = &window->StateStorage;
+ window->DC.GroupStack.resize(0);
+ window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active);
+
+ if (window->AutoFitFramesX > 0)
+ window->AutoFitFramesX--;
+ if (window->AutoFitFramesY > 0)
+ window->AutoFitFramesY--;
+
+ // Title bar
+ if (!(flags & ImGuiWindowFlags_NoTitleBar))
+ {
+ if (p_open != NULL)
+ {
+ const float pad = 2.0f;
+ const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f;
+ if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad))
+ *p_open = false;
+ }
+
+ const ImVec2 text_size = CalcTextSize(name, NULL, true);
+ if (!(flags & ImGuiWindowFlags_NoCollapse))
+ RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true);
+
+ ImVec2 text_min = window->Pos + style.FramePadding;
+ ImVec2 text_max = window->Pos + ImVec2(window->Size.x - style.FramePadding.x, style.FramePadding.y*2 + text_size.y);
+ ImVec2 clip_max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton()
+ bool pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0;
+ bool pad_right = (p_open != NULL);
+ if (style.WindowTitleAlign & ImGuiAlign_Center) pad_right = pad_left;
+ if (pad_left) text_min.x += g.FontSize + style.ItemInnerSpacing.x;
+ if (pad_right) text_max.x -= g.FontSize + style.ItemInnerSpacing.x;
+ RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, NULL, &clip_max);
+ }
+
+ // Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
+ window->WindowRectClipped = window->Rect();
+ window->WindowRectClipped.Clip(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))
+ ImGui::LogToClipboard();
+ */
+ }
+
+ // Inner clipping 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 a null clipping rectangle which is the correct behavior.
+ const ImRect title_bar_rect = window->TitleBarRect();
+ const float border_size = window->BorderSize;
+ ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
+ clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
+ clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size);
+ clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
+ clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size);
+ PushClipRect(clip_rect.Min, clip_rect.Max, true);
+
+ // Clear 'accessed' flag last thing
+ if (first_begin_of_the_frame)
+ window->Accessed = false;
+ window->BeginCount++;
+ g.SetNextWindowSizeConstraint = false;
+
+ // 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 because they have no title bar).
+ if (flags & ImGuiWindowFlags_ChildWindow)
+ {
+ IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
+ window->Collapsed = parent_window && parent_window->Collapsed;
+
+ if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
+ window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
+
+ // We also hide the window from rendering because we've already added its border to the command list.
+ // (we could perform the check earlier in the function but it is simpler at this point)
+ if (window->Collapsed)
+ window->Active = false;
+ }
+ if (style.Alpha <= 0.0f)
+ window->Active = false;
+
+ // 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->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
+ return !window->SkipItems;
+}
+
+void ImGui::End()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ Columns(1, "#CloseColumns");
+ PopClipRect(); // inner window clip rectangle
+
+ // Stop logging
+ if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
+ LogFinish();
+
+ // Pop
+ // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin().
+ g.CurrentWindowStack.pop_back();
+ if (window->Flags & ImGuiWindowFlags_Popup)
+ g.CurrentPopupStack.pop_back();
+ CheckStacksSize(window, false);
+ SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
+}
+
+// Vertical 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.
+static void Scrollbar(ImGuiWindow* window, bool horizontal)
+{
+ ImGuiContext& g = *GImGui;
+ 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->BorderSize;
+ 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);
+
+ float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
+ int window_rounding_corners;
+ if (horizontal)
+ window_rounding_corners = 8 | (other_scrollbar ? 0 : 4);
+ else
+ window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? 2 : 0) | (other_scrollbar ? 0 : 4);
+ window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners);
+ bb.Reduce(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 axis of the 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->Size.x : window->Size.y) - other_scrollbar_size_w;
+ float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
+
+ // The grabable box size 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.
+ const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_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);
+ ImGui::ButtonBehavior(bb, id, &hovered, &held);
+
+ 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);
+ ImGui::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 = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
+ if (horizontal)
+ window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding);
+ else
+ window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding);
+}
+
+// Moving window to front of display (which happens to be back of our sorted list)
+void ImGui::FocusWindow(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+
+ // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
+ g.FocusedWindow = window;
+
+ // Passing NULL allow to disable keyboard focus
+ if (!window)
+ return;
+
+ // And move its 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)
+ SetActiveID(0);
+
+ // Bring to front
+ if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window)
+ return;
+ for (int i = 0; i < g.Windows.Size; i++)
+ if (g.Windows[i] == window)
+ {
+ g.Windows.erase(g.Windows.begin() + i);
+ break;
+ }
+ g.Windows.push_back(window);
+}
+
+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);
+}
+
+static void PushMultiItemsWidths(int components, float w_full)
+{
+ ImGuiWindow* window = ImGui::GetCurrentWindow();
+ const ImGuiStyle& style = GImGui->Style;
+ if (w_full <= 0.0f)
+ w_full = ImGui::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;
+}
+
+static void 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;
+ g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel;
+}
+
+void ImGui::PushFont(ImFont* font)
+{
+ ImGuiContext& g = *GImGui;
+ if (!font)
+ font = g.IO.Fonts->Fonts[0];
+ 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() ? g.IO.Fonts->Fonts[0] : g.FontStack.back());
+}
+
+void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.AllowKeyboardFocus = allow_keyboard_focus;
+ window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus);
+}
+
+void ImGui::PopAllowKeyboardFocus()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.AllowKeyboardFocusStack.pop_back();
+ window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back();
+}
+
+void ImGui::PushButtonRepeat(bool repeat)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.ButtonRepeat = repeat;
+ window->DC.ButtonRepeatStack.push_back(repeat);
+}
+
+void ImGui::PopButtonRepeat()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.ButtonRepeatStack.pop_back();
+ window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back();
+}
+
+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();
+}
+
+void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiColMod backup;
+ backup.Col = idx;
+ backup.PreviousValue = 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)
+ {
+ ImGuiColMod& backup = g.ColorModifiers.back();
+ g.Style.Colors[backup.Col] = backup.PreviousValue;
+ g.ColorModifiers.pop_back();
+ count--;
+ }
+}
+
+static float* GetStyleVarFloatAddr(ImGuiStyleVar idx)
+{
+ ImGuiContext& g = *GImGui;
+ switch (idx)
+ {
+ case ImGuiStyleVar_Alpha: return &g.Style.Alpha;
+ case ImGuiStyleVar_WindowRounding: return &g.Style.WindowRounding;
+ case ImGuiStyleVar_ChildWindowRounding: return &g.Style.ChildWindowRounding;
+ case ImGuiStyleVar_FrameRounding: return &g.Style.FrameRounding;
+ case ImGuiStyleVar_IndentSpacing: return &g.Style.IndentSpacing;
+ case ImGuiStyleVar_GrabMinSize: return &g.Style.GrabMinSize;
+ }
+ return NULL;
+}
+
+static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx)
+{
+ ImGuiContext& g = *GImGui;
+ switch (idx)
+ {
+ case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding;
+ case ImGuiStyleVar_WindowMinSize: return &g.Style.WindowMinSize;
+ case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding;
+ case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing;
+ case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing;
+ }
+ return NULL;
+}
+
+void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
+{
+ ImGuiContext& g = *GImGui;
+ float* pvar = GetStyleVarFloatAddr(idx);
+ IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a float.
+ ImGuiStyleMod backup;
+ backup.Var = idx;
+ backup.PreviousValue = ImVec2(*pvar, 0.0f);
+ g.StyleModifiers.push_back(backup);
+ *pvar = val;
+}
+
+
+void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
+{
+ ImGuiContext& g = *GImGui;
+ ImVec2* pvar = GetStyleVarVec2Addr(idx);
+ IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a ImVec2.
+ ImGuiStyleMod backup;
+ backup.Var = idx;
+ backup.PreviousValue = *pvar;
+ g.StyleModifiers.push_back(backup);
+ *pvar = val;
+}
+
+void ImGui::PopStyleVar(int count)
+{
+ ImGuiContext& g = *GImGui;
+ while (count > 0)
+ {
+ ImGuiStyleMod& backup = g.StyleModifiers.back();
+ if (float* pvar_f = GetStyleVarFloatAddr(backup.Var))
+ *pvar_f = backup.PreviousValue.x;
+ else if (ImVec2* pvar_v = GetStyleVarVec2Addr(backup.Var))
+ *pvar_v = backup.PreviousValue;
+ g.StyleModifiers.pop_back();
+ count--;
+ }
+}
+
+const char* ImGui::GetStyleColName(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_ChildWindowBg: return "ChildWindowBg";
+ 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_TitleBgCollapsed: return "TitleBgCollapsed";
+ case ImGuiCol_TitleBgActive: return "TitleBgActive";
+ 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_ComboBg: return "ComboBg";
+ 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_Column: return "Column";
+ case ImGuiCol_ColumnHovered: return "ColumnHovered";
+ case ImGuiCol_ColumnActive: return "ColumnActive";
+ case ImGuiCol_ResizeGrip: return "ResizeGrip";
+ case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
+ case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
+ case ImGuiCol_CloseButton: return "CloseButton";
+ case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered";
+ case ImGuiCol_CloseButtonActive: return "CloseButtonActive";
+ 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_ModalWindowDarkening: return "ModalWindowDarkening";
+ }
+ IM_ASSERT(0);
+ return "Unknown";
+}
+
+bool ImGui::IsWindowHovered()
+{
+ ImGuiContext& g = *GImGui;
+ return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow);
+}
+
+bool ImGui::IsWindowFocused()
+{
+ ImGuiContext& g = *GImGui;
+ return g.FocusedWindow == g.CurrentWindow;
+}
+
+bool ImGui::IsRootWindowFocused()
+{
+ ImGuiContext& g = *GImGui;
+ return g.FocusedWindow == g.CurrentWindow->RootWindow;
+}
+
+bool ImGui::IsRootWindowOrAnyChildFocused()
+{
+ ImGuiContext& g = *GImGui;
+ return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow;
+}
+
+bool ImGui::IsRootWindowOrAnyChildHovered()
+{
+ ImGuiContext& g = *GImGui;
+ return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow);
+}
+
+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;
+}
+
+static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
+{
+ window->DC.CursorMaxPos.y += window->Scroll.y;
+ window->Scroll.y = new_scroll_y;
+ window->DC.CursorMaxPos.y -= window->Scroll.y;
+}
+
+static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond)
+{
+ // Test condition (NB: bit 0 is always true) and clear flags for next time
+ if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
+ return;
+ window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+ window->SetWindowPosCenterWanted = false;
+
+ // Set
+ const ImVec2 old_pos = window->Pos;
+ window->PosFloat = pos;
+ window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ 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, ImGuiSetCond cond)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ SetWindowPos(window, pos, cond);
+}
+
+void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond)
+{
+ ImGuiWindow* window = FindWindowByName(name);
+ if (window)
+ SetWindowPos(window, pos, cond);
+}
+
+ImVec2 ImGui::GetWindowSize()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->Size;
+}
+
+static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond)
+{
+ // Test condition (NB: bit 0 is always true) and clear flags for next time
+ if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
+ return;
+ window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+
+ // Set
+ if (size.x > 0.0f)
+ {
+ window->AutoFitFramesX = 0;
+ window->SizeFull.x = size.x;
+ }
+ else
+ {
+ window->AutoFitFramesX = 2;
+ window->AutoFitOnlyGrows = false;
+ }
+ if (size.y > 0.0f)
+ {
+ window->AutoFitFramesY = 0;
+ window->SizeFull.y = size.y;
+ }
+ else
+ {
+ window->AutoFitFramesY = 2;
+ window->AutoFitOnlyGrows = false;
+ }
+}
+
+void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond)
+{
+ SetWindowSize(GImGui->CurrentWindow, size, cond);
+}
+
+void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond)
+{
+ ImGuiWindow* window = FindWindowByName(name);
+ if (window)
+ SetWindowSize(window, size, cond);
+}
+
+static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond)
+{
+ // Test condition (NB: bit 0 is always true) and clear flags for next time
+ if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
+ return;
+ window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+
+ // Set
+ window->Collapsed = collapsed;
+}
+
+void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond)
+{
+ SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
+}
+
+bool ImGui::IsWindowCollapsed()
+{
+ return GImGui->CurrentWindow->Collapsed;
+}
+
+void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond)
+{
+ ImGuiWindow* window = FindWindowByName(name);
+ if (window)
+ SetWindowCollapsed(window, collapsed, cond);
+}
+
+void ImGui::SetWindowFocus()
+{
+ FocusWindow(GImGui->CurrentWindow);
+}
+
+void ImGui::SetWindowFocus(const char* name)
+{
+ if (name)
+ {
+ ImGuiWindow* window = FindWindowByName(name);
+ if (window)
+ FocusWindow(window);
+ }
+ else
+ {
+ FocusWindow(NULL);
+ }
+}
+
+void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowPosVal = pos;
+ g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
+}
+
+void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX);
+ g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
+}
+
+void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowSizeVal = size;
+ g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always;
+}
+
+void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowSizeConstraint = true;
+ g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max);
+ g.SetNextWindowSizeConstraintCallback = custom_callback;
+ g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data;
+}
+
+void ImGui::SetNextWindowContentSize(const ImVec2& size)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowContentSizeVal = size;
+ g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
+}
+
+void ImGui::SetNextWindowContentWidth(float width)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f);
+ g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
+}
+
+void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowCollapsedVal = collapsed;
+ g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always;
+}
+
+void ImGui::SetNextWindowFocus()
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextWindowFocus = true;
+}
+
+// In window space (not screen space!)
+ImVec2 ImGui::GetContentRegionMax()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImVec2 mx = window->ContentsRegionRect.Max;
+ if (window->DC.ColumnsCount != 1)
+ mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 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;
+}
+
+ImVec2 ImGui::GetWindowContentRegionMax()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->ContentsRegionRect.Max;
+}
+
+float ImGui::GetWindowContentRegionWidth()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
+}
+
+float ImGui::GetTextLineHeight()
+{
+ ImGuiContext& g = *GImGui;
+ return g.FontSize;
+}
+
+float ImGui::GetTextLineHeightWithSpacing()
+{
+ ImGuiContext& g = *GImGui;
+ return g.FontSize + g.Style.ItemSpacing.y;
+}
+
+float ImGui::GetItemsLineHeightWithSpacing()
+{
+ 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->FontTexUvWhitePixel;
+}
+
+void ImGui::SetWindowFontScale(float scale)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ window->FontWindowScale = scale;
+ g.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 = GetCurrentWindow();
+ return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
+}
+
+float ImGui::GetCursorPosY()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ 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;
+}
+
+float ImGui::GetScrollX()
+{
+ return GImGui->CurrentWindow->Scroll.x;
+}
+
+float ImGui::GetScrollY()
+{
+ return GImGui->CurrentWindow->Scroll.y;
+}
+
+float ImGui::GetScrollMaxX()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x;
+}
+
+float ImGui::GetScrollMaxY()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y;
+}
+
+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(); // 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);
+ if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y)
+ window->ScrollTarget.y = 0.0f;
+ 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::SetScrollHere(float center_y_ratio)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * 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 - window->Pos.y, center_y_ratio);
+}
+
+void ImGui::SetKeyboardFocusHere(int offset)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
+ window->FocusIdxTabRequestNext = INT_MAX;
+}
+
+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::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::Text(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ TextV(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::TextColored(const ImVec4& col, const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ TextColoredV(col, 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::TextDisabled(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ TextDisabledV(fmt, args);
+ va_end(args);
+}
+
+void ImGui::TextWrappedV(const char* fmt, va_list args)
+{
+ PushTextWrapPos(0.0f);
+ TextV(fmt, args);
+ PopTextWrapPos();
+}
+
+void ImGui::TextWrapped(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ TextWrappedV(fmt, args);
+ va_end(args);
+}
+
+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 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.
+ const char* line = text;
+ const float line_height = GetTextLineHeight();
+ const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset);
+ 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 = strchr(line, '\n');
+ 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(GetWindowWidth(), line_height));
+ while (line < text_end)
+ {
+ const char* line_end = strchr(line, '\n');
+ if (IsClippedEx(line_rect, NULL, false))
+ break;
+
+ 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);
+ if (!line_end)
+ line_end = text_end;
+ 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 = strchr(line, '\n');
+ 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, NULL);
+ }
+ 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
+ ImVec2 text_pos = window->DC.CursorPos;
+ text_pos.y += window->DC.CurrentLineTextBaseOffset;
+
+ ImRect bb(text_pos, text_pos + text_size);
+ ItemSize(text_size);
+ if (!ItemAdd(bb, NULL))
+ return;
+
+ // Render (we don't hide text after ## in this end-user function)
+ RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
+ }
+}
+
+void ImGui::AlignFirstTextHeightToWidgets()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height.
+ ImGuiContext& g = *GImGui;
+ ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y);
+ SameLine(0, 0);
+}
+
+// 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, NULL))
+ 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, ImGuiAlign_VCenter);
+ 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::LabelText(const char* label, const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ LabelTextV(label, fmt, args);
+ va_end(args);
+}
+
+static inline bool IsWindowContentHoverable(ImGuiWindow* window)
+{
+ // An active popup disable hovering on other windows (apart from its own children)
+ ImGuiContext& g = *GImGui;
+ if (ImGuiWindow* focused_window = g.FocusedWindow)
+ if (ImGuiWindow* focused_root_window = focused_window->RootWindow)
+ if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow)
+ return false;
+
+ return true;
+}
+
+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) SetActiveID(0);
+ return false;
+ }
+
+ if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
+ flags |= ImGuiButtonFlags_PressedOnClickRelease;
+
+ bool pressed = false;
+ bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0);
+ if (hovered)
+ {
+ SetHoveredID(id);
+ 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> ..
+ if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
+ {
+ SetActiveID(id, window); // Hold on ID
+ FocusWindow(window);
+ g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
+ }
+ if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
+ {
+ pressed = true;
+ SetActiveID(0);
+ 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;
+ SetActiveID(0);
+ }
+
+ // '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;
+ }
+ }
+
+ bool held = false;
+ if (g.ActiveId == id)
+ {
+ 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>
+ pressed = true;
+ SetActiveID(0);
+ }
+ }
+
+ // 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_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
+ hovered = pressed = held = false;
+
+ 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)
+ 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.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
+ bool hovered, held;
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
+
+ // Render
+ const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
+ RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
+ RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, ImGuiAlign_Center | ImGuiAlign_VCenter);
+
+ // 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;
+
+ 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;
+}
+
+// Upper-right button to close a window.
+bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+
+ const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
+
+ bool hovered, held;
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held);
+
+ // Render
+ const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton);
+ const ImVec2 center = bb.GetCenter();
+ window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12);
+
+ const float cross_extent = (radius * 0.7071f) - 1.0f;
+ if (hovered)
+ {
+ window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text));
+ window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text));
+ }
+
+ return pressed;
+}
+
+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, NULL))
+ 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 *)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((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
+ 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;
+}
+
+// Start logging ImGui output to TTY
+void ImGui::LogToTTY(int max_depth)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.LogEnabled)
+ return;
+ ImGuiWindow* window = GetCurrentWindowRead();
+
+ g.LogEnabled = true;
+ g.LogFile = stdout;
+ 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 = GetCurrentWindowRead();
+
+ if (!filename)
+ {
+ filename = g.IO.LogFilename;
+ if (!filename)
+ return;
+ }
+
+ g.LogFile = fopen(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 = GetCurrentWindowRead();
+
+ g.LogEnabled = true;
+ g.LogFile = NULL;
+ 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);
+ g.LogEnabled = false;
+ if (g.LogFile != NULL)
+ {
+ if (g.LogFile == stdout)
+ fflush(g.LogFile);
+ else
+ fclose(g.LogFile);
+ g.LogFile = NULL;
+ }
+ if (g.LogClipboard->size() > 1)
+ {
+ if (g.IO.SetClipboardTextFn)
+ g.IO.SetClipboardTextFn(g.LogClipboard->begin());
+ g.LogClipboard->clear();
+ }
+}
+
+// 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);
+}
+
+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 explicitely use SetNextTreeNode*** functions)
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiStorage* storage = window->DC.StateStorage;
+
+ bool is_open;
+ if (g.SetNextTreeNodeOpenCond != 0)
+ {
+ if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always)
+ {
+ is_open = g.SetNextTreeNodeOpenVal;
+ storage->SetInt(id, is_open);
+ }
+ else
+ {
+ // We treat ImGuiSetCondition_Once and ImGuiSetCondition_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.SetNextTreeNodeOpenVal;
+ storage->SetInt(id, is_open);
+ }
+ else
+ {
+ is_open = stored_value != 0;
+ }
+ }
+ g.SetNextTreeNodeOpenCond = 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 ? 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(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it
+ const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
+ ImRect 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
+ bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
+ 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 we want want the hit test to be done up to the right side of the content or not)
+ const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y);
+ bool is_open = TreeNodeBehaviorIsOpen(id, flags);
+ if (!ItemAdd(interact_bb, &id))
+ {
+ 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_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0);
+ 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 (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
+ {
+ bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick));
+ if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
+ toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
+ if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
+ toggled |= g.IO.MouseDoubleClicked[0];
+ if (toggled)
+ {
+ is_open = !is_open;
+ window->DC.StateStorage->SetInt(id, is_open);
+ }
+ }
+ if (flags & ImGuiTreeNodeFlags_AllowOverlapMode)
+ SetItemAllowOverlap();
+
+ // Render
+ const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
+ const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y);
+ if (display_frame)
+ {
+ // Framed type
+ RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
+ RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f, true);
+ 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, bb.Max, label, label_end, &label_size);
+ LogRenderedText(text_pos, log_suffix+1, log_suffix+3);
+ }
+ else
+ {
+ RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size);
+ }
+ }
+ else
+ {
+ // Unframed typed for tree nodes
+ if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
+ RenderFrame(bb.Min, bb.Max, col, false);
+
+ if (flags & ImGuiTreeNodeFlags_Bullet)
+ RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
+ else if (!(flags & ImGuiTreeNodeFlags_Leaf))
+ RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f, false);
+ if (g.LogEnabled)
+ LogRenderedText(text_pos, ">");
+ RenderText(text_pos, label, label_end, false);
+ }
+
+ if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
+ TreePushRawID(id);
+ return is_open;
+}
+
+// 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 | ImGuiTreeNodeFlags_NoTreePushOnOpen). 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 | ImGuiTreeNodeFlags_NoTreePushOnOpen, 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 | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 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;
+ float button_sz = g.FontSize * 0.5f;
+ if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
+ *p_open = false;
+ }
+
+ return is_open;
+}
+
+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::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::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* 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::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);
+}
+
+void ImGui::TreeAdvanceToLabelPos()
+{
+ ImGuiContext& g = *GImGui;
+ g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
+}
+
+// Horizontal distance preceeding 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, ImGuiSetCond cond)
+{
+ ImGuiContext& g = *GImGui;
+ g.SetNextTreeNodeOpenVal = is_open;
+ g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always;
+}
+
+void ImGui::PushID(const char* str_id)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->IDStack.push_back(window->GetID(str_id));
+}
+
+void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
+}
+
+void ImGui::PushID(const void* ptr_id)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->IDStack.push_back(window->GetID(ptr_id));
+}
+
+void ImGui::PushID(int int_id)
+{
+ const void* ptr_id = (void*)(intptr_t)int_id;
+ ImGuiWindow* window = GetCurrentWindow();
+ window->IDStack.push_back(window->GetID(ptr_id));
+}
+
+void ImGui::PopID()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ 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);
+}
+
+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.CurrentLineHeight, 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, NULL))
+ {
+ 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);
+}
+
+// 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, true);
+ 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.CurrentLineHeight, 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, NULL))
+ 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);
+}
+
+void ImGui::BulletText(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ BulletTextV(fmt, args);
+ va_end(args);
+}
+
+static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
+{
+ if (data_type == ImGuiDataType_Int)
+ ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
+ else if (data_type == ImGuiDataType_Float)
+ ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
+}
+
+static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
+{
+ if (data_type == ImGuiDataType_Int)
+ {
+ if (decimal_precision < 0)
+ ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
+ else
+ ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
+ }
+ else if (data_type == ImGuiDataType_Float)
+ {
+ if (decimal_precision < 0)
+ ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits?
+ else
+ ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
+ }
+}
+
+static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1
+{
+ if (data_type == ImGuiDataType_Int)
+ {
+ if (op == '+')
+ *(int*)value1 = *(int*)value1 + *(const int*)value2;
+ else if (op == '-')
+ *(int*)value1 = *(int*)value1 - *(const int*)value2;
+ }
+ else if (data_type == ImGuiDataType_Float)
+ {
+ if (op == '+')
+ *(float*)value1 = *(float*)value1 + *(const float*)value2;
+ else if (op == '-')
+ *(float*)value1 = *(float*)value1 - *(const float*)value2;
+ }
+}
+
+// User can input math operators (e.g. +100) to edit a numerical values.
+static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
+{
+ while (ImCharIsSpace(*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 (ImCharIsSpace(*buf))
+ buf++;
+ }
+ else
+ {
+ op = 0;
+ }
+ if (!buf[0])
+ return false;
+
+ if (data_type == ImGuiDataType_Int)
+ {
+ if (!scalar_format)
+ scalar_format = "%d";
+ int* v = (int*)data_ptr;
+ const int old_v = *v;
+ int arg0 = *v;
+ if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 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
+ float arg1 = 0.0f;
+ if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract)
+ else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply
+ else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide
+ else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant
+ return (old_v != *v);
+ }
+ 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
+ scalar_format = "%f";
+ float* v = (float*)data_ptr;
+ const float old_v = *v;
+ float arg0 = *v;
+ if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1)
+ return false;
+
+ float arg1 = 0.0f;
+ if (sscanf(buf, scalar_format, &arg1) < 1)
+ return false;
+ if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract)
+ else if (op == '*') { *v = arg0 * arg1; } // Multiply
+ else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide
+ else { *v = arg1; } // Assign constant
+ return (old_v != *v);
+ }
+
+ return false;
+}
+
+// Create text input in place of a slider (when CTRL+Clicking on slider)
+bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+
+ // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
+ SetActiveID(g.ScalarAsInputTextId, window);
+ SetHoveredID(0);
+ FocusableItemUnregister(window);
+
+ char buf[32];
+ DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
+ bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
+ if (g.ScalarAsInputTextId == 0)
+ {
+ // First frame
+ IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
+ g.ScalarAsInputTextId = g.ActiveId;
+ SetHoveredID(id);
+ }
+ else if (g.ActiveId != g.ScalarAsInputTextId)
+ {
+ // Release
+ g.ScalarAsInputTextId = 0;
+ }
+ if (text_value_changed)
+ return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
+ return false;
+}
+
+// Parse display precision back from the display format string
+int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
+{
+ int precision = default_precision;
+ while ((fmt = strchr(fmt, '%')) != NULL)
+ {
+ fmt++;
+ if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
+ while (*fmt >= '0' && *fmt <= '9')
+ fmt++;
+ if (*fmt == '.')
+ {
+ precision = atoi(fmt + 1);
+ if (precision < 0 || precision > 10)
+ precision = default_precision;
+ }
+ break;
+ }
+ return precision;
+}
+
+float ImGui::RoundScalar(float value, int decimal_precision)
+{
+ // Round past decimal precision
+ // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
+ // FIXME: Investigate better rounding methods
+ 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 };
+ float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
+ bool negative = value < 0.0f;
+ value = fabsf(value);
+ float remainder = fmodf(value, min_step);
+ if (remainder <= min_step*0.5f)
+ value -= remainder;
+ else
+ value += (min_step - remainder);
+ return negative ? -value : value;
+}
+
+bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ const ImGuiStyle& style = g.Style;
+
+ // Draw frame
+ RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
+
+ const bool is_non_linear = fabsf(power - 1.0f) > 0.0001f;
+ const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
+
+ const float grab_padding = 2.0f;
+ const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
+ float grab_sz;
+ if (decimal_precision > 0)
+ grab_sz = ImMin(style.GrabMinSize, slider_sz);
+ else
+ grab_sz = ImMin(ImMax(1.0f * (slider_sz / (v_max-v_min+1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
+ const float slider_usable_sz = slider_sz - grab_sz;
+ const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
+ const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
+
+ // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
+ float linear_zero_pos = 0.0f; // 0.0->1.0f
+ if (v_min * v_max < 0.0f)
+ {
+ // Different sign
+ const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
+ const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
+ linear_zero_pos = 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 clicking on the slider
+ bool value_changed = false;
+ if (g.ActiveId == id)
+ {
+ if (g.IO.MouseDown[0])
+ {
+ const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
+ float normalized_pos = ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f);
+ if (!is_horizontal)
+ normalized_pos = 1.0f - normalized_pos;
+
+ float new_value;
+ if (is_non_linear)
+ {
+ // Account for logarithmic scale on both sides of the zero
+ if (normalized_pos < linear_zero_pos)
+ {
+ // Negative: rescale to the negative range before powering
+ float a = 1.0f - (normalized_pos / linear_zero_pos);
+ a = powf(a, power);
+ new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
+ }
+ else
+ {
+ // Positive: rescale to the positive range before powering
+ float a;
+ if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
+ a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos);
+ else
+ a = normalized_pos;
+ a = powf(a, power);
+ new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
+ }
+ }
+ else
+ {
+ // Linear slider
+ new_value = ImLerp(v_min, v_max, normalized_pos);
+ }
+
+ // Round past decimal precision
+ new_value = RoundScalar(new_value, decimal_precision);
+ if (*v != new_value)
+ {
+ *v = new_value;
+ value_changed = true;
+ }
+ }
+ else
+ {
+ SetActiveID(0);
+ }
+ }
+
+ // Calculate slider grab positioning
+ float grab_t;
+ if (is_non_linear)
+ {
+ float v_clamped = ImClamp(*v, v_min, v_max);
+ if (v_clamped < 0.0f)
+ {
+ const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
+ grab_t = (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
+ }
+ else
+ {
+ const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
+ grab_t = linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
+ }
+ }
+ else
+ {
+ // Linear slider
+ grab_t = (ImClamp(*v, v_min, v_max) - v_min) / (v_max - v_min);
+ }
+
+ // Draw
+ if (!is_horizontal)
+ grab_t = 1.0f - grab_t;
+ const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
+ ImRect grab_bb;
+ if (is_horizontal)
+ grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding));
+ else
+ grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f));
+ window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
+
+ return value_changed;
+}
+
+// Use power!=1.0 for logarithmic sliders.
+// Adjust display_format to decorate the value with a prefix or a suffix.
+// "%.3f" 1.234
+// "%5.2f secs" 01.23 secs
+// "Gold: %.0f" Gold: 1
+bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_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))
+ {
+ ItemSize(total_bb, style.FramePadding.y);
+ return false;
+ }
+
+ const bool hovered = IsHovered(frame_bb, id);
+ if (hovered)
+ SetHoveredID(id);
+
+ if (!display_format)
+ display_format = "%.3f";
+ int decimal_precision = ParseFormatPrecision(display_format, 3);
+
+ // Tabbing or CTRL-clicking on Slider turns it into an input box
+ bool start_text_input = false;
+ const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
+ if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
+ {
+ SetActiveID(id, window);
+ FocusWindow(window);
+
+ if (tab_focus_requested || g.IO.KeyCtrl)
+ {
+ start_text_input = true;
+ g.ScalarAsInputTextId = 0;
+ }
+ }
+ if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
+ return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
+
+ ItemSize(total_bb, style.FramePadding.y);
+
+ // Actual slider behavior + render grab
+ const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
+
+ // 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 + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
+ RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter);
+
+ 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* display_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;
+
+ const bool hovered = IsHovered(frame_bb, id);
+ if (hovered)
+ SetHoveredID(id);
+
+ if (!display_format)
+ display_format = "%.3f";
+ int decimal_precision = ParseFormatPrecision(display_format, 3);
+
+ if (hovered && g.IO.MouseClicked[0])
+ {
+ SetActiveID(id, window);
+ FocusWindow(window);
+ }
+
+ // Actual slider behavior + render grab
+ bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
+
+ // 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];
+ char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
+ RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center);
+ 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::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
+{
+ float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
+ bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 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* display_format)
+{
+ if (!display_format)
+ display_format = "%.0f";
+ float v_f = (float)*v;
+ bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
+ *v = (int)v_f;
+ return value_changed;
+}
+
+bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
+{
+ if (!display_format)
+ display_format = "%.0f";
+ float v_f = (float)*v;
+ bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
+ *v = (int)v_f;
+ return value_changed;
+}
+
+// Add multiple sliders on 1 line for compact edition of multiple components
+bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ bool value_changed = false;
+ BeginGroup();
+ PushID(label);
+ PushMultiItemsWidths(components);
+ for (int i = 0; i < components; i++)
+ {
+ PushID(i);
+ value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+ PopID();
+ PopItemWidth();
+ }
+ PopID();
+
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
+{
+ return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
+}
+
+bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
+{
+ return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
+}
+
+bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
+{
+ return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
+}
+
+bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ bool value_changed = false;
+ BeginGroup();
+ PushID(label);
+ PushMultiItemsWidths(components);
+ for (int i = 0; i < components; i++)
+ {
+ PushID(i);
+ value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+ PopID();
+ PopItemWidth();
+ }
+ PopID();
+
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
+{
+ return SliderIntN(label, v, 2, v_min, v_max, display_format);
+}
+
+bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
+{
+ return SliderIntN(label, v, 3, v_min, v_max, display_format);
+}
+
+bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
+{
+ return SliderIntN(label, v, 4, v_min, v_max, display_format);
+}
+
+bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power)
+{
+ ImGuiContext& g = *GImGui;
+ const ImGuiStyle& style = g.Style;
+
+ // Draw frame
+ const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
+ RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
+
+ bool value_changed = false;
+
+ // Process clicking on the drag
+ if (g.ActiveId == id)
+ {
+ if (g.IO.MouseDown[0])
+ {
+ if (g.ActiveIdIsJustActivated)
+ {
+ // Lock current value on click
+ g.DragCurrentValue = *v;
+ g.DragLastMouseDelta = ImVec2(0.f, 0.f);
+ }
+
+ float v_cur = g.DragCurrentValue;
+ const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
+ if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f)
+ {
+ float speed = v_speed;
+ if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
+ speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
+ if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
+ speed = speed * g.DragSpeedScaleFast;
+ if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
+ speed = speed * g.DragSpeedScaleSlow;
+
+ float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed;
+ if (fabsf(power - 1.0f) > 0.001f)
+ {
+ // Logarithmic curve on both side of 0.0
+ float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
+ float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
+ float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign);
+ float v1_abs = v1 >= 0.0f ? v1 : -v1;
+ float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
+ v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
+ }
+ else
+ {
+ v_cur += delta;
+ }
+ g.DragLastMouseDelta.x = mouse_drag_delta.x;
+
+ // Clamp
+ if (v_min < v_max)
+ v_cur = ImClamp(v_cur, v_min, v_max);
+ g.DragCurrentValue = v_cur;
+ }
+
+ // Round to user desired precision, then apply
+ v_cur = RoundScalar(v_cur, decimal_precision);
+ if (*v != v_cur)
+ {
+ *v = v_cur;
+ value_changed = true;
+ }
+ }
+ else
+ {
+ SetActiveID(0);
+ }
+ }
+
+ return value_changed;
+}
+
+bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_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 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))
+ {
+ ItemSize(total_bb, style.FramePadding.y);
+ return false;
+ }
+
+ const bool hovered = IsHovered(frame_bb, id);
+ if (hovered)
+ SetHoveredID(id);
+
+ if (!display_format)
+ display_format = "%.3f";
+ int decimal_precision = ParseFormatPrecision(display_format, 3);
+
+ // Tabbing or CTRL-clicking on Drag turns it into an input box
+ bool start_text_input = false;
+ const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
+ if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0])))
+ {
+ SetActiveID(id, window);
+ FocusWindow(window);
+
+ if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
+ {
+ start_text_input = true;
+ g.ScalarAsInputTextId = 0;
+ }
+ }
+ if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
+ return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
+
+ // Actual drag behavior
+ ItemSize(total_bb, style.FramePadding.y);
+ const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
+
+ // 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 + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
+ RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImGuiAlign_Center|ImGuiAlign_VCenter);
+
+ 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::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ bool value_changed = false;
+ BeginGroup();
+ PushID(label);
+ PushMultiItemsWidths(components);
+ for (int i = 0; i < components; i++)
+ {
+ PushID(i);
+ value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+ PopID();
+ PopItemWidth();
+ }
+ PopID();
+
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
+{
+ return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
+}
+
+bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
+{
+ return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
+}
+
+bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
+{
+ return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_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* display_format, const char* display_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), display_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, display_format_max ? display_format_max : display_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* display_format)
+{
+ if (!display_format)
+ display_format = "%.0f";
+ float v_f = (float)*v;
+ bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
+ *v = (int)v_f;
+ return value_changed;
+}
+
+bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ bool value_changed = false;
+ BeginGroup();
+ PushID(label);
+ PushMultiItemsWidths(components);
+ for (int i = 0; i < components; i++)
+ {
+ PushID(i);
+ value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+ PopID();
+ PopItemWidth();
+ }
+ PopID();
+
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
+{
+ return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
+}
+
+bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
+{
+ return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
+}
+
+bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
+{
+ return DragIntN(label, v, 4, v_speed, v_min, v_max, display_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* display_format, const char* display_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), display_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, display_format_max ? display_format_max : display_format);
+ PopItemWidth();
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+ PopID();
+
+ return value_changed;
+}
+
+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, NULL))
+ return;
+
+ // 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);
+
+ 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 (IsHovered(inner_bb, 0))
+ {
+ 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;
+
+ float v0 = values_getter(data, (0 + values_offset) % values_count);
+ float t0 = 0.0f;
+ ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
+
+ 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) / (scale_max - scale_min)) );
+
+ // 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, 1.0f));
+ 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, ImGuiAlign_Center);
+
+ 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 = *(float*)(void*)((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);
+}
+
+// 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, NULL))
+ return;
+
+ // Render
+ fraction = ImSaturate(fraction);
+ RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
+ bb.Reduce(ImVec2(window->BorderSize, window->BorderSize));
+ const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
+ RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, 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, ImGuiAlign_Left|ImGuiAlign_VCenter, &bb.Min, &bb.Max);
+}
+
+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));
+ 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);
+
+ 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));
+ window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
+ }
+
+ if (g.LogEnabled)
+ LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]");
+ if (label_size.x > 0.0f)
+ RenderText(text_bb.GetTL(), 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);
+
+ 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 (window->Flags & ImGuiWindowFlags_ShowBorders)
+ {
+ window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16);
+ window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16);
+ }
+
+ if (g.LogEnabled)
+ LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )");
+ if (label_size.x > 0.0f)
+ RenderText(text_bb.GetTL(), 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;
+}
+
+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((unsigned short)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->Text[idx]; }
+static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[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->Text.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 ImCharIsSpace(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->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; }
+static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int 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->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; }
+static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int 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) { 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->Text.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
+ const ImWchar* src = obj->Text.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 int text_len = obj->CurLenW;
+ if (new_text_len + text_len + 1 > obj->Text.Size)
+ return false;
+
+ const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
+ if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
+ return false;
+
+ ImWchar* text = obj->Text.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->Text[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 "stb_textedit.h"
+
+}
+
+void ImGuiTextEditState::OnKeyPressed(int key)
+{
+ stb_textedit_key(this, &StbState, key);
+ CursorFollow = true;
+ CursorAnimReset();
+}
+
+// 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 ImGuiTextEditCallbackData::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 ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
+{
+ const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
+ if (new_text_len + BufTextLen + 1 >= BufSize)
+ return;
+
+ 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, ImGuiTextEditCallback 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))
+ {
+ if (flags & ImGuiInputTextFlags_CharsDecimal)
+ if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
+ 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 (ImCharIsSpace(c))
+ return false;
+ }
+
+ if (flags & ImGuiInputTextFlags_CallbackCharFilter)
+ {
+ ImGuiTextEditCallbackData callback_data;
+ memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
+ 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
+// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect.
+// 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, ImGuiTextEditCallback callback, void* 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 ImGuiID id = window->GetID(label);
+ 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 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)
+ {
+ BeginGroup();
+ if (!BeginChildFrame(id, frame_bb.GetSize()))
+ {
+ EndChildFrame();
+ EndGroup();
+ return false;
+ }
+ draw_window = GetCurrentWindow();
+ size.x -= draw_window->ScrollbarSizes.x;
+ }
+ else
+ {
+ ItemSize(total_bb, style.FramePadding.y);
+ if (!ItemAdd(total_bb, &id))
+ return false;
+ }
+
+ // Password pushes a temporary font with only a fallback glyph
+ if (is_password)
+ {
+ const ImFont::Glyph* 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->FallbackXAdvance = glyph->XAdvance;
+ IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty());
+ PushFont(password_font);
+ }
+
+ // NB: we are only allowed to access 'edit_state' if we are the active widget.
+ ImGuiTextEditState& edit_state = g.InputTextState;
+
+ const bool is_ctrl_down = io.KeyCtrl;
+ const bool is_shift_down = io.KeyShift;
+ const bool is_alt_down = io.KeyAlt;
+ const bool is_super_down = io.KeySuper;
+ const bool focus_requested = FocusableItemRegister(window, g.ActiveId == 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 hovered = IsHovered(frame_bb, id);
+ if (hovered)
+ {
+ SetHoveredID(id);
+ g.MouseCursor = ImGuiMouseCursor_TextInput;
+ }
+ 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->GetID("#SCROLLY");
+
+ bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
+ if (focus_requested || user_clicked || user_scrolled)
+ {
+ 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;
+ edit_state.Text.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(buf_size+1); // utf-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
+ ImFormatString(edit_state.InitialText.Data, edit_state.InitialText.Size, "%s", buf);
+ const char* buf_end = NULL;
+ edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
+ edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() 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 && is_ctrl_down)))
+ select_all = true;
+ }
+ SetActiveID(id, window);
+ FocusWindow(window);
+ }
+ else if (io.MouseClicked[0])
+ {
+ // Release focus when we click outside
+ if (g.ActiveId == id)
+ SetActiveID(0);
+ }
+
+ bool value_changed = false;
+ bool enter_pressed = false;
+
+ if (g.ActiveId == id)
+ {
+ if (!is_editable && !g.ActiveIdIsJustActivated)
+ {
+ // When read-only we always use the live data passed to the function
+ edit_state.Text.resize(buf_size+1);
+ const char* buf_end = NULL;
+ edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
+ edit_state.CurLenA = (int)(buf_end - buf);
+ edit_state.CursorClamp();
+ }
+
+ edit_state.BufSizeA = buf_size;
+
+ // 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];
+
+ // Edit in progress
+ const float mouse_x = (g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
+ const float mouse_y = (is_multiline ? (g.IO.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
+
+ if (select_all || (hovered && !io.DoubleClickSelectsWord && io.MouseDoubleClicked[0]))
+ {
+ edit_state.SelectAll();
+ edit_state.SelectedAllMouseLock = true;
+ }
+ else if (hovered && io.DoubleClickSelectsWord && io.MouseDoubleClicked[0])
+ {
+ // 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)
+ {
+ 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 (g.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 CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters.
+ if (!(is_ctrl_down && !is_alt_down) && is_editable)
+ {
+ for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++)
+ if (unsigned int c = (unsigned int)g.IO.InputCharacters[n])
+ {
+ // Insert character if they pass filtering
+ if (!InputTextFilterCharacter(&c, flags, callback, user_data))
+ continue;
+ edit_state.OnKeyPressed((int)c);
+ }
+ }
+
+ // Consume characters
+ memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
+ }
+
+ // Handle various key-presses
+ bool cancel_edit = false;
+ const int k_mask = (is_shift_down ? STB_TEXTEDIT_K_SHIFT : 0);
+ const bool is_shortcutkey_only = (io.ShortcutsUseSuperKey ? (is_super_down && !is_alt_down && !is_shift_down && !is_ctrl_down) : (is_ctrl_down && !is_alt_down && !is_shift_down && !is_super_down));
+ const bool is_wordmove_key_down = (io.WordMovementUsesAltKey ? io.KeyAlt : io.KeyCtrl);
+
+ if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); }
+ else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); }
+ else if (is_multiline && IsKeyPressedMap(ImGuiKey_UpArrow)) { if (is_ctrl_down) SetWindowScrollY(draw_window, draw_window->Scroll.y - g.FontSize); else edit_state.OnKeyPressed(STB_TEXTEDIT_K_UP | k_mask); }
+ else if (is_multiline && IsKeyPressedMap(ImGuiKey_DownArrow)) { if (is_ctrl_down) SetWindowScrollY(draw_window, draw_window->Scroll.y + g.FontSize); else edit_state.OnKeyPressed(STB_TEXTEDIT_K_DOWN| k_mask); }
+ else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
+ else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? 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) { 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 && !is_ctrl_down) || (!ctrl_enter_for_new_line && is_ctrl_down))
+ {
+ SetActiveID(0);
+ enter_pressed = true;
+ }
+ else if (is_editable)
+ {
+ unsigned int c = '\n'; // Insert new line
+ if (InputTextFilterCharacter(&c, flags, callback, user_data))
+ edit_state.OnKeyPressed((int)c);
+ }
+ }
+ else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !is_ctrl_down && !is_shift_down && !is_alt_down && is_editable)
+ {
+ unsigned int c = '\t'; // Insert TAB
+ if (InputTextFilterCharacter(&c, flags, callback, user_data))
+ edit_state.OnKeyPressed((int)c);
+ }
+ else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveID(0); cancel_edit = true; }
+ else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
+ else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
+ else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
+ else if (is_shortcutkey_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
+ {
+ // Cut, Copy
+ const bool cut = IsKeyPressedMap(ImGuiKey_X);
+ if (cut && !edit_state.HasSelection())
+ edit_state.SelectAll();
+
+ if (g.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.TempTextBuffer.resize((ie-ib) * 4 + 1);
+ ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
+ g.IO.SetClipboardTextFn(edit_state.TempTextBuffer.Data);
+ }
+
+ if (cut)
+ {
+ edit_state.CursorFollow = true;
+ stb_textedit_cut(&edit_state, &edit_state.StbState);
+ }
+ }
+ else if (is_shortcutkey_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
+ {
+ // Paste
+ if (g.IO.GetClipboardTextFn)
+ {
+ if (const char* clipboard = g.IO.GetClipboardTextFn())
+ {
+ // Remove new-line from pasted buffer
+ const int clipboard_len = (int)strlen(clipboard);
+ ImWchar* clipboard_filtered = (ImWchar*)ImGui::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, 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;
+ }
+ ImGui::MemFree(clipboard_filtered);
+ }
+ }
+ }
+
+ if (cancel_edit)
+ {
+ // Restore initial value
+ if (is_editable)
+ {
+ ImFormatString(buf, buf_size, "%s", edit_state.InitialText.Data);
+ value_changed = true;
+ }
+ }
+ else
+ {
+ // 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.TempTextBuffer.resize(edit_state.Text.Size * 4);
+ ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.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)
+ {
+ ImGuiTextEditCallbackData callback_data;
+ memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
+ callback_data.EventFlag = event_flag;
+ callback_data.Flags = flags;
+ callback_data.UserData = user_data;
+ callback_data.ReadOnly = !is_editable;
+
+ callback_data.EventKey = event_key;
+ callback_data.Buf = edit_state.TempTextBuffer.Data;
+ callback_data.BufTextLen = edit_state.CurLenA;
+ callback_data.BufSize = edit_state.BufSizeA;
+ 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.Text.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.TempTextBuffer.Data); // Invalid to modify those fields
+ IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
+ 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);
+ 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!
+ edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.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();
+ }
+ }
+ }
+
+ // Copy back to user buffer
+ if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
+ {
+ ImFormatString(buf, buf_size, "%s", edit_state.TempTextBuffer.Data);
+ value_changed = true;
+ }
+ }
+ }
+
+ if (!is_multiline)
+ RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
+
+ // Render
+ 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);
+ if (g.ActiveId == id || (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetID("#SCROLLY")))
+ {
+ edit_state.CursorAnim += g.IO.DeltaTime;
+
+ // We need to:
+ // - Display the text (this 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)
+ const ImWchar* text_begin = edit_state.Text.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 != 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;
+ }
+
+ // Calculate text height
+ 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)
+ {
+ 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((unsigned short)' ') * 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.Clip(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;
+ }
+ }
+
+ draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf, buf+edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
+
+ // Draw blinking cursor
+ bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(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.OsImePosRequest = 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, &buf_end) * g.FontSize); // We don't need width
+ draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf, 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, NULL);
+
+ if (label_size.x > 0)
+ RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
+
+ if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
+ return enter_pressed;
+ else
+ return value_changed;
+}
+
+bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
+{
+ IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
+ bool ret = InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
+ return ret;
+}
+
+bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
+{
+ bool ret = InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
+ return ret;
+}
+
+// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
+bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ const ImGuiStyle& style = g.Style;
+ const ImVec2 label_size = CalcTextSize(label, NULL, true);
+
+ BeginGroup();
+ PushID(label);
+ const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f;
+ if (step_ptr)
+ PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
+
+ char buf[64];
+ DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
+
+ bool value_changed = false;
+ if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal))
+ extra_flags |= ImGuiInputTextFlags_CharsDecimal;
+ extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
+ if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags))
+ value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
+
+ // Step buttons
+ if (step_ptr)
+ {
+ PopItemWidth();
+ SameLine(0, style.ItemInnerSpacing.x);
+ if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
+ {
+ DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
+ value_changed = true;
+ }
+ SameLine(0, style.ItemInnerSpacing.x);
+ if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
+ {
+ DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
+ value_changed = true;
+ }
+ }
+ PopID();
+
+ if (label_size.x > 0)
+ {
+ SameLine(0, style.ItemInnerSpacing.x);
+ RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
+ ItemSize(label_size, style.FramePadding.y);
+ }
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
+{
+ char display_format[16];
+ if (decimal_precision < 0)
+ strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
+ else
+ ImFormatString(display_format, 16, "%%.%df", decimal_precision);
+ return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
+}
+
+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* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
+ return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags);
+}
+
+bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ bool value_changed = false;
+ BeginGroup();
+ PushID(label);
+ PushMultiItemsWidths(components);
+ for (int i = 0; i < components; i++)
+ {
+ PushID(i);
+ value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+ PopID();
+ PopItemWidth();
+ }
+ PopID();
+
+ window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
+{
+ return InputFloatN(label, v, 2, decimal_precision, extra_flags);
+}
+
+bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
+{
+ return InputFloatN(label, v, 3, decimal_precision, extra_flags);
+}
+
+bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
+{
+ return InputFloatN(label, v, 4, decimal_precision, extra_flags);
+}
+
+bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ bool value_changed = false;
+ BeginGroup();
+ PushID(label);
+ PushMultiItemsWidths(components);
+ for (int i = 0; i < components; i++)
+ {
+ PushID(i);
+ value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
+ SameLine(0, g.Style.ItemInnerSpacing.x);
+ PopID();
+ PopItemWidth();
+ }
+ PopID();
+
+ window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
+ TextUnformatted(label, FindRenderedTextEnd(label));
+ EndGroup();
+
+ return value_changed;
+}
+
+bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
+{
+ return InputIntN(label, v, 2, extra_flags);
+}
+
+bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
+{
+ return InputIntN(label, v, 3, extra_flags);
+}
+
+bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
+{
+ return InputIntN(label, v, 4, extra_flags);
+}
+
+static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
+{
+ const char** items = (const char**)data;
+ if (out_text)
+ *out_text = items[idx];
+ return true;
+}
+
+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;
+}
+
+// Combo box helper allowing to pass an array of strings.
+bool ImGui::Combo(const char* label, int* current_item, const char** 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.
+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;
+}
+
+// Combo box function.
+bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
+{
+ 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));
+ ItemSize(total_bb, style.FramePadding.y);
+ if (!ItemAdd(total_bb, &id))
+ return false;
+
+ const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f);
+ const bool hovered = IsHovered(frame_bb, id);
+ bool popup_open = IsPopupOpen(id);
+ bool popup_opened_now = false;
+
+ const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
+ RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
+ RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
+ RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true);
+
+ if (*current_item >= 0 && *current_item < items_count)
+ {
+ const char* item_text;
+ if (items_getter(data, *current_item, &item_text))
+ RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL);
+ }
+
+ if (label_size.x > 0)
+ RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
+
+ if (hovered)
+ {
+ SetHoveredID(id);
+ if (g.IO.MouseClicked[0])
+ {
+ SetActiveID(0);
+ if (IsPopupOpen(id))
+ {
+ ClosePopup(id);
+ }
+ else
+ {
+ FocusWindow(window);
+ OpenPopup(label);
+ popup_open = popup_opened_now = true;
+ }
+ }
+ }
+
+ bool value_changed = false;
+ if (IsPopupOpen(id))
+ {
+ // Size default to hold ~7 items
+ if (height_in_items < 0)
+ height_in_items = 7;
+
+ float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3);
+ float popup_y1 = frame_bb.Max.y;
+ float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y);
+ if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y))
+ {
+ // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement)
+ popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y);
+ popup_y2 = frame_bb.Min.y;
+ }
+ ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2));
+ SetNextWindowPos(popup_rect.Min);
+ SetNextWindowSize(popup_rect.GetSize());
+ PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
+
+ const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0);
+ if (BeginPopupEx(label, flags))
+ {
+ // Display items
+ Spacing();
+ 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))
+ {
+ SetActiveID(0);
+ value_changed = true;
+ *current_item = i;
+ }
+ if (item_selected && popup_opened_now)
+ SetScrollHere();
+ PopID();
+ }
+ EndPopup();
+ }
+ PopStyleVar();
+ }
+ return value_changed;
+}
+
+// Tip: pass an empty 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.
+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.ColumnsCount > 1)
+ 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(pos, pos + size);
+ ItemSize(bb);
+
+ // 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_with_spacing(pos, pos + size_draw);
+ if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
+ bb_with_spacing.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_with_spacing.Min.x -= spacing_L;
+ bb_with_spacing.Min.y -= spacing_U;
+ bb_with_spacing.Max.x += spacing_R;
+ bb_with_spacing.Max.y += spacing_D;
+ if (!ItemAdd(bb_with_spacing, &id))
+ {
+ if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
+ PushColumnClipRect();
+ return false;
+ }
+
+ ImGuiButtonFlags button_flags = 0;
+ if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
+ if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|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_with_spacing, id, &hovered, &held, button_flags);
+ if (flags & ImGuiSelectableFlags_Disabled)
+ selected = false;
+
+ // Render
+ if (hovered || selected)
+ {
+ const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
+ RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
+ }
+
+ if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
+ {
+ PushColumnClipRect();
+ bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
+ }
+
+ if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
+ RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size);
+ if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
+
+ // Automatically close popups
+ if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
+ 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;
+}
+
+// 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 empty label "##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;
+
+ 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;
+}
+
+bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
+{
+ // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
+ // However we don't add +0.40f 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);
+ float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (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 + GetStyle().ItemSpacing.y;
+ return ListBoxHeader(label, size);
+}
+
+void ImGui::ListBoxFooter()
+{
+ ImGuiWindow* parent_window = GetParentWindow();
+ 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** 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.
+ bool value_changed = false;
+ ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing());
+ 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;
+ }
+ PopID();
+ }
+ ListBoxFooter();
+ return value_changed;
+}
+
+bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ ImVec2 pos = window->DC.CursorPos;
+ ImVec2 label_size = CalcTextSize(label, NULL, true);
+ 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);
+
+ bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), 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.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled));
+
+ 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;
+}
+
+bool ImGui::BeginMainMenuBar()
+{
+ ImGuiContext& g = *GImGui;
+ SetNextWindowPos(ImVec2(0.0f, 0.0f));
+ SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
+ PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
+ PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
+ if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
+ || !BeginMenuBar())
+ {
+ End();
+ PopStyleVar(2);
+ return false;
+ }
+ g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
+ return true;
+}
+
+void ImGui::EndMainMenuBar()
+{
+ EndMenuBar();
+ End();
+ PopStyleVar(2);
+}
+
+bool ImGui::BeginMenuBar()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+ if (!(window->Flags & ImGuiWindowFlags_MenuBar))
+ return false;
+
+ IM_ASSERT(!window->DC.MenuBarAppending);
+ BeginGroup(); // Save position
+ PushID("##menubar");
+ ImRect rect = window->MenuBarRect();
+ PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false);
+ window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y);
+ window->DC.LayoutType = ImGuiLayoutType_Horizontal;
+ window->DC.MenuBarAppending = true;
+ AlignFirstTextHeightToWidgets();
+ return true;
+}
+
+void ImGui::EndMenuBar()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
+ IM_ASSERT(window->DC.MenuBarAppending);
+ PopClipRect();
+ PopID();
+ window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
+ window->DC.GroupStack.back().AdvanceCursor = false;
+ EndGroup();
+ window->DC.LayoutType = ImGuiLayoutType_Vertical;
+ 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);
+ ImGuiWindow* backed_focused_window = g.FocusedWindow;
+
+ 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].ParentMenuSet == window->GetID("##menus"));
+ if (menuset_is_open)
+ g.FocusedWindow = window;
+
+ ImVec2 popup_pos, pos = window->DC.CursorPos;
+ if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
+ {
+ popup_pos = ImVec2(pos.x - window->WindowPadding.x, 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_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
+ PopStyleVar();
+ SameLine();
+ window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
+ }
+ else
+ {
+ 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_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
+ if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
+ RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false);
+ if (!enabled) PopStyleColor();
+ }
+
+ bool hovered = enabled && IsHovered(window->DC.LastItemRect, id);
+ if (menuset_is_open)
+ g.FocusedWindow = backed_focused_window;
+
+ bool want_open = false, want_close = false;
+ if (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)
+ {
+ 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(fabsf(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 = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc);
+ //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? 0x80008000 : 0x80000080); 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);
+ }
+ else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close
+ {
+ want_close = true;
+ want_open = menu_is_open = false;
+ }
+ else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others
+ want_open = true;
+ 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(GImGui->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)
+ {
+ SetNextWindowPos(popup_pos, ImGuiSetCond_Always);
+ ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
+ menu_is_open = BeginPopupEx(label, 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()
+{
+ EndPopup();
+}
+
+// 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.
+bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ ImGuiContext& g = *GImGui;
+ const ImGuiStyle& style = g.Style;
+ const ImGuiID id = window->GetID("#colorbutton");
+ const float square_size = g.FontSize;
+ const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2)));
+ ItemSize(bb, small_height ? 0.0f : style.FramePadding.y);
+ if (!ItemAdd(bb, &id))
+ return false;
+
+ bool hovered, held;
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held);
+ RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding);
+
+ if (hovered)
+ SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8(col.x), IM_F32_TO_INT8(col.y), IM_F32_TO_INT8(col.z), IM_F32_TO_INT8(col.z));
+
+ return pressed;
+}
+
+bool ImGui::ColorEdit3(const char* label, float col[3])
+{
+ float col4[4];
+ col4[0] = col[0];
+ col4[1] = col[1];
+ col4[2] = col[2];
+ col4[3] = 1.0f;
+ const bool value_changed = ColorEdit4(label, col4, false);
+ col[0] = col4[0];
+ col[1] = col4[1];
+ col[2] = col4[2];
+ return value_changed;
+}
+
+// Edit colors components (each component in 0.0f..1.0f range
+// Use CTRL-Click to input value and TAB to go to next item.
+bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha)
+{
+ 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_full = CalcItemWidth();
+ const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f);
+
+ ImGuiColorEditMode edit_mode = window->DC.ColorEditMode;
+ if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton)
+ edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3;
+
+ float f[4] = { col[0], col[1], col[2], col[3] };
+ if (edit_mode == ImGuiColorEditMode_HSV)
+ ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
+
+ int i[4] = { IM_F32_TO_INT8(f[0]), IM_F32_TO_INT8(f[1]), IM_F32_TO_INT8(f[2]), IM_F32_TO_INT8(f[3]) };
+
+ int components = alpha ? 4 : 3;
+ bool value_changed = false;
+
+ BeginGroup();
+ PushID(label);
+
+ const bool hsv = (edit_mode == 1);
+ switch (edit_mode)
+ {
+ case ImGuiColorEditMode_RGB:
+ case ImGuiColorEditMode_HSV:
+ {
+ // RGB/HSV 0..255 Sliders
+ const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x);
+ 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("M:999").x);
+ const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
+ const char* fmt_table[3][4] =
+ {
+ { "%3.0f", "%3.0f", "%3.0f", "%3.0f" },
+ { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" },
+ { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" }
+ };
+ const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[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);
+ value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]);
+ }
+ PopItemWidth();
+ PopItemWidth();
+ }
+ break;
+ case ImGuiColorEditMode_HEX:
+ {
+ // RGB Hexadecimal Input
+ const float w_slider_all = w_full - square_sz;
+ char buf[64];
+ if (alpha)
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]);
+ else
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]);
+ PushItemWidth(w_slider_all - style.ItemInnerSpacing.x);
+ if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
+ {
+ value_changed |= true;
+ char* p = buf;
+ while (*p == '#' || ImCharIsSpace(*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]);
+ }
+ PopItemWidth();
+ }
+ break;
+ }
+
+ SameLine(0, style.ItemInnerSpacing.x);
+
+ const ImVec4 col_display(col[0], col[1], col[2], 1.0f);
+ if (ColorButton(col_display))
+ g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
+
+ // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here
+ if (IsItemHovered())
+ SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8(col[0]), IM_F32_TO_INT8(col[1]), IM_F32_TO_INT8(col[2]), IM_F32_TO_INT8(col[3]));
+
+ if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton)
+ {
+ SameLine(0, style.ItemInnerSpacing.x);
+ const char* button_titles[3] = { "RGB", "HSV", "HEX" };
+ if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups))
+ g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
+ }
+
+ const char* label_display_end = FindRenderedTextEnd(label);
+ if (label != label_display_end)
+ {
+ SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x);
+ TextUnformatted(label, label_display_end);
+ }
+
+ // Convert back
+ for (int n = 0; n < 4; n++)
+ f[n] = i[n] / 255.0f;
+ if (edit_mode == 1)
+ 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();
+
+ return value_changed;
+}
+
+void ImGui::ColorEditMode(ImGuiColorEditMode mode)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.ColorEditMode = mode;
+}
+
+// Horizontal separating line.
+void ImGui::Separator()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ if (window->DC.ColumnsCount > 1)
+ PopClipRect();
+
+ float x1 = window->Pos.x;
+ float x2 = window->Pos.x + window->Size.x;
+ if (!window->DC.GroupStack.empty())
+ x1 += window->DC.IndentX;
+
+ const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y));
+ ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit // FIXME: Height should be 1.0f not 0.0f ?
+ if (!ItemAdd(bb, NULL))
+ {
+ if (window->DC.ColumnsCount > 1)
+ PushColumnClipRect();
+ return;
+ }
+
+ window->DrawList->AddLine(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border));
+
+ ImGuiContext& g = *GImGui;
+ if (g.LogEnabled)
+ LogText(IM_NEWLINE "--------------------------------");
+
+ if (window->DC.ColumnsCount > 1)
+ {
+ PushColumnClipRect();
+ window->DC.ColumnsCellMinY = window->DC.CursorPos.y;
+ }
+}
+
+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, NULL);
+}
+
+bool ImGui::IsRectVisible(const ImVec2& size)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
+}
+
+// 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()
+{
+ 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.BackupIndentX = window->DC.IndentX;
+ group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
+ group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
+ group_data.BackupLogLinePosY = window->DC.LogLinePosY;
+ group_data.AdvanceCursor = true;
+
+ window->DC.IndentX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
+ window->DC.CursorMaxPos = window->DC.CursorPos;
+ window->DC.CurrentLineHeight = 0.0f;
+ window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
+}
+
+void ImGui::EndGroup()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ ImGuiStyle& style = GetStyle();
+
+ 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.y -= style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves.
+ 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.CurrentLineHeight = group_data.BackupCurrentLineHeight;
+ window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
+ window->DC.IndentX = group_data.BackupIndentX;
+ window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
+
+ 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, NULL);
+ }
+
+ window->DC.GroupStack.pop_back();
+
+ //window->DrawList->AddRect(group_bb.Min, group_bb.Max, 0xFFFF00FF); // Debug
+}
+
+// Gets back to previous line and continue with horizontal layout
+// pos_x == 0 : follow on previous item
+// pos_x != 0 : align to specified column
+// spacing_w < 0 : use default spacing if column_x==0, no spacing if column_x!=0
+// spacing_w >= 0 : enforce spacing
+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.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.CurrentLineHeight = window->DC.PrevLineHeight;
+ window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
+}
+
+void ImGui::NewLine()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+ if (window->DC.CurrentLineHeight > 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, GImGui->FontSize));
+}
+
+void ImGui::NextColumn()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+
+ ImGuiContext& g = *GImGui;
+ if (window->DC.ColumnsCount > 1)
+ {
+ PopItemWidth();
+ PopClipRect();
+
+ window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
+ if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount)
+ {
+ // Columns 1+ cancel out IndentX
+ window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x;
+ window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent);
+ }
+ else
+ {
+ window->DC.ColumnsCurrent = 0;
+ window->DC.ColumnsOffsetX = 0.0f;
+ window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY;
+ window->DrawList->ChannelsSetCurrent(0);
+ }
+ window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
+ window->DC.CursorPos.y = window->DC.ColumnsCellMinY;
+ window->DC.CurrentLineHeight = 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.ColumnsCurrent;
+}
+
+int ImGui::GetColumnsCount()
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->DC.ColumnsCount;
+}
+
+static float GetDraggedColumnOffset(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 = ImGui::GetCurrentWindowRead();
+ IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets.
+ IM_ASSERT(g.ActiveId == window->DC.ColumnsSetID + ImGuiID(column_index));
+
+ float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x;
+ x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing);
+
+ return (float)(int)x;
+}
+
+float ImGui::GetColumnOffset(int column_index)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindowRead();
+ if (column_index < 0)
+ column_index = window->DC.ColumnsCurrent;
+
+ if (g.ActiveId)
+ {
+ const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index);
+ if (g.ActiveId == column_id)
+ return GetDraggedColumnOffset(column_index);
+ }
+
+ IM_ASSERT(column_index < window->DC.ColumnsData.Size);
+ const float t = window->DC.ColumnsData[column_index].OffsetNorm;
+ const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
+ return (float)(int)x_offset;
+}
+
+void ImGui::SetColumnOffset(int column_index, float offset)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (column_index < 0)
+ column_index = window->DC.ColumnsCurrent;
+
+ IM_ASSERT(column_index < window->DC.ColumnsData.Size);
+ const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
+ window->DC.ColumnsData[column_index].OffsetNorm = t;
+
+ const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index);
+ window->DC.StateStorage->SetFloat(column_id, t);
+}
+
+float ImGui::GetColumnWidth(int column_index)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ if (column_index < 0)
+ column_index = window->DC.ColumnsCurrent;
+
+ float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index);
+ return w;
+}
+
+static void PushColumnClipRect(int column_index)
+{
+ ImGuiWindow* window = ImGui::GetCurrentWindow();
+ if (column_index < 0)
+ column_index = window->DC.ColumnsCurrent;
+
+ float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f);
+ float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f);
+ ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true);
+}
+
+void ImGui::Columns(int columns_count, const char* id, bool border)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ IM_ASSERT(columns_count >= 1);
+
+ if (window->DC.ColumnsCount != 1)
+ {
+ if (window->DC.ColumnsCurrent != 0)
+ ItemSize(ImVec2(0,0)); // Advance to column 0
+ PopItemWidth();
+ PopClipRect();
+ window->DrawList->ChannelsMerge();
+
+ window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
+ window->DC.CursorPos.y = window->DC.ColumnsCellMaxY;
+ }
+
+ // Draw columns borders and handle resize at the time of "closing" a columns set
+ if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems)
+ {
+ const float y1 = window->DC.ColumnsStartPosY;
+ const float y2 = window->DC.CursorPos.y;
+ for (int i = 1; i < window->DC.ColumnsCount; i++)
+ {
+ float x = window->Pos.x + GetColumnOffset(i);
+ const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(i);
+ const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2));
+ if (IsClippedEx(column_rect, &column_id, false))
+ continue;
+
+ bool hovered, held;
+ ButtonBehavior(column_rect, column_id, &hovered, &held);
+ if (hovered || held)
+ g.MouseCursor = ImGuiMouseCursor_ResizeEW;
+
+ // Draw before resize so our items positioning are in sync with the line being drawn
+ const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column);
+ const float xi = (float)(int)x;
+ window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col);
+
+ if (held)
+ {
+ if (g.ActiveIdIsJustActivated)
+ g.ActiveIdClickOffset.x -= 4; // Store from center of column line
+ x = GetDraggedColumnOffset(i);
+ SetColumnOffset(i, x);
+ }
+ }
+ }
+
+ // 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 + (id ? 0 : columns_count));
+ window->DC.ColumnsSetID = window->GetID(id ? id : "columns");
+ PopID();
+
+ // Set state for first column
+ window->DC.ColumnsCurrent = 0;
+ window->DC.ColumnsCount = columns_count;
+ window->DC.ColumnsShowBorders = border;
+
+ const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x;
+ window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range
+ window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
+ window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
+ window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y;
+ window->DC.ColumnsOffsetX = 0.0f;
+ window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
+
+ if (window->DC.ColumnsCount != 1)
+ {
+ // Cache column offsets
+ window->DC.ColumnsData.resize(columns_count + 1);
+ for (int column_index = 0; column_index < columns_count + 1; column_index++)
+ {
+ const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index);
+ KeepAliveID(column_id);
+ const float default_t = column_index / (float)window->DC.ColumnsCount;
+ const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store an union into the map?)
+ window->DC.ColumnsData[column_index].OffsetNorm = t;
+ }
+ window->DrawList->ChannelsSplit(window->DC.ColumnsCount);
+ PushColumnClipRect();
+ PushItemWidth(GetColumnWidth() * 0.65f);
+ }
+ else
+ {
+ window->DC.ColumnsData.resize(0);
+ }
+}
+
+void ImGui::Indent(float indent_w)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
+ window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
+}
+
+void ImGui::Unindent(float indent_w)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
+ window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
+}
+
+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()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ Unindent();
+ window->DC.TreeDepth--;
+ PopID();
+}
+
+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);
+ }
+}
+
+// FIXME: May want to remove those helpers?
+void ImGui::ValueColor(const char* prefix, const ImVec4& v)
+{
+ Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w);
+ SameLine();
+ ColorButton(v, true);
+}
+
+void ImGui::ValueColor(const char* prefix, unsigned int v)
+{
+ Text("%s: %08X", prefix, v);
+ SameLine();
+
+ ImVec4 col;
+ col.x = (float)((v >> 0) & 0xFF) / 255.0f;
+ col.y = (float)((v >> 8) & 0xFF) / 255.0f;
+ col.z = (float)((v >> 16) & 0xFF) / 255.0f;
+ col.w = (float)((v >> 24) & 0xFF) / 255.0f;
+ ColorButton(col, true);
+}
+
+//-----------------------------------------------------------------------------
+// PLATFORM DEPENDANT HELPERS
+//-----------------------------------------------------------------------------
+
+#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS))
+#undef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+
+// Win32 API clipboard implementation
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS)
+
+#ifdef _MSC_VER
+#pragma comment(lib, "user32")
+#endif
+
+static const char* GetClipboardTextFn_DefaultImpl()
+{
+ static char* buf_local = NULL;
+ if (buf_local)
+ {
+ ImGui::MemFree(buf_local);
+ buf_local = NULL;
+ }
+ if (!OpenClipboard(NULL))
+ return NULL;
+ HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
+ if (wbuf_handle == NULL)
+ return NULL;
+ if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
+ {
+ int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
+ buf_local = (char*)ImGui::MemAlloc(buf_len * sizeof(char));
+ ImTextStrToUtf8(buf_local, buf_len, wbuf_global, NULL);
+ }
+ GlobalUnlock(wbuf_handle);
+ CloseClipboard();
+ return buf_local;
+}
+
+static void SetClipboardTextFn_DefaultImpl(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)
+ return;
+ ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
+ ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
+ GlobalUnlock(wbuf_handle);
+ EmptyClipboard();
+ SetClipboardData(CF_UNICODETEXT, wbuf_handle);
+ CloseClipboard();
+}
+
+#else
+
+// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
+static const char* GetClipboardTextFn_DefaultImpl()
+{
+ return GImGui->PrivateClipboard;
+}
+
+// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
+static void SetClipboardTextFn_DefaultImpl(const char* text)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.PrivateClipboard)
+ {
+ ImGui::MemFree(g.PrivateClipboard);
+ g.PrivateClipboard = NULL;
+ }
+ const char* text_end = text + strlen(text);
+ g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1);
+ memcpy(g.PrivateClipboard, 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(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)
+
+#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);
+ }
+}
+
+#else
+
+static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
+
+#endif
+
+//-----------------------------------------------------------------------------
+// HELP
+//-----------------------------------------------------------------------------
+
+void ImGui::ShowMetricsWindow(bool* p_open)
+{
+ if (ImGui::Begin("ImGui Metrics", p_open))
+ {
+ ImGui::Text("ImGui %s", ImGui::GetVersion());
+ ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
+ ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
+ ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
+ static bool show_clip_rects = true;
+ ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects);
+ ImGui::Separator();
+
+ struct Funcs
+ {
+ static void NodeDrawList(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;
+ }
+ if (!node_open)
+ return;
+
+ ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
+ overlay_draw_list->PushClipRectFullScreen();
+ 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)
+ {
+ 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 = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.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_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;
+ 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], *buf_p = 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 += sprintf(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())
+ overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle
+ }
+ ImGui::TreePop();
+ }
+ overlay_draw_list->PopClipRect();
+ 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;
+ NodeDrawList(window->DrawList, "DrawList");
+ if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
+ if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
+ ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
+ ImGui::TreePop();
+ }
+ };
+
+ ImGuiContext& g = *GImGui; // Access private state
+ Funcs::NodeWindows(g.Windows, "Windows");
+ if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
+ {
+ for (int i = 0; i < g.RenderDrawLists[0].Size; i++)
+ Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Popups", "Open Popups Stack (%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("Basic state"))
+ {
+ ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL");
+ 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", g.HoveredId, g.HoveredIdPreviousFrame); // 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", g.ActiveId, g.ActiveIdPreviousFrame);
+ ImGui::TreePop();
+ }
+ }
+ 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/NvCloth/samples/external/imgui/1.49/imgui.h b/NvCloth/samples/external/imgui/1.49/imgui.h
new file mode 100644
index 0000000..50971f9
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/imgui.h
@@ -0,0 +1,1402 @@
+// dear imgui, v1.49
+// (headers)
+
+// See imgui.cpp file for documentation.
+// See ImGui::ShowTestWindow() 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
+
+#pragma once
+
+#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H)
+#include "imconfig.h" // User-editable configuration file
+#endif
+#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
+
+#define IMGUI_VERSION "1.49"
+
+// Define attributes of all API symbols declarations, e.g. for DLL under Windows.
+#ifndef IMGUI_API
+#define IMGUI_API
+#endif
+
+// Define assertion handler.
+#ifndef IM_ASSERT
+#include <assert.h>
+#define IM_ASSERT(_EXPR) assert(_EXPR)
+#endif
+
+// Some compilers support applying printf-style warnings to user functions.
+#if defined(__clang__) || defined(__GNUC__)
+#define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1))))
+#else
+#define IM_PRINTFARGS(FMT)
+#endif
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wold-style-cast"
+#endif
+
+// Forward declarations
+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)
+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 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
+struct ImGuiIO; // Main configuration and I/O between your application and ImGui
+struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro
+struct ImGuiStorage; // Simple custom key value storage
+struct ImGuiStyle; // Runtime data for styling/colors
+struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
+struct ImGuiTextBuffer; // Text buffer for logging/accumulating text
+struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use)
+struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use)
+struct ImGuiListClipper; // Helper to manually clip large list of items
+struct ImGuiContext; // ImGui context (opaque)
+
+// Enumerations (declared as int for compatibility and to not pollute the top of this file)
+typedef unsigned int ImU32;
+typedef unsigned short ImWchar; // character for keyboard input/display
+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)
+typedef ImU32 ImGuiID; // unique ID used by widgets (typically hashed from a stack of string)
+typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_
+typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_
+typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_
+typedef int ImGuiAlign; // alignment // enum ImGuiAlign_
+typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_
+typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_
+typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_
+typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_
+typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_
+typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_
+typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_
+typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data);
+typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data);
+
+// Others helpers at bottom of the file:
+// class ImVector<> // Lightweight std::vector like class.
+// IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times)
+
+struct ImVec2
+{
+ float x, y;
+ ImVec2() { x = y = 0.0f; }
+ ImVec2(float _x, float _y) { x = _x; y = _y; }
+#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2.
+ IM_VEC2_CLASS_EXTRA
+#endif
+};
+
+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 // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4.
+ IM_VEC4_CLASS_EXTRA
+#endif
+};
+
+// ImGui end-user API
+// In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types)
+namespace ImGui
+{
+ // Main
+ IMGUI_API ImGuiIO& GetIO();
+ IMGUI_API ImGuiStyle& GetStyle();
+ IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
+ IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render().
+ IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set.
+ IMGUI_API void Shutdown();
+ IMGUI_API void ShowUserGuide(); // help block
+ IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
+ IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features
+ IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui
+
+ // Window
+ IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false).
+ IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually.
+ IMGUI_API void End(); // finish appending to current window, pop it off the window stack.
+ IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400).
+ IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // "
+ IMGUI_API void EndChild();
+ 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 ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw 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();
+ IMGUI_API float GetWindowHeight();
+ IMGUI_API bool IsWindowCollapsed();
+ IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows
+
+ IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin()
+ IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin()
+ IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond 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, ImGuiSizeConstraintCallback 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). set axis to 0.0f to leave it automatic. call before Begin()
+ IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin()
+ IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond 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 SetWindowPos(const ImVec2& pos, ImGuiSetCond 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, ImGuiSetCond 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, ImGuiSetCond 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 SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position.
+ IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond 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, ImGuiSetCond 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.
+
+ 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 SetScrollHere(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.
+ 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.
+ 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 negative 'offset' to access previous widgets.
+ IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
+ IMGUI_API ImGuiStorage* GetStateStorage();
+
+ // 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, 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 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
+
+ // 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 v); // 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 (uses io.KeyRepeatDelay/io.KeyRepeatRate for now). 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(); // horizontal line
+ 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& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
+ IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets
+ IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize()
+ IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y
+ IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y
+
+ // Columns
+ // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking.
+ IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1).
+ IMGUI_API void NextColumn(); // next column
+ IMGUI_API int GetColumnIndex(); // get current column index
+ 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 usually 0.0f and not resizable unless you call this
+ 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 float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset())
+ IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns())
+
+ // ID scopes
+ // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them.
+ // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details.
+ 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). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed
+ IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
+ IMGUI_API ImGuiID GetID(const void* ptr_id);
+
+ // Widgets
+ IMGUI_API void Text(const char* fmt, ...) IM_PRINTFARGS(1);
+ IMGUI_API void TextV(const char* fmt, va_list args);
+ IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_PRINTFARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
+ IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args);
+ IMGUI_API void TextDisabled(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
+ IMGUI_API void TextDisabledV(const char* fmt, va_list args);
+ IMGUI_API void TextWrapped(const char* fmt, ...) IM_PRINTFARGS(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);
+ IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text
+ IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(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);
+ 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
+ IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text()
+ IMGUI_API void BulletTextV(const char* fmt, va_list args);
+ 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)
+ IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size);
+ 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);
+ IMGUI_API bool RadioButton(const char* label, int* v, int v_button);
+ IMGUI_API bool Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1);
+ IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\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 height_in_items = -1);
+ IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true);
+ IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x
+ IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // "
+ IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced.
+ 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));
+ IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL);
+
+ // 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, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
+ 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* display_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* display_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* display_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* display_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* display_format = "%.3f", const char* display_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* display_format = "%.0f"); // 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* display_format = "%.0f");
+ 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* display_format = "%.0f");
+ 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* display_format = "%.0f");
+ 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* display_format = "%.0f", const char* display_format_max = NULL);
+
+ // Widgets: Input with Keyboard
+ IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback 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, ImGuiTextEditCallback callback = NULL, void* user_data = NULL);
+ IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0);
+ IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0);
+ IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0);
+ IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, 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);
+
+ // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds)
+ IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders
+ IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f);
+ IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f);
+ IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_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);
+ IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f");
+ IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format = "%.0f");
+ IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format = "%.0f");
+ IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format = "%.0f");
+ IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_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* display_format = "%.0f");
+
+ // Widgets: Trees
+ IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop().
+ IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // 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_PRINTFARGS(2); // "
+ IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // "
+ IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // "
+ IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
+ IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3);
+ IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3);
+ IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args);
+ IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args);
+ IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose
+ 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 preceeding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
+ IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond 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: Selectable / Lists
+ IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // 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));
+ IMGUI_API bool ListBox(const char* label, int* current_item, const char** 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. make sure to 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
+
+ // 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);
+ IMGUI_API void ValueColor(const char* prefix, const ImVec4& v);
+ IMGUI_API void ValueColor(const char* prefix, unsigned int v);
+
+ // Tooltips
+ IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins
+ IMGUI_API void SetTooltipV(const char* fmt, va_list args);
+ IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text
+ IMGUI_API void EndTooltip();
+
+ // Menus
+ IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true!
+ IMGUI_API void EndMainMenuBar();
+ IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true!
+ IMGUI_API void EndMenuBar();
+ 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();
+ 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
+
+ // Popups
+ IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. 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).
+ IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true!
+ IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (can't close them by clicking outside)
+ IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp!
+ IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // 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 (no window).
+ IMGUI_API void EndPopup();
+ IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup.
+
+ // Logging: all text output from interface is redirected 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_PRINTFARGS(1); // pass text data straight to log (without being displayed)
+
+ // 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();
+
+ // Utilities
+ IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse?
+ IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this
+ IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false)
+ IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on)
+ IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.)
+ IMGUI_API bool IsAnyItemHovered();
+ IMGUI_API bool IsAnyItemActive();
+ IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space
+ IMGUI_API ImVec2 GetItemRectMax(); // "
+ IMGUI_API ImVec2 GetItemRectSize(); // "
+ 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.
+ IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others)
+ IMGUI_API bool IsWindowFocused(); // is current window focused
+ IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self)
+ IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused
+ IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup)
+ IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle of given size starting from cursor pos is visible (not clipped). to perform coarse clipping on user's side (as an optimization)
+ IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window
+ IMGUI_API float GetTime();
+ IMGUI_API int GetFrameCount();
+ IMGUI_API const char* GetStyleColName(ImGuiCol idx);
+ IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items
+ 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 extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
+ IMGUI_API void EndChildFrame();
+
+ 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
+ IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
+ IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[] array, imgui doesn't know the semantic of each entry, uses your own indices!
+ IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // uses user's key indices as stored in the keys_down[] array. if repeat=true. uses io.KeyRepeatDelay / KeyRepeatRate
+ IMGUI_API bool IsKeyReleased(int key_index); // "
+ IMGUI_API bool IsMouseDown(int button); // is mouse button held
+ IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down)
+ 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 IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup)
+ IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window
+ 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. disregarding of consideration of focus/window ordering/blocked by a popup.
+ 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 ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
+ IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning 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 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 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 handle).
+
+ // Helpers functions to access functions pointers in ImGui::GetIO()
+ IMGUI_API void* MemAlloc(size_t sz);
+ IMGUI_API void MemFree(void* ptr);
+ IMGUI_API const char* GetClipboardText();
+ IMGUI_API void SetClipboardText(const char* text);
+
+ // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default.
+ // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context.
+ IMGUI_API const char* GetVersion();
+ IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL);
+ IMGUI_API void DestroyContext(ImGuiContext* ctx);
+ IMGUI_API ImGuiContext* GetCurrentContext();
+ IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
+
+ // Obsolete (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+
+ static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+
+ static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+
+ static inline void OpenNextNode(bool open) { ImGui::SetNextTreeNodeOpen(open, 0); } // OBSOLETE 1.34+
+ static inline bool GetWindowIsFocused() { return ImGui::IsWindowFocused(); } // OBSOLETE 1.36+
+ static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+
+ static inline ImVec2 GetItemBoxMin() { return GetItemRectMin(); } // OBSOLETE 1.36+
+ static inline ImVec2 GetItemBoxMax() { return GetItemRectMax(); } // OBSOLETE 1.36+
+ static inline bool IsClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.38+
+ static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+
+ static inline bool IsMouseHoveringBox(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(rect_min, rect_max); } // OBSOLETE 1.36+
+ static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+
+#endif
+
+} // namespace ImGui
+
+// Flags for ImGui::Begin()
+enum ImGuiWindowFlags_
+{
+ // Default: 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
+ 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_ShowBorders = 1 << 7, // Show borders around windows and items
+ ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file
+ ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs
+ 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)
+ // [Internal]
+ ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild()
+ ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild()
+ ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild()
+ ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox()
+ ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip()
+ ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup()
+ ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal()
+ ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu()
+};
+
+// Flags for ImGui::InputText()
+enum ImGuiInputTextFlags_
+{
+ // Default: 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, // Call user function on pressing TAB (for completion handling)
+ ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling)
+ ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer.
+ ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character.
+ ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field
+ ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines 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 '*'
+ // [Internal]
+ ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline()
+};
+
+// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*()
+enum ImGuiTreeNodeFlags_
+{
+ ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected
+ ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader)
+ ImGuiTreeNodeFlags_AllowOverlapMode = 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_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed
+ //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
+ ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog
+};
+
+// Flags for ImGui::Selectable()
+enum ImGuiSelectableFlags_
+{
+ // Default: 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
+};
+
+// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
+enum ImGuiKey_
+{
+ ImGuiKey_Tab, // for tabbing through fields
+ ImGuiKey_LeftArrow, // for text edit
+ ImGuiKey_RightArrow,// for text edit
+ ImGuiKey_UpArrow, // for text edit
+ ImGuiKey_DownArrow, // for text edit
+ ImGuiKey_PageUp,
+ ImGuiKey_PageDown,
+ ImGuiKey_Home, // for text edit
+ ImGuiKey_End, // for text edit
+ ImGuiKey_Delete, // for text edit
+ ImGuiKey_Backspace, // for text edit
+ ImGuiKey_Enter, // for text edit
+ ImGuiKey_Escape, // for text edit
+ 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
+};
+
+// Enumeration for PushStyleColor() / PopStyleColor()
+enum ImGuiCol_
+{
+ ImGuiCol_Text,
+ ImGuiCol_TextDisabled,
+ ImGuiCol_WindowBg, // Background of normal windows
+ ImGuiCol_ChildWindowBg, // 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_TitleBgCollapsed,
+ ImGuiCol_TitleBgActive,
+ ImGuiCol_MenuBarBg,
+ ImGuiCol_ScrollbarBg,
+ ImGuiCol_ScrollbarGrab,
+ ImGuiCol_ScrollbarGrabHovered,
+ ImGuiCol_ScrollbarGrabActive,
+ ImGuiCol_ComboBg,
+ ImGuiCol_CheckMark,
+ ImGuiCol_SliderGrab,
+ ImGuiCol_SliderGrabActive,
+ ImGuiCol_Button,
+ ImGuiCol_ButtonHovered,
+ ImGuiCol_ButtonActive,
+ ImGuiCol_Header,
+ ImGuiCol_HeaderHovered,
+ ImGuiCol_HeaderActive,
+ ImGuiCol_Column,
+ ImGuiCol_ColumnHovered,
+ ImGuiCol_ColumnActive,
+ ImGuiCol_ResizeGrip,
+ ImGuiCol_ResizeGripHovered,
+ ImGuiCol_ResizeGripActive,
+ ImGuiCol_CloseButton,
+ ImGuiCol_CloseButtonHovered,
+ ImGuiCol_CloseButtonActive,
+ ImGuiCol_PlotLines,
+ ImGuiCol_PlotLinesHovered,
+ ImGuiCol_PlotHistogram,
+ ImGuiCol_PlotHistogramHovered,
+ ImGuiCol_TextSelectedBg,
+ ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active
+ ImGuiCol_COUNT
+};
+
+// Enumeration for PushStyleVar() / PopStyleVar()
+// NB: the enum only refers to fields of ImGuiStyle() which makes sense to be pushed/poped in UI code. Feel free to add others.
+enum ImGuiStyleVar_
+{
+ ImGuiStyleVar_Alpha, // float
+ ImGuiStyleVar_WindowPadding, // ImVec2
+ ImGuiStyleVar_WindowRounding, // float
+ ImGuiStyleVar_WindowMinSize, // ImVec2
+ ImGuiStyleVar_ChildWindowRounding, // float
+ ImGuiStyleVar_FramePadding, // ImVec2
+ ImGuiStyleVar_FrameRounding, // float
+ ImGuiStyleVar_ItemSpacing, // ImVec2
+ ImGuiStyleVar_ItemInnerSpacing, // ImVec2
+ ImGuiStyleVar_IndentSpacing, // float
+ ImGuiStyleVar_GrabMinSize // float
+};
+
+enum ImGuiAlign_
+{
+ ImGuiAlign_Left = 1 << 0,
+ ImGuiAlign_Center = 1 << 1,
+ ImGuiAlign_Right = 1 << 2,
+ ImGuiAlign_Top = 1 << 3,
+ ImGuiAlign_VCenter = 1 << 4,
+ ImGuiAlign_Default = ImGuiAlign_Left | ImGuiAlign_Top
+};
+
+// Enumeration for ColorEditMode()
+// FIXME-OBSOLETE: Will be replaced by future color/picker api
+enum ImGuiColorEditMode_
+{
+ ImGuiColorEditMode_UserSelect = -2,
+ ImGuiColorEditMode_UserSelectShowButton = -1,
+ ImGuiColorEditMode_RGB = 0,
+ ImGuiColorEditMode_HSV = 1,
+ ImGuiColorEditMode_HEX = 2
+};
+
+// Enumeration for GetMouseCursor()
+enum ImGuiMouseCursor_
+{
+ ImGuiMouseCursor_Arrow = 0,
+ ImGuiMouseCursor_TextInput, // When hovering over InputText, etc.
+ ImGuiMouseCursor_Move, // Unused
+ ImGuiMouseCursor_ResizeNS, // Unused
+ ImGuiMouseCursor_ResizeEW, // When hovering over a column
+ ImGuiMouseCursor_ResizeNESW, // Unused
+ ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window
+ ImGuiMouseCursor_Count_
+};
+
+// Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions
+// All those functions treat 0 as a shortcut to ImGuiSetCond_Always
+enum ImGuiSetCond_
+{
+ ImGuiSetCond_Always = 1 << 0, // Set the variable
+ ImGuiSetCond_Once = 1 << 1, // Only set the variable on the first call per runtime session
+ ImGuiSetCond_FirstUseEver = 1 << 2, // Only set the variable if the window doesn't exist in the .ini file
+ ImGuiSetCond_Appearing = 1 << 3 // Only set the variable if the window is appearing after being inactive (or the first time)
+};
+
+struct ImGuiStyle
+{
+ float Alpha; // Global alpha applies to everything in ImGui
+ ImVec2 WindowPadding; // Padding within a window
+ ImVec2 WindowMinSize; // Minimum window size
+ float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
+ ImGuiAlign WindowTitleAlign; // Alignment for title bar text
+ float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows
+ 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).
+ 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 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
+ ImVec2 DisplaySafeAreaPadding; // 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.
+ bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.
+ bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
+ float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
+ ImVec4 Colors[ImGuiCol_COUNT];
+
+ IMGUI_API ImGuiStyle();
+};
+
+// This is where your app communicate with ImGui. Access via ImGui::GetIO().
+// Read 'Programmer guide' section in .cpp file for general usage.
+struct ImGuiIO
+{
+ //------------------------------------------------------------------
+ // Settings (fill once) // Default value:
+ //------------------------------------------------------------------
+
+ ImVec2 DisplaySize; // <unset> // 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 // Maximum time between saving positions/sizes to .ini file, in seconds.
+ const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving.
+ 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
+ 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.020f // 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.
+ 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) // 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) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize
+
+ // Advanced/subtle behaviors
+ bool WordMovementUsesAltKey; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl
+ bool ShortcutsUseSuperKey; // = defined(__APPLE__) // OS X style: Shortcuts using Cmd/Super instead of Ctrl
+ bool DoubleClickSelectsWord; // = defined(__APPLE__) // OS X style: Double click selects by word instead of selecting whole text
+ bool MultiSelectUsesSuperKey; // = defined(__APPLE__) // OS X style: Multi-selection in lists uses Cmd/Super instead of Ctrl [unused yet]
+
+ //------------------------------------------------------------------
+ // User Functions
+ //------------------------------------------------------------------
+
+ // Rendering function, will be called in Render().
+ // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer.
+ // See example applications if you are unsure of how to implement this.
+ void (*RenderDrawListsFn)(ImDrawData* data);
+
+ // 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 (*SetClipboardTextFn)(const char* text);
+
+ // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer.
+ // (default to posix malloc/free)
+ void* (*MemAllocFn)(size_t sz);
+ void (*MemFreeFn)(void* ptr);
+
+ // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in 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.
+
+ //------------------------------------------------------------------
+ // Input - Fill before calling NewFrame()
+ //------------------------------------------------------------------
+
+ ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
+ bool MouseDown[5]; // Mouse buttons: left, right, 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: 1 unit scrolls about 5 lines text.
+ bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor).
+ 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 (in whatever storage order you naturally have access to keyboard data)
+ ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper.
+
+ // Functions
+ IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[]
+ IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Helper to add new characters into InputCharacters[] from an UTF-8 string
+ inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Helper to clear the text input buffer
+
+ //------------------------------------------------------------------
+ // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application
+ //------------------------------------------------------------------
+
+ bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input)
+ bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input)
+ bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array.
+ float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames
+ int MetricsAllocs; // Number of active memory allocations
+ int MetricsRenderVertices; // Vertices output during last call to Render()
+ int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
+ int MetricsActiveWindows; // Number of visible windows (exclude child windows)
+
+ //------------------------------------------------------------------
+ // [Internal] ImGui will maintain those fields for you
+ //------------------------------------------------------------------
+
+ ImVec2 MousePosPrev; // Previous mouse position
+ ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative to allow mouse enabling/disabling.
+ bool MouseClicked[5]; // Mouse button went from !Down to Down
+ ImVec2 MouseClickedPos[5]; // Position at time of clicking
+ float MouseClickedTime[5]; // Time of last click (used to figure out double-click)
+ 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
+ float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click 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
+
+ IMGUI_API ImGuiIO();
+};
+
+//-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+// 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).
+// Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight 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;
+
+ ImVector() { Size = Capacity = 0; Data = NULL; }
+ ~ImVector() { if (Data) ImGui::MemFree(Data); }
+
+ 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<T>& 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 new_size) { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > new_size ? new_capacity : new_size; }
+
+ inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
+ inline void reserve(int new_capacity)
+ {
+ if (new_capacity <= Capacity) return;
+ T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type));
+ memcpy(new_data, Data, (size_t)Size * sizeof(value_type));
+ ImGui::MemFree(Data);
+ Data = new_data;
+ Capacity = new_capacity;
+ }
+
+ inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; }
+ inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
+
+ 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 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(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; }
+};
+
+// 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:
+// IMGUI_ONCE_UPON_A_FRAME
+// {
+// // code block will be executed one per frame
+// }
+// Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces.
+#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__)
+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: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
+struct ImGuiTextFilter
+{
+ 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; }
+ char front() const { return *b; }
+ static bool is_blank(char c) { return c == ' ' || c == '\t'; }
+ void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; }
+ IMGUI_API void split(char separator, ImVector<TextRange>& out);
+ };
+
+ char InputBuf[256];
+ ImVector<TextRange> Filters;
+ int CountGrep;
+
+ ImGuiTextFilter(const char* default_filter = "");
+ ~ImGuiTextFilter() {}
+ void Clear() { InputBuf[0] = 0; Build(); }
+ bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build
+ bool PassFilter(const char* text, const char* text_end = NULL) const;
+ bool IsActive() const { return !Filters.empty(); }
+ IMGUI_API void Build();
+};
+
+// Helper: Text buffer for logging/accumulating text
+struct ImGuiTextBuffer
+{
+ ImVector<char> Buf;
+
+ ImGuiTextBuffer() { Buf.push_back(0); }
+ inline char operator[](int i) { return Buf.Data[i]; }
+ const char* begin() const { return &Buf.front(); }
+ const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator
+ int size() const { return Buf.Size - 1; }
+ bool empty() { return Buf.Size <= 1; }
+ void clear() { Buf.clear(); Buf.push_back(0); }
+ const char* c_str() const { return Buf.Data; }
+ IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2);
+ IMGUI_API void appendv(const char* fmt, va_list args);
+};
+
+// Helper: Simple Key->value storage
+// - Store collapse state for a tree (Int 0/1)
+// - Store color edit options (Int using values in ImGuiColorEditMode enum).
+// - Custom user storage for temporary values.
+// Typically you don't have to worry about this since a storage is held within each Window.
+// Declare your own storage if:
+// - 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.
+// 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.
+ IMGUI_API void 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:
+ // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar;
+ // - You can also use this to quickly create temporary editable values during a session of using Edit&Continue, without restarting your application.
+ 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);
+};
+
+// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered.
+struct ImGuiTextEditCallbackData
+{
+ ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only
+ ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only
+ void* UserData; // What user passed to InputText() // Read-only
+ bool ReadOnly; // Read-only mode // Read-only
+
+ // CharFilter event:
+ ImWchar EventChar; // Character input // Read-write (replace character or set to zero)
+
+ // Completion,History,Always events:
+ // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true.
+ ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only
+ char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer)
+ int BufTextLen; // Current text length in bytes // Read-write
+ int BufSize; // Maximum text length in bytes // Read-only
+ bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write
+ int CursorPos; // // Read-write
+ int SelectionStart; // // Read-write (== to SelectionEnd when no selection)
+ int SelectionEnd; // // Read-write
+
+ // NB: Helper functions for text manipulation. Calling those function loses selection.
+ void DeleteChars(int pos, int bytes_count);
+ 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 ImGuiSizeConstraintCallbackData
+{
+ 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.
+};
+
+// ImColor() helper to 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.
+// 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.
+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&0xFF) * sc; Value.y = (float)((rgba>>8)&0xFF) * sc; Value.z = (float)((rgba>>16)&0xFF) * sc; Value.w = (float)(rgba >> 24) * 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; }
+
+ 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); }
+};
+
+// 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 GetItemsLineHeightWithSpacing().
+ // 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.
+};
+
+//-----------------------------------------------------------------------------
+// Draw List
+// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList.
+//-----------------------------------------------------------------------------
+
+// Helpers macros to generate 32-bits encoded colors
+#define IM_COL32(R,G,B,A) (((ImU32)(A)<<24) | ((ImU32)(B)<<16) | ((ImU32)(G)<<8) | ((ImU32)(R)))
+#define IM_COL32_WHITE (0xFFFFFFFF)
+#define IM_COL32_BLACK (0xFF000000)
+#define IM_COL32_BLACK_TRANS (0x00000000) // Transparent black
+
+// 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, 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)
+ 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 = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; }
+};
+
+// Vertex index (override with '#define ImDrawIdx unsigned int' inside 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)
+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;
+};
+
+// 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.
+// At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future.
+// If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives.
+// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
+// All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions).
+struct ImDrawList
+{
+ // This is what you have to render
+ ImVector<ImDrawCmd> CmdBuffer; // Commands. Typically 1 command = 1 gpu draw call.
+ ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
+ ImVector<ImDrawVert> VtxBuffer; // Vertex buffer.
+
+ // [Internal, used while building lists]
+ const char* _OwnerName; // Pointer to owner window's name (if any) 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)
+
+ ImDrawList() { _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(const ImTextureID& texture_id);
+ IMGUI_API void PopTextureID();
+
+ // 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 = 0x0F, float thickness = 1.0f); // a: upper-left, b: lower-right
+ IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); // 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& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), ImU32 col = 0xFFFFFFFF);
+ IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased);
+ IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased);
+ 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 PathFill() 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 PathFill(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); }
+ inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); 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 = 0x0F);
+
+ // 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
+
+ // 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
+struct ImDrawData
+{
+ bool Valid; // Only valid after Render() is called and before the next NewFrame() is called.
+ ImDrawList** CmdLists;
+ int CmdListsCount;
+ int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size
+ int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size
+
+ // Functions
+ ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; }
+ IMGUI_API void DeIndexAllBuffers(); // 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!
+ 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.
+};
+
+struct ImFontConfig
+{
+ void* FontData; // // TTF data
+ int FontDataSize; // // TTF data size
+ bool FontDataOwnedByAtlas; // true // TTF data ownership taken by the container ImFontAtlas (will delete memory itself). Set to true
+ int FontNo; // 0 // Index of font within TTF file
+ float SizePixels; // // Size in pixels for rasterizer
+ int OversampleH, OversampleV; // 3, 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 character to pixel boundary (if enabled, set OversampleH/V to 1)
+ ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs
+ const ImWchar* GlyphRanges; // // 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.
+ bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs).
+ bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline
+
+ // [Internal]
+ char Name[32]; // Name (strictly for debugging)
+ ImFont* DstFont;
+
+ IMGUI_API ImFontConfig();
+};
+
+// Load and rasterize multiple TTF fonts into a same texture.
+// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering.
+// We also add custom graphic data into the texture that serves for ImGui.
+// 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you.
+// 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
+// 3. Upload the pixels data into a texture within your graphics system.
+// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture.
+// 5. Call ClearTexData() to free textures memory on the heap.
+// NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data.
+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* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build()
+ IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data' still owned by caller. Compress with binary_to_compressed_c.cpp
+ IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter
+ IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory.
+ IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges)
+ IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates)
+ IMGUI_API void Clear(); // Clear all
+
+ // Retrieve texture data
+ // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID()
+ // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images)
+ // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted.
+ // Pitch = Width * BytesPerPixels
+ 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(void* id) { TexID = id; }
+
+ // 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. See FAQ for details.
+ 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* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs
+ IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
+
+ // Members
+ // (Access texture data via GetTexData*() calls which will setup a default font for you.)
+ void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering.
+ 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().
+ 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.
+ 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.
+
+ // Private
+ ImVector<ImFontConfig> ConfigData; // Internal data
+ IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions.
+ IMGUI_API void RenderCustomTexData(int pass, void* rects);
+};
+
+// Font runtime data and rendering
+// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
+struct ImFont
+{
+ struct Glyph
+ {
+ ImWchar Codepoint;
+ float XAdvance;
+ float X0, Y0, X1, Y1;
+ float U0, V0, U1, V1; // Texture coordinates
+ };
+
+ // 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,1.f) // Offset font rendering by xx pixels
+ ImVector<Glyph> Glyphs; // // All glyphs.
+ ImVector<float> IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
+ ImVector<short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point.
+ const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar)
+ float FallbackXAdvance; // == FallbackGlyph->XAdvance
+ 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]
+
+ // Methods
+ IMGUI_API ImFont();
+ IMGUI_API ~ImFont();
+ IMGUI_API void Clear();
+ IMGUI_API void BuildLookupTable();
+ IMGUI_API const Glyph* FindGlyph(ImWchar c) const;
+ IMGUI_API void SetFallbackChar(ImWchar c);
+ float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; }
+ bool IsLoaded() const { return ContainerAtlas != NULL; }
+
+ // '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, unsigned short 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;
+
+ // Private
+ IMGUI_API void GrowIndex(int new_size);
+ 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.
+};
+
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+
+//---- Include imgui_user.h at the end of imgui.h
+//---- So you can include code that extends ImGui using any of the types declared above.
+//---- (also convenient for user to only explicitly include vanilla imgui.h)
+#ifdef IMGUI_INCLUDE_IMGUI_USER_H
+#include "imgui_user.h"
+#endif
diff --git a/NvCloth/samples/external/imgui/1.49/imgui_demo.cpp b/NvCloth/samples/external/imgui/1.49/imgui_demo.cpp
new file mode 100644
index 0000000..6ec0018
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/imgui_demo.cpp
@@ -0,0 +1,2538 @@
+// dear imgui, v1.49
+// (demo code)
+
+// Don't remove this file from your project! It is useful reference code that you can execute.
+// You can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui.
+// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow().
+
+#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "imgui.h"
+#include <ctype.h> // toupper, isprint
+#include <math.h> // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf
+#include <stdio.h> // vsnprintf, sscanf, printf
+#include <stdlib.h> // NULL, malloc, free, qsort, atoi
+#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
+#include <stddef.h> // intptr_t
+#else
+#include <stdint.h> // intptr_t
+#endif
+
+#ifdef _MSC_VER
+#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
+#define snprintf _snprintf
+#endif
+#ifdef __clang__
+#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code)
+#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
+#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal
+#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 "-Wreserved-id-macro" // warning : macro name is a reserved identifier //
+#elif defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
+#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure)
+#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
+#endif
+
+// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
+#ifdef _WIN32
+#define IM_NEWLINE "\r\n"
+#else
+#define IM_NEWLINE "\n"
+#endif
+
+#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
+#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B))
+
+//-----------------------------------------------------------------------------
+// DEMO CODE
+//-----------------------------------------------------------------------------
+
+#ifndef IMGUI_DISABLE_TEST_WINDOWS
+
+static void ShowExampleAppConsole(bool* p_open);
+static void ShowExampleAppLog(bool* p_open);
+static void ShowExampleAppLayout(bool* p_open);
+static void ShowExampleAppPropertyEditor(bool* p_open);
+static void ShowExampleAppLongText(bool* p_open);
+static void ShowExampleAppAutoResize(bool* p_open);
+static void ShowExampleAppConstrainedResize(bool* p_open);
+static void ShowExampleAppFixedOverlay(bool* p_open);
+static void ShowExampleAppManipulatingWindowTitle(bool* p_open);
+static void ShowExampleAppCustomRendering(bool* p_open);
+static void ShowExampleAppMainMenuBar();
+static void ShowExampleMenuFile();
+
+static void ShowHelpMarker(const char* desc)
+{
+ ImGui::TextDisabled("(?)");
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip(desc);
+}
+
+void ImGui::ShowUserGuide()
+{
+ ImGui::BulletText("Double-click on title bar to collapse window.");
+ ImGui::BulletText("Click and drag on lower right corner to resize window.");
+ ImGui::BulletText("Click and drag on any empty space to move window.");
+ ImGui::BulletText("Mouse Wheel to scroll.");
+ if (ImGui::GetIO().FontAllowUserScaling)
+ ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents.");
+ ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
+ ImGui::BulletText("CTRL+Click on a slider or drag box to input text.");
+ ImGui::BulletText(
+ "While editing text:\n"
+ "- Hold SHIFT or use mouse to select text\n"
+ "- CTRL+Left/Right to word jump\n"
+ "- CTRL+A or double-click to select all\n"
+ "- CTRL+X,CTRL+C,CTRL+V clipboard\n"
+ "- CTRL+Z,CTRL+Y undo/redo\n"
+ "- ESCAPE to revert\n"
+ "- You can apply arithmetic operators +,*,/ on numerical values.\n"
+ " Use +- to subtract.\n");
+}
+
+// Demonstrate most ImGui features (big function!)
+void ImGui::ShowTestWindow(bool* p_open)
+{
+ // Examples apps
+ static bool show_app_main_menu_bar = false;
+ static bool show_app_console = false;
+ static bool show_app_log = false;
+ static bool show_app_layout = false;
+ static bool show_app_property_editor = false;
+ static bool show_app_long_text = false;
+ static bool show_app_auto_resize = false;
+ static bool show_app_constrained_resize = false;
+ static bool show_app_fixed_overlay = false;
+ static bool show_app_manipulating_window_title = false;
+ static bool show_app_custom_rendering = false;
+ static bool show_app_style_editor = false;
+
+ static bool show_app_metrics = false;
+ static bool show_app_about = false;
+
+ if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
+ if (show_app_console) ShowExampleAppConsole(&show_app_console);
+ if (show_app_log) ShowExampleAppLog(&show_app_log);
+ if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
+ if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor);
+ if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text);
+ if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize);
+ if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize);
+ if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay);
+ if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title);
+ if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering);
+
+ if (show_app_metrics) ImGui::ShowMetricsWindow(&show_app_metrics);
+ if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); }
+ if (show_app_about)
+ {
+ ImGui::Begin("About ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize);
+ ImGui::Text("dear imgui, %s", ImGui::GetVersion());
+ ImGui::Separator();
+ ImGui::Text("By Omar Cornut and all github contributors.");
+ ImGui::Text("ImGui is licensed under the MIT License, see LICENSE for more information.");
+ ImGui::End();
+ }
+
+ static bool no_titlebar = false;
+ static bool no_border = true;
+ static bool no_resize = false;
+ static bool no_move = false;
+ static bool no_scrollbar = false;
+ static bool no_collapse = false;
+ static bool no_menu = false;
+
+ // Demonstrate the various window flags. Typically you would just use the default.
+ ImGuiWindowFlags window_flags = 0;
+ if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar;
+ if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders;
+ if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
+ if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
+ if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar;
+ if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
+ if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar;
+ ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiSetCond_FirstUseEver);
+ if (!ImGui::Begin("ImGui Demo", p_open, window_flags))
+ {
+ // Early out if the window is collapsed, as an optimization.
+ ImGui::End();
+ return;
+ }
+
+ //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels
+ ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels
+
+ ImGui::Text("Dear ImGui says hello.");
+
+ // Menu
+ if (ImGui::BeginMenuBar())
+ {
+ if (ImGui::BeginMenu("Menu"))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Examples"))
+ {
+ ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar);
+ ImGui::MenuItem("Console", NULL, &show_app_console);
+ ImGui::MenuItem("Log", NULL, &show_app_log);
+ ImGui::MenuItem("Simple layout", NULL, &show_app_layout);
+ ImGui::MenuItem("Property editor", NULL, &show_app_property_editor);
+ ImGui::MenuItem("Long text display", NULL, &show_app_long_text);
+ ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize);
+ ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize);
+ ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay);
+ ImGui::MenuItem("Manipulating window title", NULL, &show_app_manipulating_window_title);
+ ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering);
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Help"))
+ {
+ ImGui::MenuItem("Metrics", NULL, &show_app_metrics);
+ ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor);
+ ImGui::MenuItem("About ImGui", NULL, &show_app_about);
+ ImGui::EndMenu();
+ }
+ ImGui::EndMenuBar();
+ }
+
+ ImGui::Spacing();
+ if (ImGui::CollapsingHeader("Help"))
+ {
+ ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:");
+ ImGui::ShowUserGuide();
+ }
+
+ if (ImGui::CollapsingHeader("Window options"))
+ {
+ ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150);
+ ImGui::Checkbox("No border", &no_border); ImGui::SameLine(300);
+ ImGui::Checkbox("No resize", &no_resize);
+ ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150);
+ ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300);
+ ImGui::Checkbox("No collapse", &no_collapse);
+ ImGui::Checkbox("No menu", &no_menu);
+
+ if (ImGui::TreeNode("Style"))
+ {
+ ImGui::ShowStyleEditor();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Logging"))
+ {
+ ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded. You can also call ImGui::LogText() to output directly to the log without a visual output.");
+ ImGui::LogButtons();
+ ImGui::TreePop();
+ }
+ }
+
+ if (ImGui::CollapsingHeader("Widgets"))
+ {
+ if (ImGui::TreeNode("Trees"))
+ {
+ if (ImGui::TreeNode("Basic trees"))
+ {
+ for (int i = 0; i < 5; i++)
+ if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i))
+ {
+ ImGui::Text("blah blah");
+ ImGui::SameLine();
+ if (ImGui::SmallButton("print")) printf("Child %d pressed", i);
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Advanced, with Selectable nodes"))
+ {
+ ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open.");
+ static bool align_label_with_current_x_position = false;
+ ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position);
+ ImGui::Text("Hello!");
+ if (align_label_with_current_x_position)
+ ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
+
+ static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit.
+ int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc.
+ ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents.
+ for (int i = 0; i < 6; i++)
+ {
+ // Disable the default open on single-click behavior and pass in Selected flag according to our selection state.
+ ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0);
+ if (i < 3)
+ {
+ // Node
+ bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
+ if (ImGui::IsItemClicked())
+ node_clicked = i;
+ if (node_open)
+ {
+ ImGui::Text("Blah blah\nBlah Blah");
+ ImGui::TreePop();
+ }
+ }
+ else
+ {
+ // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text().
+ ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i);
+ if (ImGui::IsItemClicked())
+ node_clicked = i;
+ }
+ }
+ if (node_clicked != -1)
+ {
+ // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame.
+ if (ImGui::GetIO().KeyCtrl)
+ selection_mask ^= (1 << node_clicked); // CTRL+click to toggle
+ else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection
+ selection_mask = (1 << node_clicked); // Click to single-select
+ }
+ ImGui::PopStyleVar();
+ if (align_label_with_current_x_position)
+ ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Collapsing Headers"))
+ {
+ static bool closable_group = true;
+ if (ImGui::CollapsingHeader("Header"))
+ {
+ ImGui::Checkbox("Enable extra group", &closable_group);
+ for (int i = 0; i < 5; i++)
+ ImGui::Text("Some content %d", i);
+ }
+ if (ImGui::CollapsingHeader("Header with a close button", &closable_group))
+ {
+ for (int i = 0; i < 5; i++)
+ ImGui::Text("More content %d", i);
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Bullets"))
+ {
+ ImGui::BulletText("Bullet point 1");
+ ImGui::BulletText("Bullet point 2\nOn multiple lines");
+ ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)");
+ ImGui::Bullet(); ImGui::SmallButton("Button");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Colored Text"))
+ {
+ // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility.
+ ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink");
+ ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow");
+ ImGui::TextDisabled("Disabled");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Word Wrapping"))
+ {
+ // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
+ ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.");
+ ImGui::Spacing();
+
+ static float wrap_width = 200.0f;
+ ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f");
+
+ ImGui::Text("Test paragraph 1:");
+ ImVec2 pos = ImGui::GetCursorScreenPos();
+ ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), 0xFFFF00FF);
+ ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
+ ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width);
+ ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF);
+ ImGui::PopTextWrapPos();
+
+ ImGui::Text("Test paragraph 2:");
+ pos = ImGui::GetCursorScreenPos();
+ ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), 0xFFFF00FF);
+ ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
+ ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh");
+ ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF);
+ ImGui::PopTextWrapPos();
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("UTF-8 Text"))
+ {
+ // UTF-8 test with Japanese characters
+ // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html)
+ // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature')
+ // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants.
+ // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system!
+ // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application.
+ ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges.");
+ ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)");
+ ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)");
+ static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e";
+ ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf));
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Images"))
+ {
+ ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!");
+ ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos();
+ float tex_w = (float)ImGui::GetIO().Fonts->TexWidth;
+ float tex_h = (float)ImGui::GetIO().Fonts->TexHeight;
+ ImTextureID tex_id = ImGui::GetIO().Fonts->TexID;
+ ImGui::Text("%.0fx%.0f", tex_w, tex_h);
+ ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128));
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ float focus_sz = 32.0f;
+ float focus_x = ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > tex_w - focus_sz) focus_x = tex_w - focus_sz;
+ float focus_y = ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > tex_h - focus_sz) focus_y = tex_h - focus_sz;
+ ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y);
+ ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz);
+ ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h);
+ ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h);
+ ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128));
+ ImGui::EndTooltip();
+ }
+ ImGui::TextWrapped("And now some textured buttons..");
+ static int pressed_count = 0;
+ for (int i = 0; i < 8; i++)
+ {
+ ImGui::PushID(i);
+ int frame_padding = -1 + i; // -1 = uses default padding
+ if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding, ImColor(0,0,0,255)))
+ pressed_count += 1;
+ ImGui::PopID();
+ ImGui::SameLine();
+ }
+ ImGui::NewLine();
+ ImGui::Text("Pressed %d times.", pressed_count);
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Selectables"))
+ {
+ if (ImGui::TreeNode("Basic"))
+ {
+ static bool selected[4] = { false, true, false, false };
+ ImGui::Selectable("1. I am selectable", &selected[0]);
+ ImGui::Selectable("2. I am selectable", &selected[1]);
+ ImGui::Text("3. I am not selectable");
+ ImGui::Selectable("4. I am selectable", &selected[2]);
+ if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick))
+ if (ImGui::IsMouseDoubleClicked(0))
+ selected[3] = !selected[3];
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Rendering more text into the same block"))
+ {
+ static bool selected[3] = { false, false, false };
+ ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
+ ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes");
+ ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Grid"))
+ {
+ static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true };
+ for (int i = 0; i < 16; i++)
+ {
+ ImGui::PushID(i);
+ if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50)))
+ {
+ int x = i % 4, y = i / 4;
+ if (x > 0) selected[i - 1] ^= 1;
+ if (x < 3) selected[i + 1] ^= 1;
+ if (y > 0) selected[i - 4] ^= 1;
+ if (y < 3) selected[i + 4] ^= 1;
+ }
+ if ((i % 4) < 3) ImGui::SameLine();
+ ImGui::PopID();
+ }
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Filtered Text Input"))
+ {
+ static char buf1[64] = ""; ImGui::InputText("default", buf1, 64);
+ static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal);
+ static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
+ static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase);
+ static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank);
+ struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } };
+ static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters);
+
+ ImGui::Text("Password input");
+ static char bufpass[64] = "password123";
+ ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank);
+ ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n");
+ ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank);
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Multi-line Text Input"))
+ {
+ static bool read_only = false;
+ static char text[1024*16] =
+ "/*\n"
+ " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n"
+ " the hexadecimal encoding of one offending instruction,\n"
+ " more formally, the invalid operand with locked CMPXCHG8B\n"
+ " instruction bug, is a design flaw in the majority of\n"
+ " Intel Pentium, Pentium MMX, and Pentium OverDrive\n"
+ " processors (all in the P5 microarchitecture).\n"
+ "*/\n\n"
+ "label:\n"
+ "\tlock cmpxchg8b eax\n";
+
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
+ ImGui::Checkbox("Read-only", &read_only);
+ ImGui::PopStyleVar();
+ ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0));
+ ImGui::TreePop();
+ }
+
+ static bool a=false;
+ if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; }
+ if (a)
+ {
+ ImGui::SameLine();
+ ImGui::Text("Thanks for clicking me!");
+ }
+
+ static bool check = true;
+ ImGui::Checkbox("checkbox", &check);
+
+ static int e = 0;
+ ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine();
+ ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine();
+ ImGui::RadioButton("radio c", &e, 2);
+
+ // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.
+ for (int i = 0; i < 7; i++)
+ {
+ if (i > 0) ImGui::SameLine();
+ ImGui::PushID(i);
+ ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f));
+ ImGui::Button("Click");
+ ImGui::PopStyleColor(3);
+ ImGui::PopID();
+ }
+
+ ImGui::Text("Hover over me");
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("I am a tooltip");
+
+ ImGui::SameLine();
+ ImGui::Text("- or me");
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ ImGui::Text("I am a fancy tooltip");
+ static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
+ ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr));
+ ImGui::EndTooltip();
+ }
+
+ // Testing IMGUI_ONCE_UPON_A_FRAME macro
+ //for (int i = 0; i < 5; i++)
+ //{
+ // IMGUI_ONCE_UPON_A_FRAME
+ // {
+ // ImGui::Text("This will be displayed only once.");
+ // }
+ //}
+
+ ImGui::Separator();
+
+ ImGui::LabelText("label", "Value");
+
+ static int item = 1;
+ ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Combo using values packed in a single constant string (for really quick combo)
+
+ const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" };
+ static int item2 = -1;
+ ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that.
+
+ {
+ static char str0[128] = "Hello, world!";
+ static int i0=123;
+ static float f0=0.001f;
+ ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
+ ImGui::SameLine(); ShowHelpMarker("Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n");
+
+ ImGui::InputInt("input int", &i0);
+ ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n");
+
+ ImGui::InputFloat("input float", &f0, 0.01f, 1.0f);
+
+ static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
+ ImGui::InputFloat3("input float3", vec4a);
+ }
+
+ {
+ static int i1=50, i2=42;
+ ImGui::DragInt("drag int", &i1, 1);
+ ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value.");
+
+ ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%");
+
+ static float f1=1.00f, f2=0.0067f;
+ ImGui::DragFloat("drag float", &f1, 0.005f);
+ ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns");
+ }
+
+ {
+ static int i1=0;
+ ImGui::SliderInt("slider int", &i1, -1, 3);
+ ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value.");
+
+ static float f1=0.123f, f2=0.0f;
+ ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
+ ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f);
+ static float angle = 0.0f;
+ ImGui::SliderAngle("slider angle", &angle);
+ }
+
+ static float col1[3] = { 1.0f,0.0f,0.2f };
+ static float col2[4] = { 0.4f,0.7f,0.0f,0.5f };
+ ImGui::ColorEdit3("color 1", col1);
+ ImGui::SameLine(); ShowHelpMarker("Click on the colored square to change edit mode.\nCTRL+click on individual component to input value.\n");
+
+ ImGui::ColorEdit4("color 2", col2);
+
+ const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" };
+ static int listbox_item_current = 1;
+ ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
+
+ //static int listbox_item_current2 = 2;
+ //ImGui::PushItemWidth(-1);
+ //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
+ //ImGui::PopItemWidth();
+
+ if (ImGui::TreeNode("Range Widgets"))
+ {
+ ImGui::Unindent();
+
+ static float begin = 10, end = 90;
+ static int begin_i = 100, end_i = 1000;
+ ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%");
+ ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units");
+
+ ImGui::Indent();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Multi-component Widgets"))
+ {
+ ImGui::Unindent();
+
+ static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
+ static int vec4i[4] = { 1, 5, 100, 255 };
+
+ ImGui::InputFloat2("input float2", vec4f);
+ ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f);
+ ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f);
+ ImGui::DragInt2("drag int2", vec4i, 1, 0, 255);
+ ImGui::InputInt2("input int2", vec4i);
+ ImGui::SliderInt2("slider int2", vec4i, 0, 255);
+ ImGui::Spacing();
+
+ ImGui::InputFloat3("input float3", vec4f);
+ ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f);
+ ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f);
+ ImGui::DragInt3("drag int3", vec4i, 1, 0, 255);
+ ImGui::InputInt3("input int3", vec4i);
+ ImGui::SliderInt3("slider int3", vec4i, 0, 255);
+ ImGui::Spacing();
+
+ ImGui::InputFloat4("input float4", vec4f);
+ ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f);
+ ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f);
+ ImGui::InputInt4("input int4", vec4i);
+ ImGui::DragInt4("drag int4", vec4i, 1, 0, 255);
+ ImGui::SliderInt4("slider int4", vec4i, 0, 255);
+
+ ImGui::Indent();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Vertical Sliders"))
+ {
+ ImGui::Unindent();
+ const float spacing = 4;
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
+
+ static int int_value = 0;
+ ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5);
+ ImGui::SameLine();
+
+ static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f };
+ ImGui::PushID("set1");
+ for (int i = 0; i < 7; i++)
+ {
+ if (i > 0) ImGui::SameLine();
+ ImGui::PushID(i);
+ ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f));
+ ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f));
+ ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f));
+ ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f));
+ ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, "");
+ if (ImGui::IsItemActive() || ImGui::IsItemHovered())
+ ImGui::SetTooltip("%.3f", values[i]);
+ ImGui::PopStyleColor(4);
+ ImGui::PopID();
+ }
+ ImGui::PopID();
+
+ ImGui::SameLine();
+ ImGui::PushID("set2");
+ static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f };
+ const int rows = 3;
+ const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows);
+ for (int nx = 0; nx < 4; nx++)
+ {
+ if (nx > 0) ImGui::SameLine();
+ ImGui::BeginGroup();
+ for (int ny = 0; ny < rows; ny++)
+ {
+ ImGui::PushID(nx*rows+ny);
+ ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, "");
+ if (ImGui::IsItemActive() || ImGui::IsItemHovered())
+ ImGui::SetTooltip("%.3f", values2[nx]);
+ ImGui::PopID();
+ }
+ ImGui::EndGroup();
+ }
+ ImGui::PopID();
+
+ ImGui::SameLine();
+ ImGui::PushID("set3");
+ for (int i = 0; i < 4; i++)
+ {
+ if (i > 0) ImGui::SameLine();
+ ImGui::PushID(i);
+ ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);
+ ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec");
+ ImGui::PopStyleVar();
+ ImGui::PopID();
+ }
+ ImGui::PopID();
+ ImGui::PopStyleVar();
+
+ ImGui::Indent();
+ ImGui::TreePop();
+ }
+ }
+
+ if (ImGui::CollapsingHeader("Graphs widgets"))
+ {
+ static bool animate = true;
+ ImGui::Checkbox("Animate", &animate);
+
+ static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
+ ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr));
+
+ // Create a dummy array of contiguous float values to plot
+ // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter.
+ static float values[90] = { 0 };
+ static int values_offset = 0;
+ if (animate)
+ {
+ static float refresh_time = ImGui::GetTime(); // Create dummy data at fixed 60 hz rate for the demo
+ for (; ImGui::GetTime() > refresh_time + 1.0f/60.0f; refresh_time += 1.0f/60.0f)
+ {
+ static float phase = 0.0f;
+ values[values_offset] = cosf(phase);
+ values_offset = (values_offset+1) % IM_ARRAYSIZE(values);
+ phase += 0.10f*values_offset;
+ }
+ }
+ ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80));
+ ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80));
+
+ // Use functions to generate output
+ // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count.
+ struct Funcs
+ {
+ static float Sin(void*, int i) { return sinf(i * 0.1f); }
+ static float Saw(void*, int i) { return (i & 1) ? 1.0f : 0.0f; }
+ };
+ static int func_type = 0, display_count = 70;
+ ImGui::Separator();
+ ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth();
+ ImGui::SameLine();
+ ImGui::SliderInt("Sample count", &display_count, 1, 500);
+ float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw;
+ ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80));
+ ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80));
+ ImGui::Separator();
+
+ // Animate a simple progress bar
+ static float progress = 0.0f, progress_dir = 1.0f;
+ if (animate)
+ {
+ progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;
+ if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; }
+ if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; }
+ }
+
+ // Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth.
+ ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f));
+ ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
+ ImGui::Text("Progress Bar");
+
+ float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress;
+ char buf[32];
+ sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753);
+ ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf);
+ }
+
+ if (ImGui::CollapsingHeader("Layout"))
+ {
+ if (ImGui::TreeNode("Child regions"))
+ {
+ ImGui::Text("Without border");
+ static int line = 50;
+ bool goto_line = ImGui::Button("Goto");
+ ImGui::SameLine();
+ ImGui::PushItemWidth(100);
+ goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue);
+ ImGui::PopItemWidth();
+ ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar);
+ for (int i = 0; i < 100; i++)
+ {
+ ImGui::Text("%04d: scrollable region", i);
+ if (goto_line && line == i)
+ ImGui::SetScrollHere();
+ }
+ if (goto_line && line >= 100)
+ ImGui::SetScrollHere();
+ ImGui::EndChild();
+
+ ImGui::SameLine();
+
+ ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f);
+ ImGui::BeginChild("Sub2", ImVec2(0,300), true);
+ ImGui::Text("With border");
+ ImGui::Columns(2);
+ for (int i = 0; i < 100; i++)
+ {
+ if (i == 50)
+ ImGui::NextColumn();
+ char buf[32];
+ sprintf(buf, "%08x", i*5731);
+ ImGui::Button(buf, ImVec2(-1.0f, 0.0f));
+ }
+ ImGui::EndChild();
+ ImGui::PopStyleVar();
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Widgets Width"))
+ {
+ static float f = 0.0f;
+ ImGui::Text("PushItemWidth(100)");
+ ImGui::SameLine(); ShowHelpMarker("Fixed width.");
+ ImGui::PushItemWidth(100);
+ ImGui::DragFloat("float##1", &f);
+ ImGui::PopItemWidth();
+
+ ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)");
+ ImGui::SameLine(); ShowHelpMarker("Half of window width.");
+ ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
+ ImGui::DragFloat("float##2", &f);
+ ImGui::PopItemWidth();
+
+ ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)");
+ ImGui::SameLine(); ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
+ ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f);
+ ImGui::DragFloat("float##3", &f);
+ ImGui::PopItemWidth();
+
+ ImGui::Text("PushItemWidth(-100)");
+ ImGui::SameLine(); ShowHelpMarker("Align to right edge minus 100");
+ ImGui::PushItemWidth(-100);
+ ImGui::DragFloat("float##4", &f);
+ ImGui::PopItemWidth();
+
+ ImGui::Text("PushItemWidth(-1)");
+ ImGui::SameLine(); ShowHelpMarker("Align to right edge");
+ ImGui::PushItemWidth(-1);
+ ImGui::DragFloat("float##5", &f);
+ ImGui::PopItemWidth();
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Basic Horizontal Layout"))
+ {
+ ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceeding item)");
+
+ // Text
+ ImGui::Text("Two items: Hello"); ImGui::SameLine();
+ ImGui::TextColored(ImVec4(1,1,0,1), "Sailor");
+
+ // Adjust spacing
+ ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20);
+ ImGui::TextColored(ImVec4(1,1,0,1), "Sailor");
+
+ // Button
+ ImGui::AlignFirstTextHeightToWidgets();
+ ImGui::Text("Normal buttons"); ImGui::SameLine();
+ ImGui::Button("Banana"); ImGui::SameLine();
+ ImGui::Button("Apple"); ImGui::SameLine();
+ ImGui::Button("Corniflower");
+
+ // Button
+ ImGui::Text("Small buttons"); ImGui::SameLine();
+ ImGui::SmallButton("Like this one"); ImGui::SameLine();
+ ImGui::Text("can fit within a text block.");
+
+ // Aligned to arbitrary position. Easy/cheap column.
+ ImGui::Text("Aligned");
+ ImGui::SameLine(150); ImGui::Text("x=150");
+ ImGui::SameLine(300); ImGui::Text("x=300");
+ ImGui::Text("Aligned");
+ ImGui::SameLine(150); ImGui::SmallButton("x=150");
+ ImGui::SameLine(300); ImGui::SmallButton("x=300");
+
+ // Checkbox
+ static bool c1=false,c2=false,c3=false,c4=false;
+ ImGui::Checkbox("My", &c1); ImGui::SameLine();
+ ImGui::Checkbox("Tailor", &c2); ImGui::SameLine();
+ ImGui::Checkbox("Is", &c3); ImGui::SameLine();
+ ImGui::Checkbox("Rich", &c4);
+
+ // Various
+ static float f0=1.0f, f1=2.0f, f2=3.0f;
+ ImGui::PushItemWidth(80);
+ const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" };
+ static int item = -1;
+ ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine();
+ ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine();
+ ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine();
+ ImGui::SliderFloat("Z", &f2, 0.0f,5.0f);
+ ImGui::PopItemWidth();
+
+ ImGui::PushItemWidth(80);
+ ImGui::Text("Lists:");
+ static int selection[4] = { 0, 1, 2, 3 };
+ for (int i = 0; i < 4; i++)
+ {
+ if (i > 0) ImGui::SameLine();
+ ImGui::PushID(i);
+ ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items));
+ ImGui::PopID();
+ //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i);
+ }
+ ImGui::PopItemWidth();
+
+ // Dummy
+ ImVec2 sz(30,30);
+ ImGui::Button("A", sz); ImGui::SameLine();
+ ImGui::Dummy(sz); ImGui::SameLine();
+ ImGui::Button("B", sz);
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Groups"))
+ {
+ ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it.)");
+ ImGui::BeginGroup();
+ {
+ ImGui::BeginGroup();
+ ImGui::Button("AAA");
+ ImGui::SameLine();
+ ImGui::Button("BBB");
+ ImGui::SameLine();
+ ImGui::BeginGroup();
+ ImGui::Button("CCC");
+ ImGui::Button("DDD");
+ ImGui::EndGroup();
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("Group hovered");
+ ImGui::SameLine();
+ ImGui::Button("EEE");
+ ImGui::EndGroup();
+ }
+ // Capture the group size and create widgets using the same size
+ ImVec2 size = ImGui::GetItemRectSize();
+ const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f };
+ ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size);
+
+ ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y));
+ ImGui::SameLine();
+ ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y));
+ ImGui::EndGroup();
+ ImGui::SameLine();
+
+ ImGui::Button("LEVERAGE\nBUZZWORD", size);
+ ImGui::SameLine();
+
+ ImGui::ListBoxHeader("List", size);
+ ImGui::Selectable("Selected", true);
+ ImGui::Selectable("Not Selected", false);
+ ImGui::ListBoxFooter();
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Text Baseline Alignment"))
+ {
+ ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)");
+
+ ImGui::Text("One\nTwo\nThree"); ImGui::SameLine();
+ ImGui::Text("Hello\nWorld"); ImGui::SameLine();
+ ImGui::Text("Banana");
+
+ ImGui::Text("Banana"); ImGui::SameLine();
+ ImGui::Text("Hello\nWorld"); ImGui::SameLine();
+ ImGui::Text("One\nTwo\nThree");
+
+ ImGui::Button("HOP"); ImGui::SameLine();
+ ImGui::Text("Banana"); ImGui::SameLine();
+ ImGui::Text("Hello\nWorld"); ImGui::SameLine();
+ ImGui::Text("Banana");
+
+ ImGui::Button("HOP"); ImGui::SameLine();
+ ImGui::Text("Hello\nWorld"); ImGui::SameLine();
+ ImGui::Text("Banana");
+
+ ImGui::Button("TEST"); ImGui::SameLine();
+ ImGui::Text("TEST"); ImGui::SameLine();
+ ImGui::SmallButton("TEST");
+
+ ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets.
+ ImGui::Text("Text aligned to Widget"); ImGui::SameLine();
+ ImGui::Button("Widget"); ImGui::SameLine();
+ ImGui::Text("Widget"); ImGui::SameLine();
+ ImGui::SmallButton("Widget");
+
+ // Tree
+ const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
+ ImGui::Button("Button##1");
+ ImGui::SameLine(0.0f, spacing);
+ if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data
+
+ ImGui::AlignFirstTextHeightToWidgets(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit).
+ bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content.
+ ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2");
+ if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data
+
+ // Bullet
+ ImGui::Button("Button##3");
+ ImGui::SameLine(0.0f, spacing);
+ ImGui::BulletText("Bullet text");
+
+ ImGui::AlignFirstTextHeightToWidgets();
+ ImGui::BulletText("Node");
+ ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4");
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Scrolling"))
+ {
+ ImGui::TextWrapped("(Use SetScrollHere() or SetScrollFromPosY() to scroll to a given position.)");
+ static bool track = true;
+ static int track_line = 50, scroll_to_px = 200;
+ ImGui::Checkbox("Track", &track);
+ ImGui::PushItemWidth(100);
+ ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line %.0f");
+ bool scroll_to = ImGui::Button("Scroll To");
+ ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "y = %.0f px");
+ ImGui::PopItemWidth();
+ if (scroll_to) track = false;
+
+ for (int i = 0; i < 5; i++)
+ {
+ if (i > 0) ImGui::SameLine();
+ ImGui::BeginGroup();
+ ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom");
+ ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true);
+ if (scroll_to)
+ ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f);
+ for (int line = 0; line < 100; line++)
+ {
+ if (track && line == track_line)
+ {
+ ImGui::TextColored(ImColor(255,255,0), "Line %d", line);
+ ImGui::SetScrollHere(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom
+ }
+ else
+ {
+ ImGui::Text("Line %d", line);
+ }
+ }
+ ImGui::EndChild();
+ ImGui::EndGroup();
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Horizontal Scrolling"))
+ {
+ ImGui::Bullet(); ImGui::TextWrapped("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.");
+ ImGui::Bullet(); ImGui::TextWrapped("You may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin().");
+ static int lines = 7;
+ ImGui::SliderInt("Lines", &lines, 1, 15);
+ ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f));
+ ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetItemsLineHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar);
+ for (int line = 0; line < lines; line++)
+ {
+ // Display random stuff
+ int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);
+ for (int n = 0; n < num_buttons; n++)
+ {
+ if (n > 0) ImGui::SameLine();
+ ImGui::PushID(n + line * 1000);
+ char num_buf[16];
+ const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : (sprintf(num_buf, "%d", n), num_buf);
+ float hue = n*0.05f;
+ ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(hue, 0.6f, 0.6f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(hue, 0.7f, 0.7f));
+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(hue, 0.8f, 0.8f));
+ ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f));
+ ImGui::PopStyleColor(3);
+ ImGui::PopID();
+ }
+ }
+ ImGui::EndChild();
+ ImGui::PopStyleVar(2);
+ float scroll_x_delta = 0.0f;
+ ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f;
+ ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine();
+ ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;
+ if (scroll_x_delta != 0.0f)
+ {
+ ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window)
+ ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta);
+ ImGui::End();
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Clipping"))
+ {
+ static ImVec2 size(100, 100), offset(50, 20);
+ ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost.");
+ ImGui::DragFloat2("size", (float*)&size, 0.5f, 0.0f, 200.0f, "%.0f");
+ ImGui::TextWrapped("(Click and drag)");
+ ImVec2 pos = ImGui::GetCursorScreenPos();
+ ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y);
+ ImGui::InvisibleButton("##dummy", size);
+ if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; }
+ ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), ImColor(90,90,120,255));
+ ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect);
+ ImGui::TreePop();
+ }
+ }
+
+ if (ImGui::CollapsingHeader("Popups & Modal windows"))
+ {
+ if (ImGui::TreeNode("Popups"))
+ {
+ ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it.");
+
+ static int selected_fish = -1;
+ const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" };
+ static bool toggles[] = { true, false, false, false, false };
+
+ if (ImGui::Button("Select.."))
+ ImGui::OpenPopup("select");
+ ImGui::SameLine();
+ ImGui::Text(selected_fish == -1 ? "<None>" : names[selected_fish]);
+ if (ImGui::BeginPopup("select"))
+ {
+ ImGui::Text("Aquarium");
+ ImGui::Separator();
+ for (int i = 0; i < IM_ARRAYSIZE(names); i++)
+ if (ImGui::Selectable(names[i]))
+ selected_fish = i;
+ ImGui::EndPopup();
+ }
+
+ if (ImGui::Button("Toggle.."))
+ ImGui::OpenPopup("toggle");
+ if (ImGui::BeginPopup("toggle"))
+ {
+ for (int i = 0; i < IM_ARRAYSIZE(names); i++)
+ ImGui::MenuItem(names[i], "", &toggles[i]);
+ if (ImGui::BeginMenu("Sub-menu"))
+ {
+ ImGui::MenuItem("Click me");
+ ImGui::EndMenu();
+ }
+
+ ImGui::Separator();
+ ImGui::Text("Tooltip here");
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("I am a tooltip over a popup");
+
+ if (ImGui::Button("Stacked Popup"))
+ ImGui::OpenPopup("another popup");
+ if (ImGui::BeginPopup("another popup"))
+ {
+ for (int i = 0; i < IM_ARRAYSIZE(names); i++)
+ ImGui::MenuItem(names[i], "", &toggles[i]);
+ if (ImGui::BeginMenu("Sub-menu"))
+ {
+ ImGui::MenuItem("Click me");
+ ImGui::EndMenu();
+ }
+ ImGui::EndPopup();
+ }
+ ImGui::EndPopup();
+ }
+
+ if (ImGui::Button("Popup Menu.."))
+ ImGui::OpenPopup("popup from button");
+ if (ImGui::BeginPopup("popup from button"))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndPopup();
+ }
+
+ ImGui::Spacing();
+ ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!");
+ ImGui::Separator();
+ // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above.
+ // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here
+ // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus.
+ ImGui::PushID("foo");
+ ImGui::MenuItem("Menu item", "CTRL+M");
+ if (ImGui::BeginMenu("Menu inside a regular window"))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndMenu();
+ }
+ ImGui::PopID();
+ ImGui::Separator();
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Context menus"))
+ {
+ static float value = 0.5f;
+ ImGui::Text("Value = %.3f (<-- right-click here)", value);
+ if (ImGui::BeginPopupContextItem("item context menu"))
+ {
+ if (ImGui::Selectable("Set to zero")) value = 0.0f;
+ if (ImGui::Selectable("Set to PI")) value = 3.1415f;
+ ImGui::EndPopup();
+ }
+
+ static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f);
+ ImGui::ColorButton(color);
+ if (ImGui::BeginPopupContextItem("color context menu"))
+ {
+ ImGui::Text("Edit color");
+ ImGui::ColorEdit3("##edit", (float*)&color);
+ if (ImGui::Button("Close"))
+ ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ }
+ ImGui::SameLine(); ImGui::Text("(<-- right-click here)");
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Modals"))
+ {
+ ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window.");
+
+ if (ImGui::Button("Delete.."))
+ ImGui::OpenPopup("Delete?");
+ if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
+ {
+ ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
+ ImGui::Separator();
+
+ //static int dummy_i = 0;
+ //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0");
+
+ static bool dont_ask_me_next_time = false;
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
+ ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time);
+ ImGui::PopStyleVar();
+
+ if (ImGui::Button("OK", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); }
+ ImGui::SameLine();
+ if (ImGui::Button("Cancel", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); }
+ ImGui::EndPopup();
+ }
+
+ if (ImGui::Button("Stacked modals.."))
+ ImGui::OpenPopup("Stacked 1");
+ if (ImGui::BeginPopupModal("Stacked 1"))
+ {
+ ImGui::Text("Hello from Stacked The First");
+
+ if (ImGui::Button("Another one.."))
+ ImGui::OpenPopup("Stacked 2");
+ if (ImGui::BeginPopupModal("Stacked 2"))
+ {
+ ImGui::Text("Hello from Stacked The Second");
+ if (ImGui::Button("Close"))
+ ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ }
+
+ if (ImGui::Button("Close"))
+ ImGui::CloseCurrentPopup();
+ ImGui::EndPopup();
+ }
+
+ ImGui::TreePop();
+ }
+ }
+
+ if (ImGui::CollapsingHeader("Columns"))
+ {
+ // Basic columns
+ if (ImGui::TreeNode("Basic"))
+ {
+ ImGui::Columns(4, "mycolumns");
+ ImGui::Separator();
+ ImGui::Text("ID"); ImGui::NextColumn();
+ ImGui::Text("Name"); ImGui::NextColumn();
+ ImGui::Text("Path"); ImGui::NextColumn();
+ ImGui::Text("Flags"); ImGui::NextColumn();
+ ImGui::Separator();
+ const char* names[3] = { "One", "Two", "Three" };
+ const char* paths[3] = { "/path/one", "/path/two", "/path/three" };
+ static int selected = -1;
+ for (int i = 0; i < 3; i++)
+ {
+ char label[32];
+ sprintf(label, "%04d", i);
+ if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))
+ selected = i;
+ ImGui::NextColumn();
+ ImGui::Text(names[i]); ImGui::NextColumn();
+ ImGui::Text(paths[i]); ImGui::NextColumn();
+ ImGui::Text("...."); ImGui::NextColumn();
+ }
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ // Scrolling columns
+ /*
+ if (ImGui::TreeNode("Scrolling"))
+ {
+ ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y));
+ ImGui::Columns(3);
+ ImGui::Text("ID"); ImGui::NextColumn();
+ ImGui::Text("Name"); ImGui::NextColumn();
+ ImGui::Text("Path"); ImGui::NextColumn();
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::EndChild();
+ ImGui::BeginChild("##scrollingregion", ImVec2(0, 60));
+ ImGui::Columns(3);
+ for (int i = 0; i < 10; i++)
+ {
+ ImGui::Text("%04d", i); ImGui::NextColumn();
+ ImGui::Text("Foobar"); ImGui::NextColumn();
+ ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn();
+ }
+ ImGui::Columns(1);
+ ImGui::EndChild();
+ ImGui::TreePop();
+ }
+ */
+
+ // Create multiple items in a same cell before switching to next column
+ if (ImGui::TreeNode("Mixed items"))
+ {
+ ImGui::Columns(3, "mixed");
+ ImGui::Separator();
+
+ ImGui::Text("Hello");
+ ImGui::Button("Banana");
+ ImGui::NextColumn();
+
+ ImGui::Text("ImGui");
+ ImGui::Button("Apple");
+ static float foo = 1.0f;
+ ImGui::InputFloat("red", &foo, 0.05f, 0, 3);
+ ImGui::Text("An extra line here.");
+ ImGui::NextColumn();
+
+ ImGui::Text("Sailor");
+ ImGui::Button("Corniflower");
+ static float bar = 1.0f;
+ ImGui::InputFloat("blue", &bar, 0.05f, 0, 3);
+ ImGui::NextColumn();
+
+ if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn();
+ if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn();
+ if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn();
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ // Word wrapping
+ if (ImGui::TreeNode("Word-wrapping"))
+ {
+ ImGui::Columns(2, "word-wrapping");
+ ImGui::Separator();
+ ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
+ ImGui::TextWrapped("Hello Left");
+ ImGui::NextColumn();
+ ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
+ ImGui::TextWrapped("Hello Right");
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Borders"))
+ {
+ static bool h_borders = true;
+ static bool v_borders = true;
+ ImGui::Checkbox("horizontal", &h_borders);
+ ImGui::SameLine();
+ ImGui::Checkbox("vertical", &v_borders);
+ ImGui::Columns(4, NULL, v_borders);
+ if (h_borders) ImGui::Separator();
+ for (int i = 0; i < 8; i++)
+ {
+ ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i);
+ ImGui::NextColumn();
+ }
+ ImGui::Columns(1);
+ if (h_borders) ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ bool node_open = ImGui::TreeNode("Tree within single cell");
+ ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell.\nThere's no storage of state per-cell.");
+ if (node_open)
+ {
+ ImGui::Columns(2, "tree items");
+ ImGui::Separator();
+ if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn();
+ if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn();
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+ }
+
+ if (ImGui::CollapsingHeader("Filtering"))
+ {
+ static ImGuiTextFilter filter;
+ ImGui::Text("Filter usage:\n"
+ " \"\" display all lines\n"
+ " \"xxx\" display lines containing \"xxx\"\n"
+ " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n"
+ " \"-xxx\" hide lines containing \"xxx\"");
+ filter.Draw();
+ const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" };
+ for (int i = 0; i < IM_ARRAYSIZE(lines); i++)
+ if (filter.PassFilter(lines[i]))
+ ImGui::BulletText("%s", lines[i]);
+ }
+
+ if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus"))
+ {
+ if (ImGui::TreeNode("Tabbing"))
+ {
+ ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.");
+ static char buf[32] = "dummy";
+ ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
+ ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
+ ImGui::InputText("3", buf, IM_ARRAYSIZE(buf));
+ ImGui::PushAllowKeyboardFocus(false);
+ ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf));
+ //ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets.");
+ ImGui::PopAllowKeyboardFocus();
+ ImGui::InputText("5", buf, IM_ARRAYSIZE(buf));
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Focus from code"))
+ {
+ bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine();
+ bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine();
+ bool focus_3 = ImGui::Button("Focus on 3");
+ int has_focus = 0;
+ static char buf[128] = "click on a button to set focus";
+
+ if (focus_1) ImGui::SetKeyboardFocusHere();
+ ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
+ if (ImGui::IsItemActive()) has_focus = 1;
+
+ if (focus_2) ImGui::SetKeyboardFocusHere();
+ ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
+ if (ImGui::IsItemActive()) has_focus = 2;
+
+ ImGui::PushAllowKeyboardFocus(false);
+ if (focus_3) ImGui::SetKeyboardFocusHere();
+ ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf));
+ if (ImGui::IsItemActive()) has_focus = 3;
+ ImGui::PopAllowKeyboardFocus();
+ if (has_focus)
+ ImGui::Text("Item with focus: %d", has_focus);
+ else
+ ImGui::Text("Item with focus: <none>");
+ ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code.");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Dragging"))
+ {
+ ImGui::TextWrapped("You can use ImGui::GetItemActiveDragDelta() to query for the dragged amount on any widget.");
+ ImGui::Button("Drag Me");
+ if (ImGui::IsItemActive())
+ {
+ // Draw a line between the button and the mouse cursor
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ draw_list->PushClipRectFullScreen();
+ draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f);
+ draw_list->PopClipRect();
+ ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f);
+ ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0);
+ ImVec2 mouse_delta = ImGui::GetIO().MouseDelta;
+ ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y);
+ }
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Keyboard & Mouse State"))
+ {
+ ImGuiIO& io = ImGui::GetIO();
+
+ ImGui::Text("MousePos: (%g, %g)", io.MousePos.x, io.MousePos.y);
+ ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
+ ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
+ ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
+ ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
+ ImGui::Text("MouseWheel: %.1f", io.MouseWheel);
+
+ ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); }
+ ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
+ ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
+ ImGui::Text("KeyMods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
+
+ ImGui::Text("WantCaptureMouse: %s", io.WantCaptureMouse ? "true" : "false");
+ ImGui::Text("WantCaptureKeyboard: %s", io.WantCaptureKeyboard ? "true" : "false");
+ ImGui::Text("WantTextInput: %s", io.WantTextInput ? "true" : "false");
+
+ ImGui::Button("Hovering me sets the\nkeyboard capture flag");
+ if (ImGui::IsItemHovered())
+ ImGui::CaptureKeyboardFromApp(true);
+ ImGui::SameLine();
+ ImGui::Button("Holding me clears the\nthe keyboard capture flag");
+ if (ImGui::IsItemActive())
+ ImGui::CaptureKeyboardFromApp(false);
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Mouse cursors"))
+ {
+ ImGui::TextWrapped("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software.");
+ ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor);
+ ImGui::Text("Hover to see mouse cursors:");
+ for (int i = 0; i < ImGuiMouseCursor_Count_; i++)
+ {
+ char label[32];
+ sprintf(label, "Mouse cursor %d", i);
+ ImGui::Bullet(); ImGui::Selectable(label, false);
+ if (ImGui::IsItemHovered())
+ ImGui::SetMouseCursor(i);
+ }
+ ImGui::TreePop();
+ }
+ }
+
+ ImGui::End();
+}
+
+void ImGui::ShowStyleEditor(ImGuiStyle* ref)
+{
+ ImGuiStyle& style = ImGui::GetStyle();
+
+ // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style)
+ const ImGuiStyle default_style; // Default style
+ if (ImGui::Button("Revert Style"))
+ style = ref ? *ref : default_style;
+
+ if (ref)
+ {
+ ImGui::SameLine();
+ if (ImGui::Button("Save Style"))
+ *ref = style;
+ }
+
+ ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f);
+
+ if (ImGui::TreeNode("Rendering"))
+ {
+ ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines);
+ ImGui::Checkbox("Anti-aliased shapes", &style.AntiAliasedShapes);
+ ImGui::PushItemWidth(100);
+ ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f);
+ if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f;
+ ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.
+ ImGui::PopItemWidth();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Sizes"))
+ {
+ ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f");
+ ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f");
+ ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f");
+ ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Colors"))
+ {
+ static int output_dest = 0;
+ static bool output_only_modified = false;
+ if (ImGui::Button("Copy Colors"))
+ {
+ if (output_dest == 0)
+ ImGui::LogToClipboard();
+ else
+ ImGui::LogToTTY();
+ ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" IM_NEWLINE);
+ for (int i = 0; i < ImGuiCol_COUNT; i++)
+ {
+ const ImVec4& col = style.Colors[i];
+ const char* name = ImGui::GetStyleColName(i);
+ if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0)
+ ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
+ }
+ ImGui::LogFinish();
+ }
+ ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY"); ImGui::PopItemWidth();
+ ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified);
+
+ static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB;
+ ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB);
+ ImGui::SameLine();
+ ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV);
+ ImGui::SameLine();
+ ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX);
+ //ImGui::Text("Tip: Click on colored square to change edit mode.");
+
+ static ImGuiTextFilter filter;
+ filter.Draw("Filter colors", 200);
+
+ ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar);
+ ImGui::PushItemWidth(-160);
+ ImGui::ColorEditMode(edit_mode);
+ for (int i = 0; i < ImGuiCol_COUNT; i++)
+ {
+ const char* name = ImGui::GetStyleColName(i);
+ if (!filter.PassFilter(name))
+ continue;
+ ImGui::PushID(i);
+ ImGui::ColorEdit4(name, (float*)&style.Colors[i], true);
+ if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0)
+ {
+ ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i];
+ if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; }
+ }
+ ImGui::PopID();
+ }
+ ImGui::PopItemWidth();
+ ImGui::EndChild();
+
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size))
+ {
+ ImGui::SameLine(); ShowHelpMarker("Tip: Load fonts with io.Fonts->AddFontFromFileTTF()\nbefore calling io.Fonts->GetTex* functions.");
+ ImFontAtlas* atlas = ImGui::GetIO().Fonts;
+ if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
+ {
+ ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128));
+ ImGui::TreePop();
+ }
+ ImGui::PushItemWidth(100);
+ for (int i = 0; i < atlas->Fonts.Size; i++)
+ {
+ ImFont* font = atlas->Fonts[i];
+ ImGui::BulletText("Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size);
+ ImGui::TreePush((void*)(intptr_t)i);
+ if (i > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { atlas->Fonts[i] = atlas->Fonts[0]; atlas->Fonts[0] = font; } }
+ ImGui::PushFont(font);
+ ImGui::Text("The quick brown fox jumps over the lazy dog");
+ ImGui::PopFont();
+ if (ImGui::TreeNode("Details"))
+ {
+ ImGui::DragFloat("font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this font
+ ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
+ ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar);
+ for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
+ {
+ ImFontConfig* cfg = &font->ConfigData[config_i];
+ ImGui::BulletText("Input %d: \'%s\'\nOversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH);
+ }
+ ImGui::TreePop();
+ }
+ ImGui::TreePop();
+ }
+ static float window_scale = 1.0f;
+ ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window
+ ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything
+ ImGui::PopItemWidth();
+ ImGui::SetWindowFontScale(window_scale);
+ ImGui::TreePop();
+ }
+
+ ImGui::PopItemWidth();
+}
+
+static void ShowExampleAppMainMenuBar()
+{
+ if (ImGui::BeginMainMenuBar())
+ {
+ if (ImGui::BeginMenu("File"))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Edit"))
+ {
+ if (ImGui::MenuItem("Undo", "CTRL+Z")) {}
+ if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item
+ ImGui::Separator();
+ if (ImGui::MenuItem("Cut", "CTRL+X")) {}
+ if (ImGui::MenuItem("Copy", "CTRL+C")) {}
+ if (ImGui::MenuItem("Paste", "CTRL+V")) {}
+ ImGui::EndMenu();
+ }
+ ImGui::EndMainMenuBar();
+ }
+}
+
+static void ShowExampleMenuFile()
+{
+ ImGui::MenuItem("(dummy menu)", NULL, false, false);
+ if (ImGui::MenuItem("New")) {}
+ if (ImGui::MenuItem("Open", "Ctrl+O")) {}
+ if (ImGui::BeginMenu("Open Recent"))
+ {
+ ImGui::MenuItem("fish_hat.c");
+ ImGui::MenuItem("fish_hat.inl");
+ ImGui::MenuItem("fish_hat.h");
+ if (ImGui::BeginMenu("More.."))
+ {
+ ImGui::MenuItem("Hello");
+ ImGui::MenuItem("Sailor");
+ if (ImGui::BeginMenu("Recurse.."))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndMenu();
+ }
+ ImGui::EndMenu();
+ }
+ ImGui::EndMenu();
+ }
+ if (ImGui::MenuItem("Save", "Ctrl+S")) {}
+ if (ImGui::MenuItem("Save As..")) {}
+ ImGui::Separator();
+ if (ImGui::BeginMenu("Options"))
+ {
+ static bool enabled = true;
+ ImGui::MenuItem("Enabled", "", &enabled);
+ ImGui::BeginChild("child", ImVec2(0, 60), true);
+ for (int i = 0; i < 10; i++)
+ ImGui::Text("Scrolling Text %d", i);
+ ImGui::EndChild();
+ static float f = 0.5f;
+ static int n = 0;
+ ImGui::SliderFloat("Value", &f, 0.0f, 1.0f);
+ ImGui::InputFloat("Input", &f, 0.1f);
+ ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0");
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Colors"))
+ {
+ for (int i = 0; i < ImGuiCol_COUNT; i++)
+ ImGui::MenuItem(ImGui::GetStyleColName((ImGuiCol)i));
+ ImGui::EndMenu();
+ }
+ if (ImGui::BeginMenu("Disabled", false)) // Disabled
+ {
+ IM_ASSERT(0);
+ }
+ if (ImGui::MenuItem("Checked", NULL, true)) {}
+ if (ImGui::MenuItem("Quit", "Alt+F4")) {}
+}
+
+static void ShowExampleAppAutoResize(bool* p_open)
+{
+ if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize))
+ {
+ ImGui::End();
+ return;
+ }
+
+ static int lines = 10;
+ ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop.");
+ ImGui::SliderInt("Number of lines", &lines, 1, 20);
+ for (int i = 0; i < lines; i++)
+ ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally
+ ImGui::End();
+}
+
+static void ShowExampleAppConstrainedResize(bool* p_open)
+{
+ struct CustomConstraints // Helper functions to demonstrate programmatic constraints
+ {
+ static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); }
+ static void Step(ImGuiSizeConstraintCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); }
+ };
+
+ static int type = 0;
+ if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only
+ if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only
+ if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100
+ if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(300, 0), ImVec2(400, FLT_MAX)); // Width 300-400
+ if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square
+ if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step
+
+ if (ImGui::Begin("Example: Constrained Resize", p_open))
+ {
+ const char* desc[] =
+ {
+ "Resize vertical only",
+ "Resize horizontal only",
+ "Width > 100, Height > 100",
+ "Width 300-400",
+ "Custom: Always Square",
+ "Custom: Fixed Steps (100)",
+ };
+ ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc));
+ if (ImGui::Button("200x200")) ImGui::SetWindowSize(ImVec2(200,200)); ImGui::SameLine();
+ if (ImGui::Button("500x500")) ImGui::SetWindowSize(ImVec2(500,500)); ImGui::SameLine();
+ if (ImGui::Button("800x200")) ImGui::SetWindowSize(ImVec2(800,200));
+ for (int i = 0; i < 10; i++)
+ ImGui::Text("Hello, sailor! Making this line long enough for the example.");
+ }
+ ImGui::End();
+}
+
+static void ShowExampleAppFixedOverlay(bool* p_open)
+{
+ ImGui::SetNextWindowPos(ImVec2(10,10));
+ if (!ImGui::Begin("Example: Fixed Overlay", p_open, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings))
+ {
+ ImGui::End();
+ return;
+ }
+ ImGui::Text("Simple overlay\non the top-left side of the screen.");
+ ImGui::Separator();
+ ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y);
+ ImGui::End();
+}
+
+static void ShowExampleAppManipulatingWindowTitle(bool*)
+{
+ // By default, Windows are uniquely identified by their title.
+ // You can use the "##" and "###" markers to manipulate the display/ID. Read FAQ at the top of this file!
+
+ // Using "##" to display same title but have unique identifier.
+ ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver);
+ ImGui::Begin("Same title as another window##1");
+ ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.");
+ ImGui::End();
+
+ ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver);
+ ImGui::Begin("Same title as another window##2");
+ ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.");
+ ImGui::End();
+
+ // Using "###" to display a changing title but keep a static identifier "AnimatedTitle"
+ char buf[128];
+ sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand());
+ ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver);
+ ImGui::Begin(buf);
+ ImGui::Text("This window has a changing title.");
+ ImGui::End();
+}
+
+static void ShowExampleAppCustomRendering(bool* p_open)
+{
+ ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiSetCond_FirstUseEver);
+ if (!ImGui::Begin("Example: Custom rendering", p_open))
+ {
+ ImGui::End();
+ return;
+ }
+
+ // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc.
+ // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4.
+ // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types)
+ // In this example we are not using the maths operators!
+ ImDrawList* draw_list = ImGui::GetWindowDrawList();
+
+ // Primitives
+ ImGui::Text("Primitives");
+ static float sz = 36.0f;
+ static ImVec4 col = ImVec4(1.0f,1.0f,0.4f,1.0f);
+ ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f");
+ ImGui::ColorEdit3("Color", &col.x);
+ {
+ const ImVec2 p = ImGui::GetCursorScreenPos();
+ const ImU32 col32 = ImColor(col);
+ float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f;
+ for (int n = 0; n < 2; n++)
+ {
+ float thickness = (n == 0) ? 1.0f : 4.0f;
+ draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, thickness); x += sz+spacing;
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ~0, thickness); x += sz+spacing;
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ~0, thickness); x += sz+spacing;
+ draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, thickness); x += sz+spacing;
+ draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, thickness); x += sz+spacing;
+ draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, thickness); x += sz+spacing;
+ draw_list->AddLine(ImVec2(x, y), ImVec2(x, y+sz), col32, thickness); x += spacing;
+ draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x+sz*1.3f,y+sz*0.3f), ImVec2(x+sz-sz*1.3f,y+sz-sz*0.3f), ImVec2(x+sz, y+sz), col32, thickness);
+ x = p.x + 4;
+ y += sz+spacing;
+ }
+ draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing;
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing;
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing;
+ draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing;
+ draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0));
+ ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3));
+ }
+ ImGui::Separator();
+ {
+ static ImVector<ImVec2> points;
+ static bool adding_line = false;
+ ImGui::Text("Canvas example");
+ if (ImGui::Button("Clear")) points.clear();
+ if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } }
+ ImGui::Text("Left-click and drag to add lines,\nRight-click to undo");
+
+ // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered()
+ // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos().
+ // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max).
+ ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
+ ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
+ if (canvas_size.x < 50.0f) canvas_size.x = 50.0f;
+ if (canvas_size.y < 50.0f) canvas_size.y = 50.0f;
+ draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60));
+ draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255));
+
+ bool adding_preview = false;
+ ImGui::InvisibleButton("canvas", canvas_size);
+ if (ImGui::IsItemHovered())
+ {
+ ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y);
+ if (!adding_line && ImGui::IsMouseClicked(0))
+ {
+ points.push_back(mouse_pos_in_canvas);
+ adding_line = true;
+ }
+ if (adding_line)
+ {
+ adding_preview = true;
+ points.push_back(mouse_pos_in_canvas);
+ if (!ImGui::GetIO().MouseDown[0])
+ adding_line = adding_preview = false;
+ }
+ if (ImGui::IsMouseClicked(1) && !points.empty())
+ {
+ adding_line = adding_preview = false;
+ points.pop_back();
+ points.pop_back();
+ }
+ }
+ draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.)
+ for (int i = 0; i < points.Size - 1; i += 2)
+ draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), 0xFF00FFFF, 2.0f);
+ draw_list->PopClipRect();
+ if (adding_preview)
+ points.pop_back();
+ }
+ ImGui::End();
+}
+
+// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions.
+struct ExampleAppConsole
+{
+ char InputBuf[256];
+ ImVector<char*> Items;
+ bool ScrollToBottom;
+ ImVector<char*> History;
+ int HistoryPos; // -1: new line, 0..History.Size-1 browsing history.
+ ImVector<const char*> Commands;
+
+ ExampleAppConsole()
+ {
+ ClearLog();
+ memset(InputBuf, 0, sizeof(InputBuf));
+ HistoryPos = -1;
+ Commands.push_back("HELP");
+ Commands.push_back("HISTORY");
+ Commands.push_back("CLEAR");
+ Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches.
+ AddLog("Welcome to ImGui!");
+ }
+ ~ExampleAppConsole()
+ {
+ ClearLog();
+ for (int i = 0; i < History.Size; i++)
+ free(History[i]);
+ }
+
+ // Portable helpers
+ static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; }
+ static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; }
+ static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buff = malloc(len); return (char*)memcpy(buff, (const void*)str, len); }
+
+ void ClearLog()
+ {
+ for (int i = 0; i < Items.Size; i++)
+ free(Items[i]);
+ Items.clear();
+ ScrollToBottom = true;
+ }
+
+ void AddLog(const char* fmt, ...) IM_PRINTFARGS(2)
+ {
+ char buf[1024];
+ va_list args;
+ va_start(args, fmt);
+ vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);
+ buf[IM_ARRAYSIZE(buf)-1] = 0;
+ va_end(args);
+ Items.push_back(Strdup(buf));
+ ScrollToBottom = true;
+ }
+
+ void Draw(const char* title, bool* p_open)
+ {
+ ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver);
+ if (!ImGui::Begin(title, p_open))
+ {
+ ImGui::End();
+ return;
+ }
+
+ ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
+ ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion.");
+
+ // TODO: display items starting from the bottom
+
+ if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine();
+ if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine();
+ if (ImGui::SmallButton("Clear")) ClearLog(); ImGui::SameLine();
+ if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true;
+ //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); }
+
+ ImGui::Separator();
+
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
+ static ImGuiTextFilter filter;
+ filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
+ ImGui::PopStyleVar();
+ ImGui::Separator();
+
+ ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
+ if (ImGui::BeginPopupContextWindow())
+ {
+ if (ImGui::Selectable("Clear")) ClearLog();
+ ImGui::EndPopup();
+ }
+
+ // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
+ // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items.
+ // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements.
+ // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with:
+ // ImGuiListClipper clipper(Items.Size);
+ // while (clipper.Step())
+ // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
+ // However take note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list.
+ // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter,
+ // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code!
+ // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list.
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing
+ for (int i = 0; i < Items.Size; i++)
+ {
+ const char* item = Items[i];
+ if (!filter.PassFilter(item))
+ continue;
+ ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text.
+ if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f);
+ else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f);
+ ImGui::PushStyleColor(ImGuiCol_Text, col);
+ ImGui::TextUnformatted(item);
+ ImGui::PopStyleColor();
+ }
+ if (ScrollToBottom)
+ ImGui::SetScrollHere();
+ ScrollToBottom = false;
+ ImGui::PopStyleVar();
+ ImGui::EndChild();
+ ImGui::Separator();
+
+ // Command-line
+ if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this))
+ {
+ char* input_end = InputBuf+strlen(InputBuf);
+ while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0;
+ if (InputBuf[0])
+ ExecCommand(InputBuf);
+ strcpy(InputBuf, "");
+ }
+
+ // Demonstrate keeping auto focus on the input box
+ if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)))
+ ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
+
+ ImGui::End();
+ }
+
+ void ExecCommand(const char* command_line)
+ {
+ AddLog("# %s\n", command_line);
+
+ // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal.
+ HistoryPos = -1;
+ for (int i = History.Size-1; i >= 0; i--)
+ if (Stricmp(History[i], command_line) == 0)
+ {
+ free(History[i]);
+ History.erase(History.begin() + i);
+ break;
+ }
+ History.push_back(Strdup(command_line));
+
+ // Process command
+ if (Stricmp(command_line, "CLEAR") == 0)
+ {
+ ClearLog();
+ }
+ else if (Stricmp(command_line, "HELP") == 0)
+ {
+ AddLog("Commands:");
+ for (int i = 0; i < Commands.Size; i++)
+ AddLog("- %s", Commands[i]);
+ }
+ else if (Stricmp(command_line, "HISTORY") == 0)
+ {
+ for (int i = History.Size >= 10 ? History.Size - 10 : 0; i < History.Size; i++)
+ AddLog("%3d: %s\n", i, History[i]);
+ }
+ else
+ {
+ AddLog("Unknown command: '%s'\n", command_line);
+ }
+ }
+
+ static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks
+ {
+ ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;
+ return console->TextEditCallback(data);
+ }
+
+ int TextEditCallback(ImGuiTextEditCallbackData* data)
+ {
+ //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd);
+ switch (data->EventFlag)
+ {
+ case ImGuiInputTextFlags_CallbackCompletion:
+ {
+ // Example of TEXT COMPLETION
+
+ // Locate beginning of current word
+ const char* word_end = data->Buf + data->CursorPos;
+ const char* word_start = word_end;
+ while (word_start > data->Buf)
+ {
+ const char c = word_start[-1];
+ if (c == ' ' || c == '\t' || c == ',' || c == ';')
+ break;
+ word_start--;
+ }
+
+ // Build a list of candidates
+ ImVector<const char*> candidates;
+ for (int i = 0; i < Commands.Size; i++)
+ if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0)
+ candidates.push_back(Commands[i]);
+
+ if (candidates.Size == 0)
+ {
+ // No match
+ AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start);
+ }
+ else if (candidates.Size == 1)
+ {
+ // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing
+ data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start));
+ data->InsertChars(data->CursorPos, candidates[0]);
+ data->InsertChars(data->CursorPos, " ");
+ }
+ else
+ {
+ // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY"
+ int match_len = (int)(word_end - word_start);
+ for (;;)
+ {
+ int c = 0;
+ bool all_candidates_matches = true;
+ for (int i = 0; i < candidates.Size && all_candidates_matches; i++)
+ if (i == 0)
+ c = toupper(candidates[i][match_len]);
+ else if (c != toupper(candidates[i][match_len]))
+ all_candidates_matches = false;
+ if (!all_candidates_matches)
+ break;
+ match_len++;
+ }
+
+ if (match_len > 0)
+ {
+ data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start));
+ data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
+ }
+
+ // List matches
+ AddLog("Possible matches:\n");
+ for (int i = 0; i < candidates.Size; i++)
+ AddLog("- %s\n", candidates[i]);
+ }
+
+ break;
+ }
+ case ImGuiInputTextFlags_CallbackHistory:
+ {
+ // Example of HISTORY
+ const int prev_history_pos = HistoryPos;
+ if (data->EventKey == ImGuiKey_UpArrow)
+ {
+ if (HistoryPos == -1)
+ HistoryPos = History.Size - 1;
+ else if (HistoryPos > 0)
+ HistoryPos--;
+ }
+ else if (data->EventKey == ImGuiKey_DownArrow)
+ {
+ if (HistoryPos != -1)
+ if (++HistoryPos >= History.Size)
+ HistoryPos = -1;
+ }
+
+ // A better implementation would preserve the data on the current input line along with cursor position.
+ if (prev_history_pos != HistoryPos)
+ {
+ data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : "");
+ data->BufDirty = true;
+ }
+ }
+ }
+ return 0;
+ }
+};
+
+static void ShowExampleAppConsole(bool* p_open)
+{
+ static ExampleAppConsole console;
+ console.Draw("Example: Console", p_open);
+}
+
+// Usage:
+// static ExampleAppLog my_log;
+// my_log.AddLog("Hello %d world\n", 123);
+// my_log.Draw("title");
+struct ExampleAppLog
+{
+ ImGuiTextBuffer Buf;
+ ImGuiTextFilter Filter;
+ ImVector<int> LineOffsets; // Index to lines offset
+ bool ScrollToBottom;
+
+ void Clear() { Buf.clear(); LineOffsets.clear(); }
+
+ void AddLog(const char* fmt, ...) IM_PRINTFARGS(2)
+ {
+ int old_size = Buf.size();
+ va_list args;
+ va_start(args, fmt);
+ Buf.appendv(fmt, args);
+ va_end(args);
+ for (int new_size = Buf.size(); old_size < new_size; old_size++)
+ if (Buf[old_size] == '\n')
+ LineOffsets.push_back(old_size);
+ ScrollToBottom = true;
+ }
+
+ void Draw(const char* title, bool* p_open = NULL)
+ {
+ ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver);
+ ImGui::Begin(title, p_open);
+ if (ImGui::Button("Clear")) Clear();
+ ImGui::SameLine();
+ bool copy = ImGui::Button("Copy");
+ ImGui::SameLine();
+ Filter.Draw("Filter", -100.0f);
+ ImGui::Separator();
+ ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar);
+ if (copy) ImGui::LogToClipboard();
+
+ if (Filter.IsActive())
+ {
+ const char* buf_begin = Buf.begin();
+ const char* line = buf_begin;
+ for (int line_no = 0; line != NULL; line_no++)
+ {
+ const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL;
+ if (Filter.PassFilter(line, line_end))
+ ImGui::TextUnformatted(line, line_end);
+ line = line_end && line_end[1] ? line_end + 1 : NULL;
+ }
+ }
+ else
+ {
+ ImGui::TextUnformatted(Buf.begin());
+ }
+
+ if (ScrollToBottom)
+ ImGui::SetScrollHere(1.0f);
+ ScrollToBottom = false;
+ ImGui::EndChild();
+ ImGui::End();
+ }
+};
+
+static void ShowExampleAppLog(bool* p_open)
+{
+ static ExampleAppLog log;
+
+ // Demo fill
+ static float last_time = -1.0f;
+ float time = ImGui::GetTime();
+ if (time - last_time >= 0.3f)
+ {
+ const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" };
+ log.AddLog("[%s] Hello, time is %.1f, rand() %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, (int)rand());
+ last_time = time;
+ }
+
+ log.Draw("Example: Log", p_open);
+}
+
+static void ShowExampleAppLayout(bool* p_open)
+{
+ ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiSetCond_FirstUseEver);
+ if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar))
+ {
+ if (ImGui::BeginMenuBar())
+ {
+ if (ImGui::BeginMenu("File"))
+ {
+ if (ImGui::MenuItem("Close")) *p_open = false;
+ ImGui::EndMenu();
+ }
+ ImGui::EndMenuBar();
+ }
+
+ // left
+ static int selected = 0;
+ ImGui::BeginChild("left pane", ImVec2(150, 0), true);
+ for (int i = 0; i < 100; i++)
+ {
+ char label[128];
+ sprintf(label, "MyObject %d", i);
+ if (ImGui::Selectable(label, selected == i))
+ selected = i;
+ }
+ ImGui::EndChild();
+ ImGui::SameLine();
+
+ // right
+ ImGui::BeginGroup();
+ ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing())); // Leave room for 1 line below us
+ ImGui::Text("MyObject: %d", selected);
+ ImGui::Separator();
+ ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
+ ImGui::EndChild();
+ ImGui::BeginChild("buttons");
+ if (ImGui::Button("Revert")) {}
+ ImGui::SameLine();
+ if (ImGui::Button("Save")) {}
+ ImGui::EndChild();
+ ImGui::EndGroup();
+ }
+ ImGui::End();
+}
+
+static void ShowExampleAppPropertyEditor(bool* p_open)
+{
+ ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiSetCond_FirstUseEver);
+ if (!ImGui::Begin("Example: Property editor", p_open))
+ {
+ ImGui::End();
+ return;
+ }
+
+ ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API.");
+
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2));
+ ImGui::Columns(2);
+ ImGui::Separator();
+
+ struct funcs
+ {
+ static void ShowDummyObject(const char* prefix, int uid)
+ {
+ ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.
+ ImGui::AlignFirstTextHeightToWidgets(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high.
+ bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid);
+ ImGui::NextColumn();
+ ImGui::AlignFirstTextHeightToWidgets();
+ ImGui::Text("my sailor is rich");
+ ImGui::NextColumn();
+ if (node_open)
+ {
+ static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f };
+ for (int i = 0; i < 8; i++)
+ {
+ ImGui::PushID(i); // Use field index as identifier.
+ if (i < 2)
+ {
+ ShowDummyObject("Child", 424242);
+ }
+ else
+ {
+ ImGui::AlignFirstTextHeightToWidgets();
+ // Here we use a Selectable (instead of Text) to highlight on hover
+ //ImGui::Text("Field_%d", i);
+ char label[32];
+ sprintf(label, "Field_%d", i);
+ ImGui::Bullet();
+ ImGui::Selectable(label);
+ ImGui::NextColumn();
+ ImGui::PushItemWidth(-1);
+ if (i >= 5)
+ ImGui::InputFloat("##value", &dummy_members[i], 1.0f);
+ else
+ ImGui::DragFloat("##value", &dummy_members[i], 0.01f);
+ ImGui::PopItemWidth();
+ ImGui::NextColumn();
+ }
+ ImGui::PopID();
+ }
+ ImGui::TreePop();
+ }
+ ImGui::PopID();
+ }
+ };
+
+ // Iterate dummy objects with dummy members (all the same data)
+ for (int obj_i = 0; obj_i < 3; obj_i++)
+ funcs::ShowDummyObject("Object", obj_i);
+
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::PopStyleVar();
+ ImGui::End();
+}
+
+static void ShowExampleAppLongText(bool* p_open)
+{
+ ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver);
+ if (!ImGui::Begin("Example: Long text display", p_open))
+ {
+ ImGui::End();
+ return;
+ }
+
+ static int test_type = 0;
+ static ImGuiTextBuffer log;
+ static int lines = 0;
+ ImGui::Text("Printing unusually long amount of text.");
+ ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped\0");
+ ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size());
+ if (ImGui::Button("Clear")) { log.clear(); lines = 0; }
+ ImGui::SameLine();
+ if (ImGui::Button("Add 1000 lines"))
+ {
+ for (int i = 0; i < 1000; i++)
+ log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i);
+ lines += 1000;
+ }
+ ImGui::BeginChild("Log");
+ switch (test_type)
+ {
+ case 0:
+ // Single call to TextUnformatted() with a big buffer
+ ImGui::TextUnformatted(log.begin(), log.end());
+ break;
+ case 1:
+ {
+ // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
+ ImGuiListClipper clipper(lines);
+ while (clipper.Step())
+ for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
+ ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
+ ImGui::PopStyleVar();
+ break;
+ }
+ case 2:
+ // Multiple calls to Text(), not clipped (slow)
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
+ for (int i = 0; i < lines; i++)
+ ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
+ ImGui::PopStyleVar();
+ break;
+ }
+ ImGui::EndChild();
+ ImGui::End();
+}
+
+// End of Demo code
+#else
+
+void ImGui::ShowTestWindow(bool*) {}
+void ImGui::ShowUserGuide() {}
+void ImGui::ShowStyleEditor(ImGuiStyle*) {}
+
+#endif
diff --git a/NvCloth/samples/external/imgui/1.49/imgui_draw.cpp b/NvCloth/samples/external/imgui/1.49/imgui_draw.cpp
new file mode 100644
index 0000000..63cf882
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/imgui_draw.cpp
@@ -0,0 +1,2377 @@
+// dear imgui, v1.49
+// (drawing and font code)
+
+// Contains implementation for
+// - ImDrawList
+// - ImDrawData
+// - ImFontAtlas
+// - ImFont
+// - Default font data
+
+#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "imgui.h"
+#define IMGUI_DEFINE_MATH_OPERATORS
+#define IMGUI_DEFINE_PLACEMENT_NEW
+#include "imgui_internal.h"
+
+#include <stdio.h> // vsnprintf, sscanf, printf
+#if !defined(alloca) && !defined(__FreeBSD__) && !defined(__DragonFly__)
+#ifdef _WIN32
+#include <malloc.h> // alloca
+#else
+#include <alloca.h> // alloca
+#endif
+#endif
+
+#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
+#define snprintf _snprintf
+#endif
+
+#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 //
+#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier //
+#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
+#endif
+
+//-------------------------------------------------------------------------
+// STB libraries implementation
+//-------------------------------------------------------------------------
+
+//#define IMGUI_STB_NAMESPACE ImGuiStb
+//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
+//#define IMGUI_DISABLE_STB_TRUETYPE_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 "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
+#pragma clang diagnostic ignored "-Wunused-function"
+#pragma clang diagnostic ignored "-Wmissing-prototypes"
+#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]
+#endif
+
+#define STBRP_ASSERT(x) IM_ASSERT(x)
+#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
+#define STBRP_STATIC
+#define STB_RECT_PACK_IMPLEMENTATION
+#endif
+#include "stb_rect_pack.h"
+
+#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)
+#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
+#define STBTT_STATIC
+#define STB_TRUETYPE_IMPLEMENTATION
+#else
+#define STBTT_DEF extern
+#endif
+#include "stb_truetype.h"
+
+#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
+
+//-----------------------------------------------------------------------------
+// ImDrawList
+//-----------------------------------------------------------------------------
+
+static const ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift
+
+void ImDrawList::Clear()
+{
+ CmdBuffer.resize(0);
+ IdxBuffer.resize(0);
+ VtxBuffer.resize(0);
+ _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();
+}
+
+// Use macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug mode
+#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : GNullClipRect)
+#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 (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 (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(GNullClipRect.x, GNullClipRect.y), ImVec2(GNullClipRect.z, GNullClipRect.w));
+ //PushClipRect(GetVisibleRect()); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiContext from here?
+}
+
+void ImDrawList::PopClipRect()
+{
+ IM_ASSERT(_ClipRectStack.Size > 0);
+ _ClipRectStack.pop_back();
+ UpdateClipRect();
+}
+
+void ImDrawList::PushTextureID(const 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 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; }
+ }
+ AddDrawCmd();
+ _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_size = VtxBuffer.Size;
+ VtxBuffer.resize(vtx_buffer_size + vtx_count);
+ _VtxWritePtr = VtxBuffer.Data + vtx_buffer_size;
+
+ int idx_buffer_size = IdxBuffer.Size;
+ IdxBuffer.resize(idx_buffer_size + idx_count);
+ _IdxWritePtr = IdxBuffer.Data + idx_buffer_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(GImGui->FontTexUvWhitePixel);
+ 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, bool anti_aliased)
+{
+ if (points_count < 2)
+ return;
+
+ const ImVec2 uv = GImGui->FontTexUvWhitePixel;
+ anti_aliased &= GImGui->Style.AntiAliasedLines;
+ //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug
+
+ int count = points_count;
+ if (!closed)
+ count = points_count-1;
+
+ const bool thick_line = thickness > 1.0f;
+ if (anti_aliased)
+ {
+ // Anti-aliased stroke
+ const float AA_SIZE = 1.0f;
+ const ImU32 col_trans = col & 0x00ffffff;
+
+ 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, bool anti_aliased)
+{
+ const ImVec2 uv = GImGui->FontTexUvWhitePixel;
+ anti_aliased &= GImGui->Style.AntiAliasedShapes;
+ //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug
+
+ if (anti_aliased)
+ {
+ // Anti-aliased Fill
+ const float AA_SIZE = 1.0f;
+ const ImU32 col_trans = col & 0x00ffffff;
+ 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 amin, int amax)
+{
+ static ImVec2 circle_vtx[12];
+ static bool circle_vtx_builds = false;
+ const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx);
+ if (!circle_vtx_builds)
+ {
+ for (int i = 0; i < circle_vtx_count; i++)
+ {
+ const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI;
+ circle_vtx[i].x = cosf(a);
+ circle_vtx[i].y = sinf(a);
+ }
+ circle_vtx_builds = true;
+ }
+
+ if (amin > amax) return;
+ if (radius == 0.0f)
+ {
+ _Path.push_back(centre);
+ }
+ else
+ {
+ _Path.reserve(_Path.Size + (amax - amin + 1));
+ for (int a = amin; a <= amax; a++)
+ {
+ const ImVec2& c = circle_vtx[a % circle_vtx_count];
+ _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius));
+ }
+ }
+}
+
+void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments)
+{
+ if (radius == 0.0f)
+ _Path.push_back(centre);
+ _Path.reserve(_Path.Size + (num_segments + 1));
+ for (int i = 0; i <= num_segments; i++)
+ {
+ const float a = amin + ((float)i / (float)num_segments) * (amax - amin);
+ _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(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, GImGui->Style.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)
+{
+ float r = rounding;
+ r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f);
+ r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f);
+
+ if (r <= 0.0f || rounding_corners == 0)
+ {
+ PathLineTo(a);
+ PathLineTo(ImVec2(b.x,a.y));
+ PathLineTo(b);
+ PathLineTo(ImVec2(a.x,b.y));
+ }
+ else
+ {
+ const float r0 = (rounding_corners & 1) ? r : 0.0f;
+ const float r1 = (rounding_corners & 2) ? r : 0.0f;
+ const float r2 = (rounding_corners & 4) ? r : 0.0f;
+ const float r3 = (rounding_corners & 8) ? r : 0.0f;
+ PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9);
+ PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12);
+ PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3);
+ PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6);
+ }
+}
+
+void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness)
+{
+ if ((col >> 24) == 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, float thickness)
+{
+ if ((col >> 24) == 0)
+ return;
+ PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners);
+ PathStroke(col, true, thickness);
+}
+
+void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners)
+{
+ if ((col >> 24) == 0)
+ return;
+ if (rounding > 0.0f)
+ {
+ PathRect(a, b, rounding, rounding_corners);
+ PathFill(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) >> 24) == 0)
+ return;
+
+ const ImVec2 uv = GImGui->FontTexUvWhitePixel;
+ 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 >> 24) == 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 >> 24) == 0)
+ return;
+
+ PathLineTo(a);
+ PathLineTo(b);
+ PathLineTo(c);
+ PathLineTo(d);
+ PathFill(col);
+}
+
+void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness)
+{
+ if ((col >> 24) == 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 >> 24) == 0)
+ return;
+
+ PathLineTo(a);
+ PathLineTo(b);
+ PathLineTo(c);
+ PathFill(col);
+}
+
+void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness)
+{
+ if ((col >> 24) == 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 >> 24) == 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);
+ PathFill(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 >> 24) == 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 >> 24) == 0)
+ return;
+
+ if (text_end == NULL)
+ text_end = text_begin + strlen(text_begin);
+ if (text_begin == text_end)
+ return;
+
+ // Note: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful.
+ // Might just move Font/FontSize to ImDrawList?
+ if (font == NULL)
+ font = GImGui->Font;
+ if (font_size == 0.0f)
+ font_size = GImGui->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(GImGui->Font, GImGui->FontSize, pos, col, text_begin, text_end);
+}
+
+void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col)
+{
+ if ((col >> 24) == 0)
+ return;
+
+ // FIXME-OPT: This is wasting draw calls.
+ 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, uv0, uv1, col);
+
+ if (push_texture_id)
+ PopTextureID();
+}
+
+//-----------------------------------------------------------------------------
+// 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);
+ }
+ }
+}
+
+//-----------------------------------------------------------------------------
+// ImFontAtlas
+//-----------------------------------------------------------------------------
+
+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);
+ GlyphRanges = NULL;
+ MergeMode = false;
+ MergeGlyphCenterV = false;
+ DstFont = NULL;
+ memset(Name, 0, sizeof(Name));
+}
+
+ImFontAtlas::ImFontAtlas()
+{
+ TexID = NULL;
+ TexPixelsAlpha8 = NULL;
+ TexPixelsRGBA32 = NULL;
+ TexWidth = TexHeight = TexDesiredWidth = 0;
+ TexUvWhitePixel = ImVec2(0, 0);
+}
+
+ImFontAtlas::~ImFontAtlas()
+{
+ Clear();
+}
+
+void ImFontAtlas::ClearInputData()
+{
+ 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();
+}
+
+void ImFontAtlas::ClearTexData()
+{
+ if (TexPixelsAlpha8)
+ ImGui::MemFree(TexPixelsAlpha8);
+ if (TexPixelsRGBA32)
+ ImGui::MemFree(TexPixelsRGBA32);
+ TexPixelsAlpha8 = NULL;
+ TexPixelsRGBA32 = NULL;
+}
+
+void ImFontAtlas::ClearFonts()
+{
+ for (int i = 0; i < Fonts.Size; i++)
+ {
+ Fonts[i]->~ImFont();
+ ImGui::MemFree(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;
+ GetTexDataAsAlpha8(&pixels, NULL, NULL);
+ 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++ = ((unsigned int)(*src++) << 24) | 0x00FFFFFF;
+ }
+
+ *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(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);
+ IM_ASSERT(font_cfg->SizePixels > 0.0f);
+
+ // Create new font
+ if (!font_cfg->MergeMode)
+ {
+ ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont));
+ IM_PLACEMENT_NEW(font) ImFont();
+ Fonts.push_back(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 extra_fonts/binary_to_compressed_c.cpp for encoder)
+static unsigned int stb_decompress_length(unsigned char *input);
+static unsigned int stb_decompress(unsigned char *output, unsigned char *i, 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-endianess.
+ 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, "<default>");
+
+ const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
+ ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault());
+ return font;
+}
+
+ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
+{
+ int data_size = 0;
+ void* data = ImLoadFileToMemory(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--) {}
+ snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p);
+ }
+ return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges);
+}
+
+// NBM 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)
+{
+ 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((unsigned char*)compressed_ttf_data);
+ unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size);
+ stb_decompress(buf_decompressed_data, (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;
+}
+
+bool ImFontAtlas::Build()
+{
+ IM_ASSERT(ConfigData.Size > 0);
+
+ TexID = NULL;
+ TexWidth = TexHeight = 0;
+ TexUvWhitePixel = ImVec2(0, 0);
+ ClearTexData();
+
+ struct ImFontTempBuildData
+ {
+ stbtt_fontinfo FontInfo;
+ stbrp_rect* Rects;
+ stbtt_pack_range* Ranges;
+ int RangesCount;
+ };
+ ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData));
+
+ // Initialize font information early (so we can error without any cleanup) + count glyphs
+ int total_glyph_count = 0;
+ int total_glyph_range_count = 0;
+ for (int input_i = 0; input_i < ConfigData.Size; input_i++)
+ {
+ ImFontConfig& cfg = ConfigData[input_i];
+ ImFontTempBuildData& tmp = tmp_array[input_i];
+
+ IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this));
+ const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo);
+ IM_ASSERT(font_offset >= 0);
+ if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))
+ return false;
+
+ // Count glyphs
+ if (!cfg.GlyphRanges)
+ cfg.GlyphRanges = GetGlyphRangesDefault();
+ for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2)
+ {
+ total_glyph_count += (in_range[1] - in_range[0]) + 1;
+ total_glyph_range_count++;
+ }
+ }
+
+ // Start packing. We need a known width for the skyline algorithm. Using a cheap heuristic here to decide of width. User can override TexDesiredWidth if they wish.
+ // After packing is done, width shouldn't matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
+ TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 4000) ? 4096 : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512;
+ TexHeight = 0;
+ const int max_tex_height = 1024*32;
+ stbtt_pack_context spc;
+ stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL);
+
+ // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
+ ImVector<stbrp_rect> extra_rects;
+ RenderCustomTexData(0, &extra_rects);
+ stbtt_PackSetOversampling(&spc, 1, 1);
+ stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size);
+ for (int i = 0; i < extra_rects.Size; i++)
+ if (extra_rects[i].was_packed)
+ TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h);
+
+ // 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_glyph_count * sizeof(stbtt_packedchar));
+ stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect));
+ stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range));
+ memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar));
+ memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity.
+ memset(buf_ranges, 0, total_glyph_range_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 < ConfigData.Size; input_i++)
+ {
+ ImFontConfig& cfg = ConfigData[input_i];
+ ImFontTempBuildData& tmp = tmp_array[input_i];
+
+ // Setup ranges
+ int glyph_count = 0;
+ int glyph_ranges_count = 0;
+ for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2)
+ {
+ glyph_count += (in_range[1] - in_range[0]) + 1;
+ glyph_ranges_count++;
+ }
+ tmp.Ranges = buf_ranges + buf_ranges_n;
+ tmp.RangesCount = glyph_ranges_count;
+ buf_ranges_n += glyph_ranges_count;
+ for (int i = 0; i < glyph_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;
+ }
+
+ // Pack
+ tmp.Rects = buf_rects + buf_rects_n;
+ buf_rects_n += glyph_count;
+ stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV);
+ int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects);
+ stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n);
+
+ // Extend texture height
+ for (int i = 0; i < n; i++)
+ if (tmp.Rects[i].was_packed)
+ TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h);
+ }
+ IM_ASSERT(buf_rects_n == total_glyph_count);
+ IM_ASSERT(buf_packedchars_n == total_glyph_count);
+ IM_ASSERT(buf_ranges_n == total_glyph_range_count);
+
+ // Create texture
+ TexHeight = ImUpperPowerOfTwo(TexHeight);
+ TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight);
+ memset(TexPixelsAlpha8, 0, TexWidth * TexHeight);
+ spc.pixels = TexPixelsAlpha8;
+ spc.height = TexHeight;
+
+ // Second pass: render characters
+ for (int input_i = 0; input_i < ConfigData.Size; input_i++)
+ {
+ ImFontConfig& cfg = 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);
+ 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 < ConfigData.Size; input_i++)
+ {
+ ImFontConfig& cfg = ConfigData[input_i];
+ ImFontTempBuildData& tmp = tmp_array[input_i];
+ ImFont* dst_font = cfg.DstFont;
+
+ 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);
+
+ float ascent = unscaled_ascent * font_scale;
+ float descent = unscaled_descent * font_scale;
+ if (!cfg.MergeMode)
+ {
+ dst_font->ContainerAtlas = this;
+ dst_font->ConfigData = &cfg;
+ dst_font->ConfigDataCount = 0;
+ dst_font->FontSize = cfg.SizePixels;
+ dst_font->Ascent = ascent;
+ dst_font->Descent = descent;
+ dst_font->Glyphs.resize(0);
+ }
+ dst_font->ConfigDataCount++;
+ float off_y = (cfg.MergeMode && cfg.MergeGlyphCenterV) ? (ascent - dst_font->Ascent) * 0.5f : 0.0f;
+
+ dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable()
+ 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->FindGlyph((unsigned short)codepoint))
+ continue;
+
+ stbtt_aligned_quad q;
+ float dummy_x = 0.0f, dummy_y = 0.0f;
+ stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0);
+
+ dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1);
+ ImFont::Glyph& glyph = dst_font->Glyphs.back();
+ glyph.Codepoint = (ImWchar)codepoint;
+ glyph.X0 = q.x0; glyph.Y0 = q.y0; glyph.X1 = q.x1; glyph.Y1 = q.y1;
+ glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1;
+ glyph.Y0 += (float)(int)(dst_font->Ascent + off_y + 0.5f);
+ glyph.Y1 += (float)(int)(dst_font->Ascent + off_y + 0.5f);
+ glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance
+ if (cfg.PixelSnapH)
+ glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f);
+ }
+ }
+ cfg.DstFont->BuildLookupTable();
+ }
+
+ // Cleanup temporaries
+ ImGui::MemFree(buf_packedchars);
+ ImGui::MemFree(buf_ranges);
+ ImGui::MemFree(tmp_array);
+
+ // Render into our custom data block
+ RenderCustomTexData(1, &extra_rects);
+
+ return true;
+}
+
+void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects)
+{
+ // 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 TEX_DATA_W = 90;
+ const int TEX_DATA_H = 27;
+ const char texture_data[TEX_DATA_W*TEX_DATA_H+1] =
+ {
+ "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX"
+ "..- -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"
+ "XX - 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..X - X.X - X.X - X.X -XX X.X - X.X XX"
+ "X...X - X.X - X.X - 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 - X.X - X..X X.X X..X - X.X - X.X "
+ "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-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...XXXXXX.XXXXXX...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......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X "
+ "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX "
+ "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------"
+ "X.X X..X - -X.......X- X.......X - XX XX - "
+ "XX 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 - "
+ "------------ - X - X -X.....................X- "
+ " ----------------------------------- X...XXXXXXXXXXXXX...X - "
+ " - X..X X..X - "
+ " - X.X X.X - "
+ " - XX XX - "
+ };
+
+ ImVector<stbrp_rect>& rects = *(ImVector<stbrp_rect>*)p_rects;
+ if (pass == 0)
+ {
+ // Request rectangles
+ stbrp_rect r;
+ memset(&r, 0, sizeof(r));
+ r.w = (TEX_DATA_W*2)+1;
+ r.h = TEX_DATA_H+1;
+ rects.push_back(r);
+ }
+ else if (pass == 1)
+ {
+ // Render/copy pixels
+ const stbrp_rect& r = rects[0];
+ for (int y = 0, n = 0; y < TEX_DATA_H; y++)
+ for (int x = 0; x < TEX_DATA_W; x++, n++)
+ {
+ const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth;
+ const int offset1 = offset0 + 1 + TEX_DATA_W;
+ TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00;
+ TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00;
+ }
+ const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight);
+ TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y);
+
+ // Setup mouse cursors
+ const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] =
+ {
+ // Pos ........ Size ......... Offset ......
+ { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow
+ { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput
+ { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move
+ { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS
+ { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW
+ { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW
+ { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE
+ };
+
+ for (int type = 0; type < ImGuiMouseCursor_Count_; type++)
+ {
+ ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type];
+ ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y);
+ const ImVec2 size = cursor_datas[type][1];
+ cursor_data.Type = type;
+ cursor_data.Size = size;
+ cursor_data.HotOffset = cursor_datas[type][2];
+ cursor_data.TexUvMin[0] = (pos) * tex_uv_scale;
+ cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale;
+ pos.x += TEX_DATA_W+1;
+ cursor_data.TexUvMin[1] = (pos) * tex_uv_scale;
+ cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale;
+ }
+ }
+}
+
+// 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::GetGlyphRangesChinese()
+{
+ 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];
+}
+
+const ImWchar* ImFontAtlas::GetGlyphRangesJapanese()
+{
+ // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1.
+ // This encoding helps us reduce the source code size.
+ static const short offsets_from_0x4E00[] =
+ {
+ -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17,
+ 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1,
+ 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0,
+ 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19,
+ 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48,
+ 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14,
+ 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14,
+ 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0,
+ 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0,
+ 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0,
+ 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7,
+ 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20,
+ 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2,
+ 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11,
+ 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27,
+ 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0,
+ 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14,
+ 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0,
+ 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26,
+ 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20,
+ 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23,
+ 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10,
+ 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21,
+ 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4,
+ 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6,
+ 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5,
+ 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11,
+ 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0,
+ 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6,
+ 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2,
+ 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20,
+ 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38,
+ };
+ static ImWchar base_ranges[] =
+ {
+ 0x0020, 0x00FF, // Basic Latin + Latin Supplement
+ 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana
+ 0x31F0, 0x31FF, // Katakana Phonetic Extensions
+ 0xFF00, 0xFFEF, // Half-width characters
+ };
+ static bool full_ranges_unpacked = false;
+ static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1];
+ if (!full_ranges_unpacked)
+ {
+ // Unpack
+ int codepoint = 0x4e00;
+ memcpy(full_ranges, base_ranges, sizeof(base_ranges));
+ ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);;
+ for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2)
+ dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1));
+ dst[0] = 0;
+ full_ranges_unpacked = true;
+ }
+ 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];
+}
+
+//-----------------------------------------------------------------------------
+// ImFont
+//-----------------------------------------------------------------------------
+
+ImFont::ImFont()
+{
+ Scale = 1.0f;
+ FallbackChar = (ImWchar)'?';
+ Clear();
+}
+
+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;
+ */
+ Clear();
+}
+
+void ImFont::Clear()
+{
+ FontSize = 0.0f;
+ DisplayOffset = ImVec2(0.0f, 1.0f);
+ ConfigData = NULL;
+ ConfigDataCount = 0;
+ Ascent = Descent = 0.0f;
+ ContainerAtlas = NULL;
+ Glyphs.clear();
+ FallbackGlyph = NULL;
+ FallbackXAdvance = 0.0f;
+ IndexXAdvance.clear();
+ IndexLookup.clear();
+}
+
+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 < 32*1024);
+ IndexXAdvance.clear();
+ IndexLookup.clear();
+ GrowIndex(max_codepoint + 1);
+ for (int i = 0; i < Glyphs.Size; i++)
+ {
+ int codepoint = (int)Glyphs[i].Codepoint;
+ IndexXAdvance[codepoint] = Glyphs[i].XAdvance;
+ IndexLookup[codepoint] = (short)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((unsigned short)' '))
+ {
+ if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times
+ Glyphs.resize(Glyphs.Size + 1);
+ ImFont::Glyph& tab_glyph = Glyphs.back();
+ tab_glyph = *FindGlyph((unsigned short)' ');
+ tab_glyph.Codepoint = '\t';
+ tab_glyph.XAdvance *= 4;
+ IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance;
+ IndexLookup[(int)tab_glyph.Codepoint] = (short)(Glyphs.Size-1);
+ }
+
+ FallbackGlyph = NULL;
+ FallbackGlyph = FindGlyph(FallbackChar);
+ FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f;
+ for (int i = 0; i < max_codepoint + 1; i++)
+ if (IndexXAdvance[i] < 0.0f)
+ IndexXAdvance[i] = FallbackXAdvance;
+}
+
+void ImFont::SetFallbackChar(ImWchar c)
+{
+ FallbackChar = c;
+ BuildLookupTable();
+}
+
+void ImFont::GrowIndex(int new_size)
+{
+ IM_ASSERT(IndexXAdvance.Size == IndexLookup.Size);
+ int old_size = IndexLookup.Size;
+ if (new_size <= old_size)
+ return;
+ IndexXAdvance.resize(new_size);
+ IndexLookup.resize(new_size);
+ for (int i = old_size; i < new_size; i++)
+ {
+ IndexXAdvance[i] = -1.0f;
+ IndexLookup[i] = (short)-1;
+ }
+}
+
+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] == -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] : -1;
+ IndexXAdvance[dst] = (src < index_size) ? IndexXAdvance.Data[src] : 1.0f;
+}
+
+const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const
+{
+ if (c < IndexLookup.Size)
+ {
+ const short i = IndexLookup[c];
+ if (i != -1)
+ return &Glyphs.Data[i];
+ }
+ return FallbackGlyph;
+}
+
+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;
+
+ 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 < IndexXAdvance.Size) ? IndexXAdvance[(int)c] * scale : FallbackXAdvance;
+ if (ImCharIsSpace(c))
+ {
+ if (inside_word)
+ {
+ line_width += blank_width;
+ blank_width = 0.0f;
+ }
+ 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 (ImCharIsSpace(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)
+ 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 < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * 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, unsigned short c) const
+{
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded.
+ return;
+ if (const Glyph* 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;
+ ImVec2 pos_tl(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale);
+ ImVec2 pos_br(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale);
+ draw_list->PrimReserve(6, 4);
+ draw_list->PrimRectUV(pos_tl, pos_br, 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);
+
+ // 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;
+
+ // Skip non-visible lines
+ const char* s = text_begin;
+ if (!word_wrap_enabled && y + line_height < clip_rect.y)
+ while (s < text_end && *s != '\n') // Fast-forward to next line
+ s++;
+
+ // 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 (ImCharIsSpace(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)
+ break;
+ }
+
+ if (c < 32)
+ {
+ if (c == '\n')
+ {
+ x = pos.x;
+ y += line_height;
+
+ if (y > clip_rect.w)
+ break;
+ if (!word_wrap_enabled && y + line_height < clip_rect.y)
+ while (s < text_end && *s != '\n') // Fast-forward to next line
+ s++;
+ continue;
+ }
+ if (c == '\r')
+ continue;
+ }
+
+ float char_width = 0.0f;
+ if (const Glyph* glyph = FindGlyph((unsigned short)c))
+ {
+ char_width = glyph->XAdvance * 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 build.
+ // 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;
+}
+
+//-----------------------------------------------------------------------------
+// DEFAULT FONT DATA
+//-----------------------------------------------------------------------------
+// Compressed with stb_compress() then converted to a C array.
+// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file.
+// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h
+//-----------------------------------------------------------------------------
+
+static unsigned int stb_decompress_length(unsigned char *input)
+{
+ return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];
+}
+
+static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4;
+static unsigned char *stb__dout;
+static void stb__match(unsigned char *data, unsigned int length)
+{
+ // INVERSE of memmove... write each byte before copying the next...
+ IM_ASSERT (stb__dout + length <= stb__barrier);
+ if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
+ if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }
+ while (length--) *stb__dout++ = *data++;
+}
+
+static void stb__lit(unsigned char *data, unsigned int length)
+{
+ IM_ASSERT (stb__dout + length <= stb__barrier);
+ if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
+ if (data < stb__barrier2) { stb__dout = stb__barrier+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 unsigned char *stb_decompress_token(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, 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__barrier2 = i;
+ stb__barrier3 = i+length;
+ stb__barrier = output + olen;
+ stb__barrier4 = output;
+ i += 16;
+
+ stb__dout = output;
+ for (;;) {
+ 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;
+ }
+}
+
+//-----------------------------------------------------------------------------
+// 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 binary_to_compressed_c.cpp
+//-----------------------------------------------------------------------------
+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^#[email protected]<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL"
+ "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#[email protected]'[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<[email protected];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^;[email protected]$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/NvCloth/samples/external/imgui/1.49/imgui_internal.h b/NvCloth/samples/external/imgui/1.49/imgui_internal.h
new file mode 100644
index 0000000..c641c45
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/imgui_internal.h
@@ -0,0 +1,754 @@
+// dear imgui, v1.49
+// (internals)
+
+// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
+// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
+// #define IMGUI_DEFINE_MATH_OPERATORS
+
+#pragma once
+
+#ifndef IMGUI_VERSION
+#error Must include imgui.h before imgui_internal.h
+#endif
+
+#include <stdio.h> // FILE*
+#include <math.h> // sqrtf()
+
+#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;
+struct ImGuiColMod;
+struct ImGuiStyleMod;
+struct ImGuiGroupData;
+struct ImGuiSimpleColumns;
+struct ImGuiDrawContext;
+struct ImGuiTextEditState;
+struct ImGuiIniData;
+struct ImGuiMouseCursorData;
+struct ImGuiPopupRef;
+struct ImGuiWindow;
+
+typedef int ImGuiLayoutType; // enum ImGuiLayoutType_
+typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_
+typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_
+typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_
+
+//-------------------------------------------------------------------------
+// STB libraries
+//-------------------------------------------------------------------------
+
+namespace ImGuiStb
+{
+
+#undef STB_TEXTEDIT_STRING
+#undef STB_TEXTEDIT_CHARTYPE
+#define STB_TEXTEDIT_STRING ImGuiTextEditState
+#define STB_TEXTEDIT_CHARTYPE ImWchar
+#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f
+#include "stb_textedit.h"
+
+} // namespace ImGuiStb
+
+//-----------------------------------------------------------------------------
+// Context
+//-----------------------------------------------------------------------------
+
+extern IMGUI_API ImGuiContext* GImGui; // current implicit ImGui context pointer
+
+//-----------------------------------------------------------------------------
+// Helpers
+//-----------------------------------------------------------------------------
+
+#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
+#define IM_PI 3.14159265358979323846f
+
+// 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); // 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 ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points
+
+// 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* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0);
+IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c);
+static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; }
+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; }
+
+// Helpers: String
+IMGUI_API int ImStricmp(const char* str1, const char* str2);
+IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count);
+IMGUI_API char* ImStrdup(const char* str);
+IMGUI_API int ImStrlenW(const ImWchar* str);
+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 int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3);
+IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args);
+
+// Helpers: Math
+// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined)
+#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); }
+#endif
+
+static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; }
+static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; }
+static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; }
+static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; }
+static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); }
+static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); }
+static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
+static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
+static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); }
+static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
+static inline float ImLerp(float a, float b, float t) { return a + (b - a) * 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 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 / sqrtf(d); return fail_value; }
+static inline float ImFloor(float f) { return (float)(int)f; }
+static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
+
+// 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.
+#ifdef IMGUI_DEFINE_PLACEMENT_NEW
+struct ImPlacementNewDummy {};
+inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; }
+inline void operator delete(void*, ImPlacementNewDummy, void*) {}
+#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR)
+#endif
+
+//-----------------------------------------------------------------------------
+// Types
+//-----------------------------------------------------------------------------
+
+enum ImGuiButtonFlags_
+{
+ ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
+ ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set)
+ ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release)
+ ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release)
+ ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release)
+ ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping
+ ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press
+ ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction
+ ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only
+ ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held
+ ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable
+};
+
+enum ImGuiSliderFlags_
+{
+ ImGuiSliderFlags_Vertical = 1 << 0
+};
+
+enum ImGuiSelectableFlagsPrivate_
+{
+ // NB: need to be in sync with last value of ImGuiSelectableFlags_
+ ImGuiSelectableFlags_Menu = 1 << 3,
+ ImGuiSelectableFlags_MenuItem = 1 << 4,
+ ImGuiSelectableFlags_Disabled = 1 << 5,
+ ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6
+};
+
+// FIXME: this is in development, not exposed/functional as a generic feature yet.
+enum ImGuiLayoutType_
+{
+ ImGuiLayoutType_Vertical,
+ ImGuiLayoutType_Horizontal
+};
+
+enum ImGuiPlotType
+{
+ ImGuiPlotType_Lines,
+ ImGuiPlotType_Histogram
+};
+
+enum ImGuiDataType
+{
+ ImGuiDataType_Int,
+ ImGuiDataType_Float
+};
+
+// 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& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; }
+ void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.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 Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; }
+ void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; }
+ 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; }
+ ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const
+ {
+ if (!on_edge && Contains(p))
+ return p;
+ if (p.x > Max.x) p.x = Max.x;
+ else if (p.x < Min.x) p.x = Min.x;
+ if (p.y > Max.y) p.y = Max.y;
+ else if (p.y < Min.y) p.y = Min.y;
+ return p;
+ }
+};
+
+// Stacked color modifier, backup of modified data so we can restore it
+struct ImGuiColMod
+{
+ ImGuiCol Col;
+ ImVec4 PreviousValue;
+};
+
+// Stacked style modifier, backup of modified data so we can restore it
+struct ImGuiStyleMod
+{
+ ImGuiStyleVar Var;
+ ImVec2 PreviousValue;
+};
+
+// Stacked data for BeginGroup()/EndGroup()
+struct ImGuiGroupData
+{
+ ImVec2 BackupCursorPos;
+ ImVec2 BackupCursorMaxPos;
+ float BackupIndentX;
+ float BackupCurrentLineHeight;
+ float BackupCurrentLineTextBaseOffset;
+ float BackupLogLinePosY;
+ bool AdvanceCursor;
+};
+
+// Per column data for Columns()
+struct ImGuiColumnData
+{
+ float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
+ //float IndentX;
+};
+
+// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper.
+struct IMGUI_API ImGuiSimpleColumns
+{
+ int Count;
+ float Spacing;
+ float Width, NextWidth;
+ float Pos[8], NextWidths[8];
+
+ ImGuiSimpleColumns();
+ 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 ImGuiTextEditState
+{
+ ImGuiID Id; // widget id owning the text state
+ ImVector<ImWchar> Text; // 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> TempTextBuffer;
+ int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format.
+ int BufSizeA; // end-user buffer size
+ float ScrollX;
+ ImGuiStb::STB_TexteditState StbState;
+ float CursorAnim;
+ bool CursorFollow;
+ bool SelectedAllMouseLock;
+
+ ImGuiTextEditState() { 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.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; }
+ void OnKeyPressed(int key);
+};
+
+// Data saved in imgui.ini file
+struct ImGuiIniData
+{
+ char* Name;
+ ImGuiID ID;
+ ImVec2 Pos;
+ ImVec2 Size;
+ bool Collapsed;
+};
+
+// Mouse cursor data (used when io.MouseDrawCursor is set)
+struct ImGuiMouseCursorData
+{
+ ImGuiMouseCursor Type;
+ ImVec2 HotOffset;
+ ImVec2 Size;
+ ImVec2 TexUvMin[2];
+ ImVec2 TexUvMax[2];
+};
+
+// 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()
+ ImGuiID ParentMenuSet; // Set on OpenPopup()
+ ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup
+
+ ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupID = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; }
+};
+
+// Main state for ImGui
+struct ImGuiContext
+{
+ bool Initialized;
+ ImGuiIO IO;
+ ImGuiStyle Style;
+ ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
+ float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize()
+ float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters.
+ ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel
+
+ float Time;
+ int FrameCount;
+ int FrameCountEnded;
+ int FrameCountRendered;
+ ImVector<ImGuiWindow*> Windows;
+ ImVector<ImGuiWindow*> WindowsSortBuffer;
+ ImGuiWindow* CurrentWindow; // Being drawn into
+ ImVector<ImGuiWindow*> CurrentWindowStack;
+ ImGuiWindow* FocusedWindow; // Will catch keyboard inputs
+ ImGuiWindow* HoveredWindow; // Will catch mouse inputs
+ ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
+ ImGuiID HoveredId; // Hovered widget
+ bool HoveredIdAllowOverlap;
+ ImGuiID HoveredIdPreviousFrame;
+ ImGuiID ActiveId; // Active widget
+ ImGuiID ActiveIdPreviousFrame;
+ bool ActiveIdIsAlive;
+ bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
+ bool ActiveIdAllowOverlap; // Set only by active widget
+ ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
+ ImGuiWindow* ActiveIdWindow;
+ ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window.
+ ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId
+ ImVector<ImGuiIniData> Settings; // .ini Settings
+ float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero
+ ImVector<ImGuiColMod> 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)
+
+ // Storage for SetNexWindow** and SetNextTreeNode*** functions
+ ImVec2 SetNextWindowPosVal;
+ ImVec2 SetNextWindowSizeVal;
+ ImVec2 SetNextWindowContentSizeVal;
+ bool SetNextWindowCollapsedVal;
+ ImGuiSetCond SetNextWindowPosCond;
+ ImGuiSetCond SetNextWindowSizeCond;
+ ImGuiSetCond SetNextWindowContentSizeCond;
+ ImGuiSetCond SetNextWindowCollapsedCond;
+ ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true
+ ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback;
+ void* SetNextWindowSizeConstraintCallbackUserData;
+ bool SetNextWindowSizeConstraint;
+ bool SetNextWindowFocus;
+ bool SetNextTreeNodeOpenVal;
+ ImGuiSetCond SetNextTreeNodeOpenCond;
+
+ // Render
+ ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user
+ ImVector<ImDrawList*> RenderDrawLists[3];
+ float ModalWindowDarkeningRatio;
+ ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays
+ ImGuiMouseCursor MouseCursor;
+ ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_];
+
+ // Widget state
+ ImGuiTextEditState InputTextState;
+ ImFont InputTextPasswordFont;
+ ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc.
+ ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode
+ float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings
+ ImVec2 DragLastMouseDelta;
+ float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
+ float DragSpeedScaleSlow;
+ float DragSpeedScaleFast;
+ ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
+ char Tooltip[1024];
+ char* PrivateClipboard; // If no custom clipboard handler is defined
+ ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor
+
+ // Logging
+ bool LogEnabled;
+ FILE* LogFile; // If != NULL log to stdout/ file
+ ImGuiTextBuffer* LogClipboard; // Else 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
+ int FramerateSecPerFrameIdx;
+ float FramerateSecPerFrameAccum;
+ int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags
+ int CaptureKeyboardNextFrame;
+ char TempBuffer[1024*3+1]; // temporary text buffer
+
+ ImGuiContext()
+ {
+ Initialized = false;
+ Font = NULL;
+ FontSize = FontBaseSize = 0.0f;
+ FontTexUvWhitePixel = ImVec2(0.0f, 0.0f);
+
+ Time = 0.0f;
+ FrameCount = 0;
+ FrameCountEnded = FrameCountRendered = -1;
+ CurrentWindow = NULL;
+ FocusedWindow = NULL;
+ HoveredWindow = NULL;
+ HoveredRootWindow = NULL;
+ HoveredId = 0;
+ HoveredIdAllowOverlap = false;
+ HoveredIdPreviousFrame = 0;
+ ActiveId = 0;
+ ActiveIdPreviousFrame = 0;
+ ActiveIdIsAlive = false;
+ ActiveIdIsJustActivated = false;
+ ActiveIdAllowOverlap = false;
+ ActiveIdClickOffset = ImVec2(-1,-1);
+ ActiveIdWindow = NULL;
+ MovedWindow = NULL;
+ MovedWindowMoveId = 0;
+ SettingsDirtyTimer = 0.0f;
+
+ SetNextWindowPosVal = ImVec2(0.0f, 0.0f);
+ SetNextWindowSizeVal = ImVec2(0.0f, 0.0f);
+ SetNextWindowCollapsedVal = false;
+ SetNextWindowPosCond = 0;
+ SetNextWindowSizeCond = 0;
+ SetNextWindowContentSizeCond = 0;
+ SetNextWindowCollapsedCond = 0;
+ SetNextWindowFocus = false;
+ SetNextWindowSizeConstraintCallback = NULL;
+ SetNextWindowSizeConstraintCallbackUserData = NULL;
+ SetNextTreeNodeOpenVal = false;
+ SetNextTreeNodeOpenCond = 0;
+
+ ScalarAsInputTextId = 0;
+ DragCurrentValue = 0.0f;
+ DragLastMouseDelta = ImVec2(0.0f, 0.0f);
+ DragSpeedDefaultRatio = 0.01f;
+ DragSpeedScaleSlow = 0.01f;
+ DragSpeedScaleFast = 10.0f;
+ ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f);
+ memset(Tooltip, 0, sizeof(Tooltip));
+ PrivateClipboard = NULL;
+ OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f);
+
+ ModalWindowDarkeningRatio = 0.0f;
+ OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
+ MouseCursor = ImGuiMouseCursor_Arrow;
+ memset(MouseCursorData, 0, sizeof(MouseCursorData));
+
+ LogEnabled = false;
+ LogFile = NULL;
+ LogClipboard = NULL;
+ LogStartDepth = 0;
+ LogAutoExpandMaxDepth = 2;
+
+ memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
+ FramerateSecPerFrameIdx = 0;
+ FramerateSecPerFrameAccum = 0.0f;
+ CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1;
+ memset(TempBuffer, 0, sizeof(TempBuffer));
+ }
+};
+
+// Transient per-window data, reset at the beginning of the frame
+// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered.
+struct IMGUI_API ImGuiDrawContext
+{
+ ImVec2 CursorPos;
+ ImVec2 CursorPosPrevLine;
+ ImVec2 CursorStartPos;
+ ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame
+ float CurrentLineHeight;
+ float CurrentLineTextBaseOffset;
+ float PrevLineHeight;
+ float PrevLineTextBaseOffset;
+ float LogLinePosY;
+ int TreeDepth;
+ ImGuiID LastItemID;
+ ImRect LastItemRect;
+ bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window)
+ bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window)
+ bool MenuBarAppending;
+ float MenuBarOffsetX;
+ ImVector<ImGuiWindow*> ChildWindows;
+ ImGuiStorage* StateStorage;
+ ImGuiLayoutType LayoutType;
+
+ // 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.
+ 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]
+ bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true]
+ bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false]
+ ImVector<float> ItemWidthStack;
+ ImVector<float> TextWrapPosStack;
+ ImVector<bool> AllowKeyboardFocusStack;
+ ImVector<bool> ButtonRepeatStack;
+ ImVector<ImGuiGroupData>GroupStack;
+ ImGuiColorEditMode ColorEditMode;
+ int StackSizesBackup[6]; // Store size of various stacks for asserting
+
+ float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
+ float ColumnsOffsetX; // 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.
+ int ColumnsCurrent;
+ int ColumnsCount;
+ float ColumnsMinX;
+ float ColumnsMaxX;
+ float ColumnsStartPosY;
+ float ColumnsCellMinY;
+ float ColumnsCellMaxY;
+ bool ColumnsShowBorders;
+ ImGuiID ColumnsSetID;
+ ImVector<ImGuiColumnData> ColumnsData;
+
+ ImGuiDrawContext()
+ {
+ CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f);
+ CurrentLineHeight = PrevLineHeight = 0.0f;
+ CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
+ LogLinePosY = -1.0f;
+ TreeDepth = 0;
+ LastItemID = 0;
+ LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f);
+ LastItemHoveredAndUsable = LastItemHoveredRect = false;
+ MenuBarAppending = false;
+ MenuBarOffsetX = 0.0f;
+ StateStorage = NULL;
+ LayoutType = ImGuiLayoutType_Vertical;
+ ItemWidth = 0.0f;
+ ButtonRepeat = false;
+ AllowKeyboardFocus = true;
+ TextWrapPos = -1.0f;
+ ColorEditMode = ImGuiColorEditMode_RGB;
+ memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
+
+ IndentX = 0.0f;
+ ColumnsOffsetX = 0.0f;
+ ColumnsCurrent = 0;
+ ColumnsCount = 1;
+ ColumnsMinX = ColumnsMaxX = 0.0f;
+ ColumnsStartPosY = 0.0f;
+ ColumnsCellMinY = ColumnsCellMaxY = 0.0f;
+ ColumnsShowBorders = true;
+ ColumnsSetID = 0;
+ }
+};
+
+// Windows data
+struct IMGUI_API ImGuiWindow
+{
+ char* Name;
+ ImGuiID ID; // == ImHash(Name)
+ ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_
+ int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0.
+ ImVec2 PosFloat;
+ ImVec2 Pos; // Position rounded-up to nearest pixel
+ ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
+ ImVec2 SizeFull; // Size when non collapsed
+ ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame
+ ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize()
+ ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis
+ ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect
+ ImGuiID MoveID; // == window->GetID("#MOVE")
+ 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
+ bool ScrollbarX, ScrollbarY;
+ ImVec2 ScrollbarSizes;
+ float BorderSize;
+ bool Active; // Set to true on Begin()
+ bool WasActive;
+ bool Accessed; // Set to true when any widget access the current window
+ bool Collapsed; // Set when collapsing window to become only title-bar
+ bool SkipItems; // == Visible && !Collapsed
+ int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
+ 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 AutoPosLastDirection;
+ int HiddenFrames;
+ int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag.
+ int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag.
+ int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag.
+ bool SetWindowPosCenterWanted;
+
+ ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame
+ ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack
+ ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2.
+ ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window.
+ int LastFrameActive;
+ float ItemWidthDefault;
+ ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items
+ ImGuiStorage StateStorage;
+ float FontWindowScale; // Scale multiplier per-window
+ ImDrawList* DrawList;
+ ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself.
+ ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself.
+ ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL.
+
+ // Focus
+ 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(const char* name);
+ ~ImGuiWindow();
+
+ ImGuiID GetID(const char* str, const char* str_end = NULL);
+ ImGuiID GetID(const void* ptr);
+
+ 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) ? 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()); }
+};
+
+//-----------------------------------------------------------------------------
+// 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::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->Accessed = true; return g.CurrentWindow; }
+ IMGUI_API ImGuiWindow* GetParentWindow();
+ IMGUI_API ImGuiWindow* FindWindowByName(const char* name);
+ IMGUI_API void FocusWindow(ImGuiWindow* window);
+
+ IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead!
+
+ IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
+ IMGUI_API void SetHoveredID(ImGuiID id);
+ IMGUI_API void KeepAliveID(ImGuiID id);
+
+ 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, const ImGuiID* id);
+ IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged);
+ IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false);
+ IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, 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 OpenPopupEx(const char* str_id, bool reopen_existing);
+
+ inline IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul) { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ImGui::ColorConvertFloat4ToU32(c); }
+ inline IMGUI_API ImU32 GetColorU32(const ImVec4& col) { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); }
+
+ // NB: All position are in absolute pixels coordinates (not window coordinates)
+ // FIXME: All those functions are a mess and needs to be refactored into something decent. Avoid use outside of imgui.cpp!
+ // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers.
+ 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, ImGuiAlign align = ImGuiAlign_Default, const ImVec2* clip_min = NULL, const ImVec2* clip_max = NULL);
+ IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
+ IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f, bool shadow = false);
+ IMGUI_API void RenderBullet(ImVec2 pos);
+ IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col);
+ IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
+
+ IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);
+ 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 SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0);
+ IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power);
+ IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format);
+
+ IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power);
+ IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power);
+ IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format);
+
+ IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL);
+ IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags);
+ IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags);
+ IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags);
+ IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision);
+
+ 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);
+
+ 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);
+
+ IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value);
+ IMGUI_API float RoundScalar(float value, int decimal_precision);
+
+} // namespace ImGui
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+#ifdef _MSC_VER
+#pragma warning (pop)
+#endif
diff --git a/NvCloth/samples/external/imgui/1.49/stb_rect_pack.h b/NvCloth/samples/external/imgui/1.49/stb_rect_pack.h
new file mode 100644
index 0000000..fafd889
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/stb_rect_pack.h
@@ -0,0 +1,573 @@
+// stb_rect_pack.h - v0.08 - 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
+// Bugfixes / warning fixes
+// Jeremy Jaussaud
+//
+// Version history:
+//
+// 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
+//
+// This software is in the public domain. Where that dedication is not
+// recognized, you are granted a perpetual, irrevocable license to copy,
+// distribute, and modify this file as you see fit.
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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 void 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.
+
+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
+
+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 *, stbrp_node *first, int x0, int width, int *pwaste)
+{
+ //(void)c;
+ stbrp_node *node = first;
+ int x1 = x0 + width;
+ int min_y, visited_width, waste_area;
+ 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);
+
+ {
+ stbrp_node *L1 = NULL, *L2 = NULL;
+ int count=0;
+ cur = context->active_head;
+ while (cur) {
+ L1 = cur;
+ cur = cur->next;
+ ++count;
+ }
+ cur = context->free_head;
+ while (cur) {
+ L2 = cur;
+ cur = cur->next;
+ ++count;
+ }
+ STBRP_ASSERT(count == context->num_nodes+2);
+ }
+#endif
+
+ return res;
+}
+
+static int rect_height_compare(const void *a, const void *b)
+{
+ stbrp_rect *p = (stbrp_rect *) a;
+ stbrp_rect *q = (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 rect_width_compare(const void *a, const void *b)
+{
+ stbrp_rect *p = (stbrp_rect *) a;
+ stbrp_rect *q = (stbrp_rect *) b;
+ if (p->w > q->w)
+ return -1;
+ if (p->w < q->w)
+ return 1;
+ return (p->h > q->h) ? -1 : (p->h < q->h);
+}
+
+static int rect_original_order(const void *a, const void *b)
+{
+ stbrp_rect *p = (stbrp_rect *) a;
+ stbrp_rect *q = (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 void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
+{
+ int i;
+
+ // 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
+ for (i=0; i < num_rects; ++i)
+ rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
+}
+#endif
diff --git a/NvCloth/samples/external/imgui/1.49/stb_textedit.h b/NvCloth/samples/external/imgui/1.49/stb_textedit.h
new file mode 100644
index 0000000..3c30032
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/stb_textedit.h
@@ -0,0 +1,1317 @@
+// [ImGui] this is a slightly modified version of stb_truetype.h 1.8
+// [ImGui] - fixed some minor warnings
+// [ImGui] - added STB_TEXTEDIT_MOVEWORDLEFT/STB_TEXTEDIT_MOVEWORDRIGHT custom handler (#473)
+
+// stb_textedit.h - v1.8 - 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
+//
+// This software is dual-licensed to the public domain and under the following
+// license: you are granted a perpetual, irrevocable license to copy, modify,
+// publish, and distribute this file as you see fit.
+//
+//
+// 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.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
+//
+// Bugfixes:
+// Scott Graham
+// Daniel Keller
+// Omar Cornut
+//
+// 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 + 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 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, int 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.
+//
+// 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;
+ short insert_length;
+ short delete_length;
+ short 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;
+ short 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'
+ k = i;
+ prev_x = r.x0;
+ for (i=0; i < r.num_chars; ++i) {
+ float w = STB_TEXTEDIT_GETWIDTH(str, k, i);
+ 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)
+{
+ 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 = stb_text_locate_coord(str, x, y);
+ if (state->select_start == state->select_end)
+ state->select_start = state->cursor;
+ 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 )
+{
+ 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);
+ 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(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)
+{
+ STB_TEXTEDIT_CHARTYPE *text = (STB_TEXTEDIT_CHARTYPE *) ctext;
+ // 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;
+}
+
+// API key: process a keyboard input
+static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int 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-1);
+ 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-1);
+ 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+1);
+ 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+1);
+ 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: {
+ StbFindState find;
+ stb_textedit_clamp(str, state);
+ stb_textedit_move_to_first(state);
+ stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
+ state->cursor = find.first_char;
+ state->has_preferred_x = 0;
+ break;
+ }
+
+#ifdef STB_TEXTEDIT_K_LINEEND2
+ case STB_TEXTEDIT_K_LINEEND2:
+#endif
+ case STB_TEXTEDIT_K_LINEEND: {
+ StbFindState find;
+ stb_textedit_clamp(str, state);
+ stb_textedit_move_to_first(state);
+ stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
+
+ state->has_preferred_x = 0;
+ state->cursor = find.first_char + find.length;
+ if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE)
+ --state->cursor;
+ 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: {
+ StbFindState find;
+ stb_textedit_clamp(str, state);
+ stb_textedit_prep_selection_at_cursor(state);
+ stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
+ state->cursor = state->select_end = find.first_char;
+ 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: {
+ StbFindState find;
+ stb_textedit_clamp(str, state);
+ stb_textedit_prep_selection_at_cursor(state);
+ stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);
+ state->has_preferred_x = 0;
+ state->cursor = find.first_char + find.length;
+ if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE)
+ --state->cursor;
+ state->select_end = state->cursor;
+ 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 = state->undo_char_point - (short) n; // vsnet05
+ STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) ((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 = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it
+ }
+ --state->undo_point;
+ STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((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;
+ // delete n characters from all other records
+ state->redo_char_point = state->redo_char_point + (short) n; // vsnet05
+ STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));
+ for (i=state->redo_point; i < k; ++i)
+ if (state->undo_rec[i].char_storage >= 0)
+ state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05
+ }
+ ++state->redo_point;
+ STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0])));
+ }
+}
+
+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 = (short) insert_len;
+ r->delete_length = (short) delete_len;
+
+ if (insert_len == 0) {
+ r->char_storage = -1;
+ return NULL;
+ } else {
+ r->char_storage = state->undo_char_point;
+ state->undo_char_point = state->undo_char_point + (short) 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) {
+ // there's currently not enough room, so discard a redo record
+ stb_textedit_discard_redo(s);
+ // should never happen:
+ if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)
+ return;
+ }
+ 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 - (short) 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);
+ }
+
+ 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);
+}
+#endif//STB_TEXTEDIT_IMPLEMENTATION
diff --git a/NvCloth/samples/external/imgui/1.49/stb_truetype.h b/NvCloth/samples/external/imgui/1.49/stb_truetype.h
new file mode 100644
index 0000000..e6dae97
--- /dev/null
+++ b/NvCloth/samples/external/imgui/1.49/stb_truetype.h
@@ -0,0 +1,3263 @@
+// stb_truetype.h - v1.10 - public domain
+// authored from 2009-2015 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)
+//
+// 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
+//
+// Misc other:
+// Ryan Gordon
+// Simon Glass
+//
+// Bug/warning reports/fixes:
+// "Zer" on mollyrocket (with fix)
+// Cass Everitt
+// stoiko (Haemimont Games)
+// Brian Hook
+// Walter van Niftrik
+// David Gow
+// David Given
+// Ivan-Assen Ivanov
+// Anthony Pesch
+// Johan Duparc
+// Hou Qiming
+// Fabian "ryg" Giesen
+// Martins Mozeiko
+// Cap Petschulat
+// Omar Cornut
+// github:aloucks
+// Peter LaValle
+// Sergey Popov
+// Giumo X. Clanjor
+// Higor Euripedes
+// Thomas Fields
+// Derek Vinyard
+//
+// VERSION HISTORY
+//
+// 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
+// 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
+//
+// Full history can be found at the end of this file.
+//
+// LICENSE
+//
+// This software is dual-licensed to the public domain and under the following
+// license: you are granted a perpetual, irrevocable license to copy, modify,
+// publish, and distribute this file as you see fit.
+//
+// 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_PackSetOversample() -- 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() -- use 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_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 they 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.
+//
+// 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.
+
+#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];
+
+ // #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)
+ #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 <memory.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
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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(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 weight x 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, 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, 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(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, 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, 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_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. You can just skip
+// this step if you know it's that kind of font.
+
+
+// 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; // 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_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 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
+ };
+#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;
+ 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_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_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
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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
+
+//////////////////////////////////////////////////////////////////////////
+//
+// 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)
+
+#if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
+
+ #define ttUSHORT(p) (* (stbtt_uint16 *) (p))
+ #define ttSHORT(p) (* (stbtt_int16 *) (p))
+ #define ttULONG(p) (* (stbtt_uint32 *) (p))
+ #define ttLONG(p) (* (stbtt_int32 *) (p))
+
+#else
+
+ static stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
+ static stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
+ static stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
+ static stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
+
+#endif
+
+#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(const 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
+ 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;
+}
+
+STBTT_DEF int stbtt_GetFontOffsetForIndex(const 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;
+}
+
+STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
+{
+ stbtt_uint8 *data = (stbtt_uint8 *) data2;
+ stbtt_uint32 cmap, t;
+ stbtt_int32 i,numTables;
+
+ info->data = data;
+ info->fontstart = fontstart;
+
+ 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
+ if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
+ return 0;
+
+ 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;
+
+ 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
+}
+
+STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
+{
+ 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 = 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;
+}
+
+STBTT_DEF int stbtt_GetGlyphShape(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;
+}
+
+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));
+ }
+}
+
+STBTT_DEF int stbtt_GetGlyphKernAdvance(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;
+}
+
+STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
+{
+ if (!info->kern) // 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 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) + 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 clear pairs
+ float y0 = y_top;
+ float x1 = (float) (x);
+ float x2 = (float) (x+1);
+ float x3 = xb;
+ float y3 = y_bottom;
+ float y1,y2;
+
+ // x = e->x + e->dx * (y-y_top)
+ // (y-y_top) = (x - e->x) / e->dx
+ // y = (x - e->x) / e->dx + y_top
+ y1 = (x - x0) / dx + y_top;
+ 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)
+{
+ (void)vsubsample;
+ stbtt__hheap hh = { 0, 0, 0 };
+ stbtt__active_edge *active = NULL;
+ int y,j=0, i;
+ float scanline_data[129], *scanline, *scanline2;
+
+ 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;
+}
+
+// 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;
+ }
+ }
+ (*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, *winding_lengths;
+ 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_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
+
+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)
+{
+ 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(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;
+ 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
+#ifdef _MSC_VER
+#define STBTT__NOTUSED(v) (void)(v)
+#else
+#define STBTT__NOTUSED(v) (void)sizeof(v)
+#endif
+
+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, 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;
+}
+
+// rects array must be big enough to accommodate all characters in the given ranges
+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, 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, 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, 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(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;
+ 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;
+}
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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(const stbtt_uint8 *s1, stbtt_int32 len1, const 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;
+}
+
+STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
+{
+ return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const 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((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;
+}
+
+STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const 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;
+ }
+}
+
+#endif // STB_TRUETYPE_IMPLEMENTATION
+
+
+// FULL VERSION HISTORY
+//
+// 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
+//
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/bin/Win32/nvToolsExt32_1.dll b/NvCloth/samples/external/nvToolsExt/1.0/bin/Win32/nvToolsExt32_1.dll
new file mode 100644
index 0000000..6ef0014
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/bin/Win32/nvToolsExt32_1.dll
Binary files differ
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/bin/armv7/libnvToolsExt.so b/NvCloth/samples/external/nvToolsExt/1.0/bin/armv7/libnvToolsExt.so
new file mode 100644
index 0000000..e2c6c11
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/bin/armv7/libnvToolsExt.so
Binary files differ
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/bin/x64/nvToolsExt64_1.dll b/NvCloth/samples/external/nvToolsExt/1.0/bin/x64/nvToolsExt64_1.dll
new file mode 100644
index 0000000..918a29a
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/bin/x64/nvToolsExt64_1.dll
Binary files differ
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExt.h b/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExt.h
new file mode 100644
index 0000000..9eb696e
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExt.h
@@ -0,0 +1,674 @@
+/*
+* Copyright 2009-2012 NVIDIA Corporation. All rights reserved.
+*
+* NOTICE TO USER:
+*
+* This source code is subject to NVIDIA ownership rights under U.S. and
+* international Copyright laws.
+*
+* This software and the information contained herein is PROPRIETARY and
+* CONFIDENTIAL to NVIDIA and is being provided under the terms and conditions
+* of a form of NVIDIA software license agreement.
+*
+* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
+* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
+* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
+* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
+* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
+* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
+* OR PERFORMANCE OF THIS SOURCE CODE.
+*
+* U.S. Government End Users. This source code is a "commercial item" as
+* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
+* "commercial computer software" and "commercial computer software
+* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
+* and is provided to the U.S. Government only as a commercial end item.
+* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
+* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
+* source code with only those rights set forth herein.
+*
+* Any use of this source code in individual and commercial software must
+* include, in the user documentation and internal comments to the code,
+* the above Disclaimer and U.S. Government End Users Notice.
+*/
+
+/** \mainpage
+ * \section Introduction
+ * The NVIDIA Tools Extension library is a set of functions that a
+ * developer can use to provide additional information to tools.
+ * The additional information is used by the tool to improve
+ * analysis and visualization of data.
+ *
+ * The library introduces close to zero overhead if no tool is
+ * attached to the application. The overhead when a tool is
+ * attached is specific to the tool.
+ */
+
+#ifndef NVTOOLSEXT_H_
+#define NVTOOLSEXT_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#if defined(_MSC_VER) /* Microsoft Visual C++ Compiler */
+ #ifdef NVTX_EXPORTS
+ #define NVTX_DECLSPEC
+ #else
+ #define NVTX_DECLSPEC __declspec(dllimport)
+ #endif /* NVTX_EXPORTS */
+ #define NVTX_API __stdcall
+#else /* GCC and most other compilers */
+ #define NVTX_DECLSPEC
+ #define NVTX_API
+#endif /* Platform */
+
+/**
+ * The nvToolsExt library depends on stdint.h. If the build tool chain in use
+ * does not include stdint.h then define NVTX_STDINT_TYPES_ALREADY_DEFINED
+ * and define the following types:
+ * <ul>
+ * <li>uint8_t
+ * <li>int8_t
+ * <li>uint16_t
+ * <li>int16_t
+ * <li>uint32_t
+ * <li>int32_t
+ * <li>uint64_t
+ * <li>int64_t
+ * <li>uintptr_t
+ * <li>intptr_t
+ * </ul>
+ #define NVTX_STDINT_TYPES_ALREADY_DEFINED if you are using your own header file.
+ */
+#ifndef NVTX_STDINT_TYPES_ALREADY_DEFINED
+#include <stdint.h>
+#endif
+
+/**
+ * Tools Extension API version
+ */
+#define NVTX_VERSION 1
+
+/**
+ * Size of the nvtxEventAttributes_t structure.
+ */
+#define NVTX_EVENT_ATTRIB_STRUCT_SIZE ( (uint16_t)( sizeof(nvtxEventAttributes_v1) ) )
+
+typedef uint64_t nvtxRangeId_t;
+
+/** \page EVENT_ATTRIBUTES Event Attributes
+ *
+ * \ref MARKER_AND_RANGES can be annotated with various attributes to provide
+ * additional information for an event or to guide the tool's visualization of
+ * the data. Each of the attributes is optional and if left unused the
+ * attributes fall back to a default value.
+ *
+ * To specify any attribute other than the text message, the \ref
+ * EVENT_ATTRIBUTE_STRUCTURE "Event Attribute Structure" must be used.
+ */
+
+/** ---------------------------------------------------------------------------
+ * Color Types
+ * ------------------------------------------------------------------------- */
+typedef enum nvtxColorType_t
+{
+ NVTX_COLOR_UNKNOWN = 0, /**< Color attribute is unused. */
+ NVTX_COLOR_ARGB = 1 /**< An ARGB color is provided. */
+} nvtxColorType_t;
+
+/** ---------------------------------------------------------------------------
+ * Payload Types
+ * ------------------------------------------------------------------------- */
+typedef enum nvtxPayloadType_t
+{
+ NVTX_PAYLOAD_UNKNOWN = 0, /**< Color payload is unused. */
+ NVTX_PAYLOAD_TYPE_UNSIGNED_INT64 = 1, /**< A unsigned integer value is used as payload. */
+ NVTX_PAYLOAD_TYPE_INT64 = 2, /**< A signed integer value is used as payload. */
+ NVTX_PAYLOAD_TYPE_DOUBLE = 3 /**< A floating point value is used as payload. */
+} nvtxPayloadType_t;
+
+/** ---------------------------------------------------------------------------
+ * Message Types
+ * ------------------------------------------------------------------------- */
+typedef enum nvtxMessageType_t
+{
+ NVTX_MESSAGE_UNKNOWN = 0, /**< Message payload is unused. */
+ NVTX_MESSAGE_TYPE_ASCII = 1, /**< A character sequence is used as payload. */
+ NVTX_MESSAGE_TYPE_UNICODE = 2 /**< A wide character sequence is used as payload. */
+} nvtxMessageType_t;
+
+/** \brief Event Attribute Structure.
+ * \anchor EVENT_ATTRIBUTE_STRUCTURE
+ *
+ * This structure is used to describe the attributes of an event. The layout of
+ * the structure is defined by a specific version of the tools extension
+ * library and can change between different versions of the Tools Extension
+ * library.
+ *
+ * \par Initializing the Attributes
+ *
+ * The caller should always perform the following three tasks when using
+ * attributes:
+ * <ul>
+ * <li>Zero the structure
+ * <li>Set the version field
+ * <li>Set the size field
+ * </ul>
+ *
+ * Zeroing the structure sets all the event attributes types and values
+ * to the default value.
+ *
+ * The version and size field are used by the Tools Extension
+ * implementation to handle multiple versions of the attributes structure.
+ *
+ * It is recommended that the caller use one of the following to methods
+ * to initialize the event attributes structure:
+ *
+ * \par Method 1: Initializing nvtxEventAttributes for future compatibility
+ * \code
+ * nvtxEventAttributes_t eventAttrib = {0};
+ * eventAttrib.version = NVTX_VERSION;
+ * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE;
+ * \endcode
+ *
+ * \par Method 2: Initializing nvtxEventAttributes for a specific version
+ * \code
+ * nvtxEventAttributes_t eventAttrib = {0};
+ * eventAttrib.version = 1;
+ * eventAttrib.size = (uint16_t)(sizeof(nvtxEventAttributes_v1));
+ * \endcode
+ *
+ * If the caller uses Method 1 it is critical that the entire binary
+ * layout of the structure be configured to 0 so that all fields
+ * are initialized to the default value.
+ *
+ * The caller should either use both NVTX_VERSION and
+ * NVTX_EVENT_ATTRIB_STRUCT_SIZE (Method 1) or use explicit values
+ * and a versioned type (Method 2). Using a mix of the two methods
+ * will likely cause either source level incompatibility or binary
+ * incompatibility in the future.
+ *
+ * \par Settings Attribute Types and Values
+ *
+ *
+ * \par Example:
+ * \code
+ * // Initialize
+ * nvtxEventAttributes_t eventAttrib = {0};
+ * eventAttrib.version = NVTX_VERSION;
+ * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE;
+ *
+ * // Configure the Attributes
+ * eventAttrib.colorType = NVTX_COLOR_ARGB;
+ * eventAttrib.color = 0xFF880000;
+ * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII;
+ * eventAttrib.message.ascii = "Example";
+ * \endcode
+ *
+ * In the example the caller does not have to set the value of
+ * \ref ::nvtxEventAttributes_v1::category or
+ * \ref ::nvtxEventAttributes_v1::payload as these fields were set to
+ * the default value by {0}.
+ * \sa
+ * ::nvtxMarkEx
+ * ::nvtxRangeStartEx
+ * ::nvtxRangePushEx
+ */
+typedef struct nvtxEventAttributes_v1
+{
+ /**
+ * \brief Version flag of the structure.
+ *
+ * Needs to be set to NVTX_VERSION to indicate the version of NVTX APIs
+ * supported in this header file. This can optionally be overridden to
+ * another version of the tools extension library.
+ */
+ uint16_t version;
+
+ /**
+ * \brief Size of the structure.
+ *
+ * Needs to be set to the size in bytes of the event attribute
+ * structure used to specify the event.
+ */
+ uint16_t size;
+
+ /**
+ * \brief ID of the category the event is assigned to.
+ *
+ * A category is a user-controlled ID that can be used to group
+ * events. The tool may use category IDs to improve filtering or
+ * enable grouping of events in the same category. The functions
+ * \ref ::nvtxNameCategoryA or \ref ::nvtxNameCategoryW can be used
+ * to name a category.
+ *
+ * Default Value is 0
+ */
+ uint32_t category;
+
+ /** \brief Color type specified in this attribute structure.
+ *
+ * Defines the color format of the attribute structure's \ref COLOR_FIELD
+ * "color" field.
+ *
+ * Default Value is NVTX_COLOR_UNKNOWN
+ */
+ int32_t colorType; /* nvtxColorType_t */
+
+ /** \brief Color assigned to this event. \anchor COLOR_FIELD
+ *
+ * The color that the tool should use to visualize the event.
+ */
+ uint32_t color;
+
+ /**
+ * \brief Payload type specified in this attribute structure.
+ *
+ * Defines the payload format of the attribute structure's \ref PAYLOAD_FIELD
+ * "payload" field.
+ *
+ * Default Value is NVTX_PAYLOAD_UNKNOWN
+ */
+ int32_t payloadType; /* nvtxPayloadType_t */
+
+ /**
+ * \brief Payload assigned to this event. \anchor PAYLOAD_FIELD
+ *
+ * A numerical value that can be used to annotate an event. The tool could
+ * use the payload data to reconstruct graphs and diagrams.
+ */
+ union payload_t
+ {
+ uint64_t ullValue;
+ int64_t llValue;
+ double dValue;
+ } payload;
+
+ /** \brief Message type specified in this attribute structure.
+ *
+ * Defines the message format of the attribute structure's \ref MESSAGE_FIELD
+ * "message" field.
+ *
+ * Default Value is NVTX_MESSAGE_UNKNOWN
+ */
+ int32_t messageType; /* nvtxMessageType_t */
+
+ /** \brief Message assigned to this attribute structure. \anchor MESSAGE_FIELD
+ *
+ * The text message that is attached to an event.
+ */
+ union message_t
+ {
+ const char* ascii;
+ const wchar_t* unicode;
+ } message;
+
+} nvtxEventAttributes_v1;
+
+typedef struct nvtxEventAttributes_v1 nvtxEventAttributes_t;
+
+/* ========================================================================= */
+/** \defgroup MARKER_AND_RANGES Marker and Ranges
+ *
+ * Markers and ranges are used to describe events at a specific time (markers)
+ * or over a time span (ranges) during the execution of the application
+ * respectively. The additional information is presented alongside all other
+ * captured data and facilitates understanding of the collected information.
+ */
+
+/* ========================================================================= */
+/** \name Markers
+ */
+/** \name Markers
+ */
+/** \addtogroup MARKER_AND_RANGES
+ * \section MARKER Marker
+ *
+ * A marker describes a single point in time. A marker event has no side effect
+ * on other events.
+ *
+ * @{
+ */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks an instantaneous event in the application.
+ *
+ * A marker can contain a text message or specify additional information
+ * using the event attributes structure. These attributes include a text
+ * message, color, category, and a payload. Each of the attributes is optional
+ * and can only be sent out using the \ref nvtxMarkEx function.
+ * If \ref nvtxMarkA or \ref nvtxMarkW are used to specify the the marker
+ * or if an attribute is unspecified then a default value will be used.
+ *
+ * \param eventAttrib - The event attribute structure defining the marker's
+ * attribute types and attribute values.
+ *
+ * \par Example:
+ * \code
+ * // zero the structure
+ * nvtxEventAttributes_t eventAttrib = {0};
+ * // set the version and the size information
+ * eventAttrib.version = NVTX_VERSION;
+ * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE;
+ * // configure the attributes. 0 is the default for all attributes.
+ * eventAttrib.colorType = NVTX_COLOR_ARGB;
+ * eventAttrib.color = 0xFF880000;
+ * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII;
+ * eventAttrib.message.ascii = "Example nvtxMarkEx";
+ * nvtxMarkEx(&eventAttrib);
+ * \endcode
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxMarkEx(const nvtxEventAttributes_t* eventAttrib);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks an instantaneous event in the application.
+ *
+ * A marker created using \ref nvtxMarkA or \ref nvtxMarkW contains only a
+ * text message.
+ *
+ * \param message - The message associated to this marker event.
+ *
+ * \par Example:
+ * \code
+ * nvtxMarkA("Example nvtxMarkA");
+ * nvtxMarkW(L"Example nvtxMarkW");
+ * \endcode
+ *
+ * \version \NVTX_VERSION_0
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxMarkA(const char* message);
+NVTX_DECLSPEC void NVTX_API nvtxMarkW(const wchar_t* message);
+/** @} */
+
+/** @} */ /* END MARKER_AND_RANGES */
+
+/* ========================================================================= */
+/** \name Start/Stop Ranges
+ */
+/** \addtogroup MARKER_AND_RANGES
+ * \section INDEPENDENT_RANGES Start/Stop Ranges
+ *
+ * Start/Stop ranges denote a time span that can expose arbitrary concurrency -
+ * opposed to Push/Pop ranges that only support nesting. In addition the start
+ * of a range can happen on a different thread than the end. For the
+ * correlation of a start/end pair an unique correlation ID is used that is
+ * returned from the start API call and needs to be passed into the end API
+ * call.
+ *
+ * @{
+ */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks the start of a range.
+ *
+ * \param eventAttrib - The event attribute structure defining the range's
+ * attribute types and attribute values.
+ *
+ * \return The unique ID used to correlate a pair of Start and End events.
+ *
+ * \remarks Ranges defined by Start/End can overlap.
+ *
+ * \par Example:
+ * \code
+ * nvtxEventAttributes_t eventAttrib = {0};
+ * eventAttrib.version = NVTX_VERSION;
+ * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE;
+ * eventAttrib.category = 3;
+ * eventAttrib.colorType = NVTX_COLOR_ARGB;
+ * eventAttrib.color = 0xFF0088FF;
+ * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII;
+ * eventAttrib.message.ascii = "Example RangeStartEnd";
+ * nvtxRangeId_t rangeId = nvtxRangeStartEx(&eventAttrib);
+ * // ...
+ * nvtxRangeEnd(rangeId);
+ * \endcode
+ *
+ * \sa
+ * ::nvtxRangeEnd
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxRangeStartEx(const nvtxEventAttributes_t* eventAttrib);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks the start of a range.
+ *
+ * \param message - The event message associated to this range event.
+ *
+ * \return The unique ID used to correlate a pair of Start and End events.
+ *
+ * \remarks Ranges defined by Start/End can overlap.
+ *
+ * \par Example:
+ * \code
+ * nvtxRangeId_t r1 = nvtxRangeStartA("Range 1");
+ * nvtxRangeId_t r2 = nvtxRangeStartW(L"Range 2");
+ * nvtxRangeEnd(r1);
+ * nvtxRangeEnd(r2);
+ * \endcode
+ * \sa
+ * ::nvtxRangeEnd
+ *
+ * \version \NVTX_VERSION_0
+ * @{ */
+NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxRangeStartA(const char* message);
+NVTX_DECLSPEC nvtxRangeId_t NVTX_API nvtxRangeStartW(const wchar_t* message);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks the end of a range.
+ *
+ * \param id - The correlation ID returned from a nvtxRangeStart call.
+ *
+ * \sa
+ * ::nvtxRangeStartEx
+ * ::nvtxRangeStartA
+ * ::nvtxRangeStartW
+ *
+ * \version \NVTX_VERSION_0
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxRangeEnd(nvtxRangeId_t id);
+/** @} */
+
+/** @} */
+
+
+/* ========================================================================= */
+/** \name Push/Pop Ranges
+ */
+/** \addtogroup MARKER_AND_RANGES
+ * \section PUSH_POP_RANGES Push/Pop Ranges
+ *
+ * Push/Pop ranges denote nested time ranges. Nesting is maintained per thread
+ * and does not require any additional correlation mechanism. The duration of a
+ * push/pop range is defined by the corresponding pair of Push/Pop API calls.
+ *
+ * @{
+ */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks the start of a nested range
+ *
+ * \param eventAttrib - The event attribute structure defining the range's
+ * attribute types and attribute values.
+ *
+ * \return The 0 based level of range being started. If an error occurs a
+ * negative value is returned.
+ *
+ * \par Example:
+ * \code
+ * nvtxEventAttributes_t eventAttrib = {0};
+ * eventAttrib.version = NVTX_VERSION;
+ * eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE;
+ * eventAttrib.colorType = NVTX_COLOR_ARGB;
+ * eventAttrib.color = 0xFFFF0000;
+ * eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII;
+ * eventAttrib.message.ascii = "Level 0";
+ * nvtxRangePushEx(&eventAttrib);
+ *
+ * // Re-use eventAttrib
+ * eventAttrib.messageType = NVTX_MESSAGE_TYPE_UNICODE;
+ * eventAttrib.message.unicode = L"Level 1";
+ * nvtxRangePushEx(&eventAttrib);
+ *
+ * nvtxRangePop();
+ * nvtxRangePop();
+ * \endcode
+ *
+ * \sa
+ * ::nvtxRangePop
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC int NVTX_API nvtxRangePushEx(const nvtxEventAttributes_t* eventAttrib);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks the start of a nested range
+ *
+ * \param message - The event message associated to this range event.
+ *
+ * \return The 0 based level of range being started. If an error occurs a
+ * negative value is returned.
+ *
+ * \par Example:
+ * \code
+ * nvtxRangePushA("Level 0");
+ * nvtxRangePushW(L"Level 1");
+ * nvtxRangePop();
+ * nvtxRangePop();
+ * \endcode
+ *
+ * \sa
+ * ::nvtxRangePop
+ *
+ * \version \NVTX_VERSION_0
+ * @{ */
+NVTX_DECLSPEC int NVTX_API nvtxRangePushA(const char* message);
+NVTX_DECLSPEC int NVTX_API nvtxRangePushW(const wchar_t* message);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Marks the end of a nested range
+ *
+ * \return The level of the range being ended. If an error occurs a negative
+ * value is returned on the current thread.
+ *
+ * \sa
+ * ::nvtxRangePushEx
+ * ::nvtxRangePushA
+ * ::nvtxRangePushW
+ *
+ * \version \NVTX_VERSION_0
+ * @{ */
+NVTX_DECLSPEC int NVTX_API nvtxRangePop(void);
+/** @} */
+
+/** @} */
+
+/* ========================================================================= */
+/** \defgroup RESOURCE_NAMING Resource Naming
+ *
+ * This section covers calls that allow to annotate objects with user-provided
+ * names in order to allow for a better analysis of complex trace data. All of
+ * the functions take the handle or the ID of the object to name and the name.
+ * The functions can be called multiple times during the execution of an
+ * application, however, in that case it is implementation dependent which
+ * name will be reported by the tool.
+ *
+ * \section RESOURCE_NAMING_NVTX NVTX Resource Naming
+ * The NVIDIA Tools Extension library allows to attribute events with additional
+ * information such as category IDs. These category IDs can be annotated with
+ * user-provided names using the respective resource naming functions.
+ *
+ * \section RESOURCE_NAMING_OS OS Resource Naming
+ * In order to enable a tool to report system threads not just by their thread
+ * identifier, the NVIDIA Tools Extension library allows to provide user-given
+ * names to these OS resources.
+ * @{
+ */
+
+/* ------------------------------------------------------------------------- */
+/** \name Functions for NVTX Resource Naming
+ */
+/** @{
+ * \brief Annotate an NVTX category.
+ *
+ * Categories are used to group sets of events. Each category is identified
+ * through a unique ID and that ID is passed into any of the marker/range
+ * events to assign that event to a specific category. The nvtxNameCategory
+ * function calls allow the user to assign a name to a category ID.
+ *
+ * \param category - The category ID to name.
+ * \param name - The name of the category.
+ *
+ * \remarks The category names are tracked per process.
+ *
+ * \par Example:
+ * \code
+ * nvtxNameCategory(1, "Memory Allocation");
+ * nvtxNameCategory(2, "Memory Transfer");
+ * nvtxNameCategory(3, "Memory Object Lifetime");
+ * \endcode
+ *
+ * \version \NVTX_VERSION_1
+ */
+NVTX_DECLSPEC void NVTX_API nvtxNameCategoryA(uint32_t category, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameCategoryW(uint32_t category, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \name Functions for OS Resource Naming
+ */
+/** @{
+ * \brief Annotate an OS thread.
+ *
+ * Allows the user to name an active thread of the current process. If an
+ * invalid thread ID is provided or a thread ID from a different process is
+ * used the behavior of the tool is implementation dependent.
+ *
+ * \param threadId - The ID of the thread to name.
+ * \param name - The name of the thread.
+ *
+ * \par Example:
+ * \code
+ * nvtxNameOsThread(GetCurrentThreadId(), "MAIN_THREAD");
+ * \endcode
+ *
+ * \version \NVTX_VERSION_1
+ */
+NVTX_DECLSPEC void NVTX_API nvtxNameOsThreadA(uint32_t threadId, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameOsThreadW(uint32_t threadId, const wchar_t* name);
+/** @} */
+
+/** @} */ /* END RESOURCE_NAMING */
+
+/* ========================================================================= */
+
+#ifdef UNICODE
+ #define nvtxMark nvtxMarkW
+ #define nvtxRangeStart nvtxRangeStartW
+ #define nvtxRangePush nvtxRangePushW
+ #define nvtxNameCategory nvtxNameCategoryW
+ #define nvtxNameOsThread nvtxNameOsThreadW
+#else
+ #define nvtxMark nvtxMarkA
+ #define nvtxRangeStart nvtxRangeStartA
+ #define nvtxRangePush nvtxRangePushA
+ #define nvtxNameCategory nvtxNameCategoryA
+ #define nvtxNameOsThread nvtxNameOsThreadA
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* NVTOOLSEXT_H_ */
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtCuda.h b/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtCuda.h
new file mode 100644
index 0000000..2858c32
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtCuda.h
@@ -0,0 +1,128 @@
+/*
+* Copyright 2009-2012 NVIDIA Corporation. All rights reserved.
+*
+* NOTICE TO USER:
+*
+* This source code is subject to NVIDIA ownership rights under U.S. and
+* international Copyright laws.
+*
+* This software and the information contained herein is PROPRIETARY and
+* CONFIDENTIAL to NVIDIA and is being provided under the terms and conditions
+* of a form of NVIDIA software license agreement.
+*
+* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
+* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
+* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
+* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
+* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
+* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
+* OR PERFORMANCE OF THIS SOURCE CODE.
+*
+* U.S. Government End Users. This source code is a "commercial item" as
+* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
+* "commercial computer software" and "commercial computer software
+* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
+* and is provided to the U.S. Government only as a commercial end item.
+* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
+* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
+* source code with only those rights set forth herein.
+*
+* Any use of this source code in individual and commercial software must
+* include, in the user documentation and internal comments to the code,
+* the above Disclaimer and U.S. Government End Users Notice.
+*/
+
+#ifndef NVTOOLSEXT_CUDA_H_
+#define NVTOOLSEXT_CUDA_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "cuda.h"
+
+#include "nvToolsExt.h"
+
+/* ========================================================================= */
+/** \name Functions for CUDA Resource Naming
+*/
+/** \addtogroup RESOURCE_NAMING
+ * \section RESOURCE_NAMING_CUDA CUDA Resource Naming
+ *
+ * This section covers the API functions that allow to annotate CUDA resources
+ * with user-provided names.
+ *
+ * @{
+ */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates a CUDA device.
+ *
+ * Allows the user to associate a CUDA device with a user-provided name.
+ *
+ * \param device - The handle of the CUDA device to name.
+ * \param name - The name of the CUDA device.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameCuDeviceA(CUdevice device, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameCuDeviceW(CUdevice device, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates a CUDA context.
+ *
+ * Allows the user to associate a CUDA context with a user-provided name.
+ *
+ * \param context - The handle of the CUDA context to name.
+ * \param name - The name of the CUDA context.
+ *
+ * \par Example:
+ * \code
+ * CUresult status = cuCtxCreate( &cuContext, 0, cuDevice );
+ * if ( CUDA_SUCCESS != status )
+ * goto Error;
+ * nvtxNameCuContext(cuContext, "CTX_NAME");
+ * \endcode
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameCuContextA(CUcontext context, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameCuContextW(CUcontext context, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates a CUDA stream.
+ *
+ * Allows the user to associate a CUDA stream with a user-provided name.
+ *
+ * \param stream - The handle of the CUDA stream to name.
+ * \param name - The name of the CUDA stream.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameCuStreamA(CUstream stream, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameCuStreamW(CUstream stream, const wchar_t* name);
+/** @} */
+
+/** @} */ /* END RESOURCE_NAMING */
+
+/* ========================================================================= */
+#ifdef UNICODE
+ #define nvtxNameCuDevice nvtxNameCuDeviceW
+ #define nvtxNameCuContext nvtxNameCuContextW
+ #define nvtxNameCuStream nvtxNameCuStreamW
+#else
+ #define nvtxNameCuDevice nvtxNameCuDeviceA
+ #define nvtxNameCuContext nvtxNameCuContextA
+ #define nvtxNameCuStream nvtxNameCuStreamA
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* NVTOOLSEXT_CUDA_H_ */
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtOpenCL.h b/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtOpenCL.h
new file mode 100644
index 0000000..570d1b3
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/include/nvToolsExtOpenCL.h
@@ -0,0 +1,191 @@
+/*
+* Copyright 2009-2012 NVIDIA Corporation. All rights reserved.
+*
+* NOTICE TO USER:
+*
+* This source code is subject to NVIDIA ownership rights under U.S. and
+* international Copyright laws.
+*
+* This software and the information contained herein is PROPRIETARY and
+* CONFIDENTIAL to NVIDIA and is being provided under the terms and conditions
+* of a form of NVIDIA software license agreement.
+*
+* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
+* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
+* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
+* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
+* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
+* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
+* OR PERFORMANCE OF THIS SOURCE CODE.
+*
+* U.S. Government End Users. This source code is a "commercial item" as
+* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
+* "commercial computer software" and "commercial computer software
+* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
+* and is provided to the U.S. Government only as a commercial end item.
+* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
+* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
+* source code with only those rights set forth herein.
+*
+* Any use of this source code in individual and commercial software must
+* include, in the user documentation and internal comments to the code,
+* the above Disclaimer and U.S. Government End Users Notice.
+*/
+
+#ifndef NVTOOLSEXT_OPENCL_H_
+#define NVTOOLSEXT_OPENCL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include <CL/cl.h>
+
+#include "nvToolsExt.h"
+
+/* ========================================================================= */
+/** \name Functions for OpenCL Resource Naming
+ */
+/** \addtogroup RESOURCE_NAMING
+ * \section RESOURCE_NAMING_OPENCL OpenCL Resource Naming
+ *
+ * This section covers the API functions that allow to annotate OpenCL resources
+ * with user-provided names.
+ *
+ * @{
+ */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL device.
+ *
+ * Allows to associate an OpenCL device with a user-provided name.
+ *
+ * \param device - The handle of the OpenCL device to name.
+ * \param name - The name of the OpenCL device.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClDeviceA(cl_device_id device, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClDeviceW(cl_device_id device, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL context.
+ *
+ * Allows to associate an OpenCL context with a user-provided name.
+ *
+ * \param context - The handle of the OpenCL context to name.
+ * \param name - The name of the OpenCL context.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClContextA(cl_context context, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClContextW(cl_context context, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL command queue.
+ *
+ * Allows to associate an OpenCL command queue with a user-provided name.
+ *
+ * \param command_queue - The handle of the OpenCL command queue to name.
+ * \param name - The name of the OpenCL command queue.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClCommandQueueA(cl_command_queue command_queue, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClCommandQueueW(cl_command_queue command_queue, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL memory object.
+ *
+ * Allows to associate an OpenCL memory object with a user-provided name.
+ *
+ * \param memobj - The handle of the OpenCL memory object to name.
+ * \param name - The name of the OpenCL memory object.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClMemObjectA(cl_mem memobj, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClMemObjectW(cl_mem memobj, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL sampler.
+ *
+ * Allows to associate an OpenCL sampler with a user-provided name.
+ *
+ * \param sampler - The handle of the OpenCL sampler to name.
+ * \param name - The name of the OpenCL sampler.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClSamplerA(cl_sampler sampler, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClSamplerW(cl_sampler sampler, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL program.
+ *
+ * Allows to associate an OpenCL program with a user-provided name.
+ *
+ * \param program - The handle of the OpenCL program to name.
+ * \param name - The name of the OpenCL program.
+ *
+ * \code
+ * cpProgram = clCreateProgramWithSource(cxGPUContext, 1,
+ * (const char **) &cSourceCL, &program_length, &ciErrNum);
+ * shrCheckErrorEX(ciErrNum, CL_SUCCESS, pCleanup);
+ * nvtxNameClProgram(cpProgram, L"PROGRAM_NAME");
+ * \endcode
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClProgramA(cl_program program, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClProgramW(cl_program program, const wchar_t* name);
+/** @} */
+
+/* ------------------------------------------------------------------------- */
+/** \brief Annotates an OpenCL event.
+ *
+ * Allows to associate an OpenCL event with a user-provided name.
+ *
+ * \param evnt - The handle of the OpenCL event to name.
+ * \param name - The name of the OpenCL event.
+ *
+ * \version \NVTX_VERSION_1
+ * @{ */
+NVTX_DECLSPEC void NVTX_API nvtxNameClEventA(cl_event evnt, const char* name);
+NVTX_DECLSPEC void NVTX_API nvtxNameClEventW(cl_event evnt, const wchar_t* name);
+/** @} */
+
+/** @} */ /* END RESOURCE_NAMING */
+
+/* ========================================================================= */
+#ifdef UNICODE
+ #define nvtxNameClDevice nvtxNameClDeviceW
+ #define nvtxNameClContext nvtxNameClContextW
+ #define nvtxNameClCommandQueue nvtxNameClCommandQueueW
+ #define nvtxNameClMemObject nvtxNameClMemObjectW
+ #define nvtxNameClSampler nvtxNameClSamplerW
+ #define nvtxNameClProgram nvtxNameClProgramW
+ #define nvtxNameClEvent nvtxNameClEventW
+#else
+ #define nvtxNameClDevice nvtxNameClDeviceA
+ #define nvtxNameClContext nvtxNameClContextA
+ #define nvtxNameClCommandQueue nvtxNameClCommandQueueA
+ #define nvtxNameClMemObject nvtxNameClMemObjectA
+ #define nvtxNameClSampler nvtxNameClSamplerA
+ #define nvtxNameClProgram nvtxNameClProgramA
+ #define nvtxNameClEvent nvtxNameClEventA
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* NVTOOLSEXT_OPENCL_H_ */
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/include/stdint/stdint.h b/NvCloth/samples/external/nvToolsExt/1.0/include/stdint/stdint.h
new file mode 100644
index 0000000..d02608a
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/include/stdint/stdint.h
@@ -0,0 +1,247 @@
+// ISO C9x compliant stdint.h for Microsoft Visual Studio
+// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
+//
+// Copyright (c) 2006-2008 Alexander Chemeris
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+//
+// 2. 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.
+//
+// 3. The name of the author may be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef _MSC_VER // [
+#error "Use this header only with Microsoft Visual C++ compilers!"
+#endif // _MSC_VER ]
+
+#ifndef _MSC_STDINT_H_ // [
+#define _MSC_STDINT_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif
+
+#include <limits.h>
+
+// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
+// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
+// or compiler give many errors like this:
+// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
+#ifdef __cplusplus
+extern "C" {
+#endif
+# include <wchar.h>
+#ifdef __cplusplus
+}
+#endif
+
+// Define _W64 macros to mark types changing their size, like intptr_t.
+#ifndef _W64
+# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
+# define _W64 __w64
+# else
+# define _W64
+# endif
+#endif
+
+
+// 7.18.1 Integer types
+
+// 7.18.1.1 Exact-width integer types
+
+// Visual Studio 6 and Embedded Visual C++ 4 doesn't
+// realize that, e.g. char has the same size as __int8
+// so we give up on __intX for them.
+#if (_MSC_VER < 1300)
+ typedef signed char int8_t;
+ typedef signed short int16_t;
+ typedef signed int int32_t;
+ typedef unsigned char uint8_t;
+ typedef unsigned short uint16_t;
+ typedef unsigned int uint32_t;
+#else
+ typedef signed __int8 int8_t;
+ typedef signed __int16 int16_t;
+ typedef signed __int32 int32_t;
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int16 uint16_t;
+ typedef unsigned __int32 uint32_t;
+#endif
+typedef signed __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+
+
+// 7.18.1.2 Minimum-width integer types
+typedef int8_t int_least8_t;
+typedef int16_t int_least16_t;
+typedef int32_t int_least32_t;
+typedef int64_t int_least64_t;
+typedef uint8_t uint_least8_t;
+typedef uint16_t uint_least16_t;
+typedef uint32_t uint_least32_t;
+typedef uint64_t uint_least64_t;
+
+// 7.18.1.3 Fastest minimum-width integer types
+typedef int8_t int_fast8_t;
+typedef int16_t int_fast16_t;
+typedef int32_t int_fast32_t;
+typedef int64_t int_fast64_t;
+typedef uint8_t uint_fast8_t;
+typedef uint16_t uint_fast16_t;
+typedef uint32_t uint_fast32_t;
+typedef uint64_t uint_fast64_t;
+
+// 7.18.1.4 Integer types capable of holding object pointers
+#ifdef _WIN64 // [
+ typedef signed __int64 intptr_t;
+ typedef unsigned __int64 uintptr_t;
+#else // _WIN64 ][
+ typedef _W64 signed int intptr_t;
+ typedef _W64 unsigned int uintptr_t;
+#endif // _WIN64 ]
+
+// 7.18.1.5 Greatest-width integer types
+typedef int64_t intmax_t;
+typedef uint64_t uintmax_t;
+
+
+// 7.18.2 Limits of specified-width integer types
+
+#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
+
+// 7.18.2.1 Limits of exact-width integer types
+#define INT8_MIN ((int8_t)_I8_MIN)
+#define INT8_MAX _I8_MAX
+#define INT16_MIN ((int16_t)_I16_MIN)
+#define INT16_MAX _I16_MAX
+#define INT32_MIN ((int32_t)_I32_MIN)
+#define INT32_MAX _I32_MAX
+#define INT64_MIN ((int64_t)_I64_MIN)
+#define INT64_MAX _I64_MAX
+#define UINT8_MAX _UI8_MAX
+#define UINT16_MAX _UI16_MAX
+#define UINT32_MAX _UI32_MAX
+#define UINT64_MAX _UI64_MAX
+
+// 7.18.2.2 Limits of minimum-width integer types
+#define INT_LEAST8_MIN INT8_MIN
+#define INT_LEAST8_MAX INT8_MAX
+#define INT_LEAST16_MIN INT16_MIN
+#define INT_LEAST16_MAX INT16_MAX
+#define INT_LEAST32_MIN INT32_MIN
+#define INT_LEAST32_MAX INT32_MAX
+#define INT_LEAST64_MIN INT64_MIN
+#define INT_LEAST64_MAX INT64_MAX
+#define UINT_LEAST8_MAX UINT8_MAX
+#define UINT_LEAST16_MAX UINT16_MAX
+#define UINT_LEAST32_MAX UINT32_MAX
+#define UINT_LEAST64_MAX UINT64_MAX
+
+// 7.18.2.3 Limits of fastest minimum-width integer types
+#define INT_FAST8_MIN INT8_MIN
+#define INT_FAST8_MAX INT8_MAX
+#define INT_FAST16_MIN INT16_MIN
+#define INT_FAST16_MAX INT16_MAX
+#define INT_FAST32_MIN INT32_MIN
+#define INT_FAST32_MAX INT32_MAX
+#define INT_FAST64_MIN INT64_MIN
+#define INT_FAST64_MAX INT64_MAX
+#define UINT_FAST8_MAX UINT8_MAX
+#define UINT_FAST16_MAX UINT16_MAX
+#define UINT_FAST32_MAX UINT32_MAX
+#define UINT_FAST64_MAX UINT64_MAX
+
+// 7.18.2.4 Limits of integer types capable of holding object pointers
+#ifdef _WIN64 // [
+# define INTPTR_MIN INT64_MIN
+# define INTPTR_MAX INT64_MAX
+# define UINTPTR_MAX UINT64_MAX
+#else // _WIN64 ][
+# define INTPTR_MIN INT32_MIN
+# define INTPTR_MAX INT32_MAX
+# define UINTPTR_MAX UINT32_MAX
+#endif // _WIN64 ]
+
+// 7.18.2.5 Limits of greatest-width integer types
+#define INTMAX_MIN INT64_MIN
+#define INTMAX_MAX INT64_MAX
+#define UINTMAX_MAX UINT64_MAX
+
+// 7.18.3 Limits of other integer types
+
+#ifdef _WIN64 // [
+# define PTRDIFF_MIN _I64_MIN
+# define PTRDIFF_MAX _I64_MAX
+#else // _WIN64 ][
+# define PTRDIFF_MIN _I32_MIN
+# define PTRDIFF_MAX _I32_MAX
+#endif // _WIN64 ]
+
+#define SIG_ATOMIC_MIN INT_MIN
+#define SIG_ATOMIC_MAX INT_MAX
+
+#ifndef SIZE_MAX // [
+# ifdef _WIN64 // [
+# define SIZE_MAX _UI64_MAX
+# else // _WIN64 ][
+# define SIZE_MAX _UI32_MAX
+# endif // _WIN64 ]
+#endif // SIZE_MAX ]
+
+// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
+#ifndef WCHAR_MIN // [
+# define WCHAR_MIN 0
+#endif // WCHAR_MIN ]
+#ifndef WCHAR_MAX // [
+# define WCHAR_MAX _UI16_MAX
+#endif // WCHAR_MAX ]
+
+#define WINT_MIN 0
+#define WINT_MAX _UI16_MAX
+
+#endif // __STDC_LIMIT_MACROS ]
+
+
+// 7.18.4 Limits of other integer types
+
+#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
+
+// 7.18.4.1 Macros for minimum-width integer constants
+
+#define INT8_C(val) val##i8
+#define INT16_C(val) val##i16
+#define INT32_C(val) val##i32
+#define INT64_C(val) val##i64
+
+#define UINT8_C(val) val##ui8
+#define UINT16_C(val) val##ui16
+#define UINT32_C(val) val##ui32
+#define UINT64_C(val) val##ui64
+
+// 7.18.4.2 Macros for greatest-width integer constants
+#define INTMAX_C INT64_C
+#define UINTMAX_C UINT64_C
+
+#endif // __STDC_CONSTANT_MACROS ]
+
+
+#endif // _MSC_STDINT_H_ ]
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/lib/Win32/nvToolsExt32_1.lib b/NvCloth/samples/external/nvToolsExt/1.0/lib/Win32/nvToolsExt32_1.lib
new file mode 100644
index 0000000..2acdd8d
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/lib/Win32/nvToolsExt32_1.lib
Binary files differ
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/lib/armv7/libnvToolsExt.a b/NvCloth/samples/external/nvToolsExt/1.0/lib/armv7/libnvToolsExt.a
new file mode 100644
index 0000000..1b89d42
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/lib/armv7/libnvToolsExt.a
Binary files differ
diff --git a/NvCloth/samples/external/nvToolsExt/1.0/lib/x64/nvToolsExt64_1.lib b/NvCloth/samples/external/nvToolsExt/1.0/lib/x64/nvToolsExt64_1.lib
new file mode 100644
index 0000000..b72d70e
--- /dev/null
+++ b/NvCloth/samples/external/nvToolsExt/1.0/lib/x64/nvToolsExt64_1.lib
Binary files differ
diff --git a/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib.h b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib.h
new file mode 100644
index 0000000..a0784d5
--- /dev/null
+++ b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib.h
@@ -0,0 +1,865 @@
+// This code contains NVIDIA Confidential Information and is disclosed
+// under the Mutual Non-Disclosure Agreement.
+//
+// Notice
+// ALL NVIDIA DESIGN SPECIFICATIONS AND CODE ("MATERIALS") ARE PROVIDED "AS IS" NVIDIA MAKES
+// NO REPRESENTATIONS, WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ANY IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
+//
+// NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. No third party distribution is allowed unless
+// expressly authorized by NVIDIA. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (C) 2012, NVIDIA Corporation. All rights reserved.
+//
+// NVIDIA Corporation and its licensors retain all intellectual property and proprietary
+// rights in and to this software and related documentation and any modifications thereto.
+// Any use, reproduction, disclosure or distribution of this software and related
+// documentation without an express license agreement from NVIDIA Corporation is
+// strictly prohibited.
+
+
+/*===========================================================================
+ GFSDK_ShadowLib.h
+=============================================================================
+
+GFSDK_ShadowLib written by Jon Story
+-----------------------------------------
+This library provides an API for rendering various kinds of shadow maps,
+and then rendering a shadow buffer using the desired filtering technique.
+The programmer is expected to provide either:
+1) a pointer to a function containing all the necessary render calls for the shadow map(s).
+2) pre-rendered shadow maps
+In order to render the shadow buffer the programmer must supply a depth buffer. The library
+returns a SRV of the shadow buffer for modulation with the scene color buffer.
+
+NOTE:
+1) The library tracks and restores all graphics API state it uses.
+2) All matrices are expected to be row major.
+
+The typical expected use scenario would look like this:
+
+GameEngine::OnCreateDevice()
+{
+ GFSDK_ShadowLib_GetVersion()
+ GFSDK_ShadowLib_Create()
+ GFSDK_ShadowLib_Context::AddBuffer()
+
+ // Optional - if not providing your own shadow maps
+ GFSDK_ShadowLib_Context::AddMap()
+}
+
+GameEngine::OnResizeWindow()
+{
+ GFSDK_ShadowLib_Context::RemoveBuffer()
+ GFSDK_ShadowLib_Context::AddBuffer()
+}
+
+GameEngine::OnRender()
+{
+ // Optional - depending on the render settings some temp resources may be required
+ // by the lib, see the GFSDK_ShadowLib_TempResources structure for details
+ GFSDK_ShadowLib_Context::SetTempResources()
+
+ // Optional - if not providing your own shadow maps
+ GFSDK_ShadowLib_Context::RenderMap()
+
+ GFSDK_ShadowLib_Context::ClearBuffer()
+ GFSDK_ShadowLib_Context::RenderBuffer()
+ GFSDK_ShadowLib_Context::FinalizeBuffer()
+
+ // Optional - if not wanting to perform a custom modulate with scene color
+ GFSDK_ShadowLib_Context::ModulateBuffer()
+}
+
+GameEngine::OnDestroyDevice()
+{
+ // Optional - if not providing your own shadow maps
+ GFSDK_ShadowLib_Context::RemoveMap()
+
+ GFSDK_ShadowLib_Context::RemoveBuffer()
+ GFSDK_ShadowLib_Context::Destroy()
+}
+
+ENGINEERING CONTACT
+Jon Story (NVIDIA Senior Developer Technology Engineer)
+
+===========================================================================*/
+
+#pragma once
+
+// defines general GFSDK includes and structs
+#include "GFSDK_ShadowLib_Common.h"
+
+
+/*===========================================================================
+Version
+===========================================================================*/
+
+// The major, minor and CL version of this library header file
+#define GFSDK_SHADOWLIB_MAJOR_VERSION 2
+#define GFSDK_SHADOWLIB_MINOR_VERSION 0
+#define GFSDK_SHADOWLIB_CHANGE_LIST "$Change: 20145232 $"
+
+
+/*===========================================================================
+Version structure
+===========================================================================*/
+struct GFSDK_ShadowLib_Version
+{
+ unsigned int uMajor;
+ unsigned int uMinor;
+};
+
+
+/*===========================================================================
+Return codes for the lib
+===========================================================================*/
+enum GFSDK_ShadowLib_Status
+{
+ // Success
+ GFSDK_ShadowLib_Status_Ok = 0,
+ // Fail
+ GFSDK_ShadowLib_Status_Fail = -1,
+ // Mismatch between header and dll
+ GFSDK_ShadowLib_Status_Invalid_Version = -2,
+ // One or more invalid parameters
+ GFSDK_ShadowLib_Status_Invalid_Parameter = -3,
+ // Failed to allocate a resource
+ GFSDK_ShadowLib_Status_Out_Of_Memory = -4,
+ // The library is being used by another thread
+ GFSDK_ShadowLib_Busy = -5,
+ // glewInit failed
+ GFSDK_ShadowLib_GLEW_INIT_FAILED = -6,
+ // glewIsSupported("GL_VERSION_3_2") returned false
+ GFSDK_ShadowLib_GL_CORE_VERSION_NOT_SUPPORTED = -7,
+};
+
+
+/*===========================================================================
+Shadow map types
+===========================================================================*/
+enum GFSDK_ShadowLib_MapType
+{
+ GFSDK_ShadowLib_MapType_Texture,
+ GFSDK_ShadowLib_MapType_TextureArray,
+ GFSDK_ShadowLib_MapType_Max,
+};
+
+
+/*===========================================================================
+Channel from which to sample depth in the supplied depth SRV
+===========================================================================*/
+enum GFSDK_ShadowLib_EyeDepthChannel
+{
+ GFSDK_ShadowLib_EyeDepthChannel_R,
+ GFSDK_ShadowLib_EyeDepthChannel_G,
+ GFSDK_ShadowLib_EyeDepthChannel_B,
+ GFSDK_ShadowLib_EyeDepthChannel_A,
+ GFSDK_ShadowLib_EyeDepthChannel_Max,
+};
+
+
+/*===========================================================================
+Filtering technique types
+===========================================================================*/
+enum GFSDK_ShadowLib_TechniqueType
+{
+ // A pure hard shadow
+ GFSDK_ShadowLib_TechniqueType_Hard,
+ // Regular box PCF shadow
+ GFSDK_ShadowLib_TechniqueType_PCF,
+ // PCSS+
+ GFSDK_ShadowLib_TechniqueType_PCSS,
+ GFSDK_ShadowLib_TechniqueType_Max,
+};
+
+
+/*===========================================================================
+Quality type of the filtering technique to be used
+===========================================================================*/
+enum GFSDK_ShadowLib_QualityType
+{
+ // Quality settings only apply to the PCSS+ technique
+ // Cascaded maps (C0=Low,C1=Low,C2=Low,C3=Low)
+ GFSDK_ShadowLib_QualityType_Low,
+ // Cascaded maps (C0=Medium,C1=Low,C2=Low,C3=Low)
+ GFSDK_ShadowLib_QualityType_Medium,
+ // Cascaded maps (C0=High,C1=Medium,C2=Low,C3=Low)
+ GFSDK_ShadowLib_QualityType_High,
+ GFSDK_ShadowLib_QualityType_Max,
+};
+
+
+/*===========================================================================
+Accepted shadow map view types
+===========================================================================*/
+enum GFSDK_ShadowLib_ViewType
+{
+ // Must use GFSDK_ShadowLib_MapType_Texture with GFSDK_ShadowLib_ViewType_Single
+ GFSDK_ShadowLib_ViewType_Single = 1,
+ GFSDK_ShadowLib_ViewType_Cascades_2 = 2,
+ GFSDK_ShadowLib_ViewType_Cascades_3 = 3,
+ GFSDK_ShadowLib_ViewType_Cascades_4 = 4,
+};
+
+
+/*===========================================================================
+Light source types
+===========================================================================*/
+enum GFSDK_ShadowLib_LightType
+{
+ GFSDK_ShadowLib_LightType_Directional,
+ GFSDK_ShadowLib_LightType_Spot,
+ GFSDK_ShadowLib_LightType_Max,
+};
+
+
+/*===========================================================================
+Per-sample mode to use
+===========================================================================*/
+enum GFSDK_ShadowLib_MSAARenderMode
+{
+ // Every pixel in the shadow buffer is considered to be complex
+ // and will be run at sample frequency
+ GFSDK_ShadowLib_MSAARenderMode_BruteForce,
+ // The application provides a stencil mask and ref values which
+ // indicate which pixels are considered complex / simple
+ GFSDK_ShadowLib_MSAARenderMode_ComplexPixelMask,
+ GFSDK_ShadowLib_MSAARenderMode_Max,
+};
+
+
+/*===========================================================================
+Modulate buffer mask
+===========================================================================*/
+enum GFSDK_ShadowLib_ModulateBufferMask
+{
+ GFSDK_ShadowLib_ModulateBufferMask_RGB,
+ GFSDK_ShadowLib_ModulateBufferMask_R,
+ GFSDK_ShadowLib_ModulateBufferMask_G,
+ GFSDK_ShadowLib_ModulateBufferMask_B,
+ GFSDK_ShadowLib_ModulateBufferMask_A,
+ GFSDK_ShadowLib_ModulateBufferMask_Max,
+};
+
+
+/*===========================================================================
+Light descriptor
+===========================================================================*/
+struct GFSDK_ShadowLib_LightDesc
+{
+ GFSDK_ShadowLib_LightType eLightType;
+ gfsdk_float3 v3LightPos;
+ gfsdk_float3 v3LightLookAt;
+ gfsdk_F32 fLightSize;
+ // Params for fading off shadows by distance from source (ignored if bLightFalloff == false):
+ // float3 v3LightVec = ( v3LightPos - v3PositionWS ) / fLightRadius;
+ // float fDistanceScale = square( max( 0, length( v3LightVec ) * fLightFalloffDistance + fLightFalloffBias ) );
+ // float fLerp = pow( saturate( 1.0f - fDistanceScale ), fLightFalloffExponent );
+ // Shadow = lerp( 1.0f, Shadow, fLerp );
+ gfsdk_bool bLightFalloff;
+ gfsdk_F32 fLightFalloffRadius;
+ gfsdk_F32 fLightFalloffDistance;
+ gfsdk_F32 fLightFalloffBias;
+ gfsdk_F32 fLightFalloffExponent;
+
+ // Defaults
+ GFSDK_ShadowLib_LightDesc()
+ {
+ eLightType = GFSDK_ShadowLib_LightType_Directional;
+ v3LightPos = GFSDK_One_Vector3;
+ v3LightLookAt = GFSDK_Zero_Vector3;
+ fLightSize = 1.0f;
+ bLightFalloff = false;
+ fLightFalloffRadius = 0.0f;
+ fLightFalloffDistance = 0.0f;
+ fLightFalloffBias = 0.0f;
+ fLightFalloffExponent = 0.0f;
+ }
+};
+
+
+/*===========================================================================
+Shadow buffer descriptor
+===========================================================================*/
+struct GFSDK_ShadowLib_BufferDesc
+{
+ gfsdk_U32 uResolutionWidth;
+ gfsdk_U32 uResolutionHeight;
+ gfsdk_U32 uSampleCount;
+ // A read only depth stencil view, which is required for the optimized per sample
+ // render path and the stencil channel is expected to contain a mask for complex
+ // pixels. It is also a requirment for running in stereo mode (can be NULL otherwise)
+ GFSDK_ShadowLib_DepthStencilView ReadOnlyDSV;
+
+ // Defaults
+ GFSDK_ShadowLib_BufferDesc()
+ {
+ uResolutionWidth = 0;
+ uResolutionHeight = 0;
+ uSampleCount = 1;
+ }
+};
+
+
+/*===========================================================================
+Depth buffer descriptor
+===========================================================================*/
+struct GFSDK_ShadowLib_DepthBufferDesc
+{
+ // The depth SRV from which depth values will be read
+ GFSDK_ShadowLib_ShaderResourceView DepthStencilSRV;
+ // A single sample version of depth, which is required for the optimized per sample
+ // render path (can be NULL otherwise)
+ GFSDK_ShadowLib_ShaderResourceView ResolvedDepthStencilSRV;
+ // The 2 ref values used during stencil testing to signal which pixels are considered
+ // complex and which simple
+ gfsdk_U32 uComplexRefValue;
+ gfsdk_U32 uSimpleRefValue;
+ // Determines from which channel to read depth values from in the input depth SRV
+ GFSDK_ShadowLib_EyeDepthChannel eEyeDepthChannel;
+ // Set to true to invert depth buffer values
+ gfsdk_bool bInvertEyeDepth;
+
+ // Defaults
+ GFSDK_ShadowLib_DepthBufferDesc()
+ {
+ uComplexRefValue = 0x01;
+ uSimpleRefValue = 0x00;
+ eEyeDepthChannel = GFSDK_ShadowLib_EyeDepthChannel_R;
+ bInvertEyeDepth = false;
+ }
+};
+
+
+/*===========================================================================
+Descriptor used to place each view with support for sub-regions of a shadow map
+===========================================================================*/
+struct GFSDK_ShadowLib_ViewLocationDesc
+{
+ // Array index of the shadow map (in the GFSDK_ShadowLib_MapType_TextureArray) containing this view
+ gfsdk_U32 uMapID;
+ // The origin is considered to be: DX = Top Left, GL = Bottom Left
+ gfsdk_float2 v2Origin;
+ gfsdk_float2 v2Dimension;
+
+ // Defaults
+ GFSDK_ShadowLib_ViewLocationDesc()
+ {
+ uMapID = 0;
+ v2Origin = GFSDK_Zero_Vector2;
+ v2Dimension = GFSDK_Zero_Vector2;
+ }
+};
+
+
+/*===========================================================================
+Map descriptor
+===========================================================================*/
+struct GFSDK_ShadowLib_MapDesc
+{
+ gfsdk_U32 uResolutionWidth;
+ gfsdk_U32 uResolutionHeight;
+ GFSDK_ShadowLib_MapType eMapType;
+ // Use this to optionally downsample a shadow map to increase performance of the
+ // blocker search for the PCSS technique (intended use case is for high resolution shadow maps).
+ // This pathway is only supported for: GFSDK_ShadowLib_ViewType_Single, GFSDK_ShadowLib_MapType_Texture & GFSDK_ShadowLib_TechniqueType_PCSS
+ // Setting this to true, will require you to provide the temp resource for the downsample, the resolution of the resource will determine
+ // the downsample size.
+ gfsdk_bool bDownsample;
+ // Size of array (in the case of GFSDK_ShadowLib_MapType_TextureArray)
+ gfsdk_U32 uArraySize;
+ GFSDK_ShadowLib_ViewType eViewType;
+ GFSDK_ShadowLib_ViewLocationDesc ViewLocation[GFSDK_ShadowLib_ViewType_Cascades_4];
+
+ // Defaults
+ GFSDK_ShadowLib_MapDesc()
+ {
+ uResolutionWidth = 0;
+ uResolutionHeight = 0;
+ eMapType = GFSDK_ShadowLib_MapType_Texture;
+ bDownsample = false;
+ uArraySize = 1;
+ eViewType = GFSDK_ShadowLib_ViewType_Single;
+ }
+};
+
+
+/*===========================================================================
+External map descriptor
+===========================================================================*/
+struct GFSDK_ShadowLib_ExternalMapDesc
+{
+ GFSDK_ShadowLib_MapDesc Desc;
+ gfsdk_float4x4 m4x4EyeViewMatrix;
+ gfsdk_float4x4 m4x4EyeProjectionMatrix;
+ gfsdk_float4x4 m4x4LightViewMatrix;
+ gfsdk_float4x4 m4x4LightProjMatrix[GFSDK_ShadowLib_ViewType_Cascades_4];
+ // Pure offset added to eye Z values (in shadow map space) (on a per cascade basis)
+ gfsdk_F32 fBiasZ[GFSDK_ShadowLib_ViewType_Cascades_4];
+ // Global scale of shadow intensity: shadow buffer = lerp( Shadow, 1.0f, fShadowIntensity );
+ gfsdk_F32 fShadowIntensity;
+ GFSDK_ShadowLib_LightDesc LightDesc;
+
+ // Defaults
+ GFSDK_ShadowLib_ExternalMapDesc()
+ {
+ m4x4EyeViewMatrix = GFSDK_Identity_Matrix;
+ m4x4EyeProjectionMatrix = GFSDK_Identity_Matrix;
+ m4x4LightViewMatrix = GFSDK_Identity_Matrix;
+ m4x4LightProjMatrix[0] = GFSDK_Identity_Matrix;
+ m4x4LightProjMatrix[1] = GFSDK_Identity_Matrix;
+ m4x4LightProjMatrix[2] = GFSDK_Identity_Matrix;
+ m4x4LightProjMatrix[3] = GFSDK_Identity_Matrix;
+ fBiasZ[0] = fBiasZ[1] = fBiasZ[2] = fBiasZ[3] = 0.0f;
+ fShadowIntensity = 0.0f;
+ }
+};
+
+
+/*===========================================================================
+Shadow map rendering params
+===========================================================================*/
+struct GFSDK_ShadowLib_MapRenderParams
+{
+ // Function pointer to user defined function that renders the shadow map
+ void (*fnpDrawFunction)( void*, gfsdk_float4x4* );
+ // User defined data passed to the user supplied function pointer
+ void* pDrawFunctionParams;
+ gfsdk_float4x4 m4x4EyeViewMatrix;
+ gfsdk_float4x4 m4x4EyeProjectionMatrix;
+ // World space axis aligned bounding box that encapsulates the shadow map scene geometry
+ gfsdk_float3 v3WorldSpaceBBox[2];
+ GFSDK_ShadowLib_LightDesc LightDesc;
+ // Defines the eye space Z far value for each cascade
+ gfsdk_F32 fCascadeZFarPercent[GFSDK_ShadowLib_ViewType_Cascades_4];
+ // passed to the hw through D3D11_RASTERIZER_DESC.DepthBias
+ gfsdk_S32 iDepthBias;
+ // passed to the hw through D3D11_RASTERIZER_DESC.SlopeScaledDepthBias
+ gfsdk_F32 fSlopeScaledDepthBias;
+
+ // Defaults
+ GFSDK_ShadowLib_MapRenderParams()
+ {
+ fnpDrawFunction = NULL;
+ pDrawFunctionParams = NULL;
+ m4x4EyeViewMatrix = GFSDK_Identity_Matrix;
+ m4x4EyeProjectionMatrix = GFSDK_Identity_Matrix;
+ v3WorldSpaceBBox[0] = v3WorldSpaceBBox[1] = GFSDK_Zero_Vector3;
+ fCascadeZFarPercent[0] = 20.0f;
+ fCascadeZFarPercent[1] = 40.0f;
+ fCascadeZFarPercent[2] = 70.0f;
+ fCascadeZFarPercent[3] = 100.0f;
+ iDepthBias = 1000;
+ fSlopeScaledDepthBias = 8.0f;
+ }
+};
+
+
+/*===========================================================================
+PCSS penumbra params
+===========================================================================*/
+struct GFSDK_ShadowLib_PCSSPenumbraParams
+{
+ // The World space blocker depth value at which maximum penumbra will occur
+ gfsdk_F32 fMaxThreshold;
+ // The World space blocker depth value at which penumbra size will no longer grow
+ gfsdk_F32 fMaxClamp;
+ // The minimum penumbra size, as a percentage of light size - so that you do not end up with zero
+ // filtering at blocker depth zero
+ gfsdk_F32 fMinSizePercent;
+ // The slope applied to weights of possion disc samples based upon 1-length as blocker depth approaches zero,
+ // this basically allows one to increase the fMinSizePercent, but shift sample weights towards the center
+ // of the disc.
+ gfsdk_F32 fMinWeightExponent;
+ // The percentage of penumbra size below which the fMinWeightExponent function is applied. This stops
+ // the entire shadow from being affected.
+ gfsdk_F32 fMinWeightThresholdPercent;
+ // The percentage of the blocker search and filter radius to dither by
+ gfsdk_F32 fBlockerSearchDitherPercent;
+ gfsdk_F32 fFilterDitherPercent;
+
+ // Defaults
+ GFSDK_ShadowLib_PCSSPenumbraParams()
+ {
+ fMaxThreshold = 100.0f;
+ fMaxClamp = 1.0f;
+ fMinSizePercent = 1.0f;
+ fMinWeightExponent = 3.0f;
+ fMinWeightThresholdPercent = 10.0f;
+ fBlockerSearchDitherPercent = 25.0f;
+ fFilterDitherPercent = 15.0f;
+ }
+};
+
+
+/*===========================================================================
+Shadow buffer rendering params
+===========================================================================*/
+struct GFSDK_ShadowLib_BufferRenderParams
+{
+ GFSDK_ShadowLib_TechniqueType eTechniqueType;
+ GFSDK_ShadowLib_QualityType eQualityType;
+ GFSDK_ShadowLib_MSAARenderMode eMSAARenderMode;
+ // Soft shadow test: Shadow = ( ( SceneZ - ShadowMapZ ) > ( SceneZ * fSoftShadowTestScale ) ) ? ( 0.0f ) : ( 1.0f );
+ gfsdk_F32 fSoftShadowTestScale;
+ GFSDK_ShadowLib_DepthBufferDesc DepthBufferDesc;
+ GFSDK_ShadowLib_PCSSPenumbraParams PCSSPenumbraParams;
+ // Cascade border and blending controls
+ gfsdk_F32 fCascadeBorderPercent;
+ gfsdk_F32 fCascadeBlendPercent;
+ // When non-zero this value is used to test the convergence of the shadow every 32 taps. If the shadow
+ // value has converged to this tolerance, the shader will early out. Shadow areas of low frequency can
+ // therefore take advantage of this.
+ gfsdk_F32 fConvergenceTestTolerance;
+
+ // Defaults
+ GFSDK_ShadowLib_BufferRenderParams()
+ {
+ eTechniqueType = GFSDK_ShadowLib_TechniqueType_PCSS;
+ eQualityType = GFSDK_ShadowLib_QualityType_High;
+ eMSAARenderMode = GFSDK_ShadowLib_MSAARenderMode_BruteForce;
+ fSoftShadowTestScale = 0.001f;
+ fCascadeBorderPercent = 1.0f;
+ fCascadeBlendPercent = 3.0f;
+ fConvergenceTestTolerance = 0.000001f;
+ }
+};
+
+
+/*===========================================================================
+All of the temp resources required by this lib. If you wish for the lib to create
+a resource for you then call the utility/dev mode function:
+GFSDK_ShadowLib_DevModeCreateTexture2D(). Otherwise you may provide the resource
+directly yourself. In either case you are responsible for releasing the resource.
+===========================================================================*/
+struct GFSDK_ShadowLib_TempResources
+{
+ // Downsampled shadow map resources (REQUIRED IF: GFSDK_ShadowLib_MapDesc::bDownsample = true)
+ // See comments in GFSDK_ShadowLib_MapDesc for usage model.
+ GFSDK_ShadowLib_Texture2D* pDownsampledShadowMap;
+
+ // Defaults
+ GFSDK_ShadowLib_TempResources()
+ {
+ pDownsampledShadowMap = NULL;
+ }
+};
+
+
+/*===========================================================================
+GFSDK_ShadowLib interface
+===========================================================================*/
+class GFSDK_ShadowLib_Context
+{
+public:
+
+
+/*===========================================================================
+Call once on device destruction to release the lib.
+All resources held by the context will be released/deleted including the context itself
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status Destroy() = 0;
+
+
+/*===========================================================================
+Call this function to set the temp resources required by this lib, please see
+the GFSDK_ShadowLib_TempResources structure for details of which resources
+are required and what API usage triggers their requirement.
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status SetTempResources(
+ // IN: Structure providing access to the required temp resources
+ GFSDK_ShadowLib_TempResources* __GFSDK_RESTRICT__ const pTempResources ) = 0;
+
+
+/*===========================================================================
+Creates a shadow map, based upon the descriptor, and
+adds it to an internal list of shadow maps. Returns a shadow map
+handle to the caller.
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status AddMap(
+ // IN: Describes the type of shadow map desired (see GFSDK_ShadowLib_MapDesc)
+ const GFSDK_ShadowLib_MapDesc* __GFSDK_RESTRICT__ const pShadowMapDesc,
+ // OUT: A handle to the created shadow map
+ GFSDK_ShadowLib_Map** __GFSDK_RESTRICT__ const ppShadowMapHandle ) = 0;
+
+
+/*===========================================================================
+Removes the shadow map (defined by the provided handle) from the lib's
+internal list of shadow maps
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status RemoveMap(
+ // IN/OUT: All resources held by the handle will be released/deleted including the handle itself
+ GFSDK_ShadowLib_Map** __GFSDK_RESTRICT__ const ppShadowMapHandle ) = 0;
+
+
+/*===========================================================================
+Creates a shadow buffer, based upon the descriptor, and
+adds it to an internal list of shadow buffers. Returns a shadow buffer
+handle to the caller.
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status AddBuffer(
+ // IN: Describes the type of shadow buffer desired (see GFSDK_ShadowLib_BufferDesc)
+ const GFSDK_ShadowLib_BufferDesc* __GFSDK_RESTRICT__ const pShadowBufferDesc,
+ // IN/OUT: A handle to the created shadow buffer
+ GFSDK_ShadowLib_Buffer** __GFSDK_RESTRICT__ const ppShadowBufferHandle ) = 0;
+
+
+/*===========================================================================
+Removes the shadow buffer (defined by the provided handle) from the lib's
+internal list of shadow buffers
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status RemoveBuffer(
+ // IN/OUT: All resources held by the handle will be released/deleted including the handle itself
+ GFSDK_ShadowLib_Buffer** __GFSDK_RESTRICT__ const ppShadowBufferHandle ) = 0;
+
+
+/*===========================================================================
+Renders the shadow map (defined by the provided handle), based upon the
+provided render params
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status RenderMap(
+ // IN: Handle of the shadow map you wish to render to
+ GFSDK_ShadowLib_Map* __GFSDK_RESTRICT__ const pShadowMapHandle,
+ // IN: The render params instructing the lib how to render the map (see GFSDK_ShadowLib_MapRenderParams)
+ const GFSDK_ShadowLib_MapRenderParams* __GFSDK_RESTRICT__ const pShadowMapRenderParams ) = 0;
+
+
+/*===========================================================================
+Clears the specified shadow buffer
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status ClearBuffer(
+ // IN: Handle of the shadow buffer you wish to clear
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle ) = 0;
+
+
+/*===========================================================================
+Accumulates shadows in the specified buffer (with min blending),
+using the given technique on the given shadow map. This function may be
+called multiple times with different shadow maps, and techniques to
+accumulate shadowed regions of the screen.
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status RenderBuffer(
+ // IN: Handle of the shadow map you wish to use
+ GFSDK_ShadowLib_Map* __GFSDK_RESTRICT__ const pShadowMapHandle,
+ // IN: Handle of the shadow buffer you wish to use
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ // IN: The render params instructing the lib how to render the buffer (see GFSDK_ShadowLib_BufferRenderParams)
+ const GFSDK_ShadowLib_BufferRenderParams* __GFSDK_RESTRICT__ const pShadowBufferRenderParams ) = 0;
+
+
+/*===========================================================================
+Accumulates shadows in the specified buffer (with min blending),
+using the given technique on the given _external_ shadow map. This function may be
+called multiple times with different _external_ shadow maps, and techniques to
+accumulate shadowed regions of the screen.
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status RenderBufferUsingExternalMap(
+ // IN: Details of the external shadow map required by the library (see GFSDK_ShadowLib_ExternalMapDesc)
+ const GFSDK_ShadowLib_ExternalMapDesc* __GFSDK_RESTRICT__ const pExternalShadowMapDesc,
+ // IN: Used to pass in platform specific shadow map (see GFSDK_ShadowLib_Common.h)
+ const GFSDK_ShadowLib_ShaderResourceView* __GFSDK_RESTRICT__ const pShadowMapSRV,
+ // IN: Handle of the shadow buffer you wish to use
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ // IN: The render params instructing the lib how to render the buffer (see GFSDK_ShadowLib_BufferRenderParams)
+ const GFSDK_ShadowLib_BufferRenderParams* __GFSDK_RESTRICT__ const pShadowBufferRenderParams ) = 0;
+
+
+/*===========================================================================
+Once done with accumulating shadows in the buffer, call this function to
+finalize the accumulated result and get back the shadow buffer SRV
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status FinalizeBuffer(
+ // IN: Handle of the shadow buffer you wish to finalize
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ // OUT: A platform specific shadow buffer texture - which can the be used to modulate with scene color
+ GFSDK_ShadowLib_ShaderResourceView* __GFSDK_RESTRICT__ const pShadowBufferSRV ) = 0;
+
+
+/*===========================================================================
+Combines the finalized shadow buffer with the color render target provided,
+using the supplied parameters
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status ModulateBuffer(
+ // IN: Handle of the shadow buffer you wish to modulate with scene color
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ // IN: Platform specific color texture to modulate with
+ const GFSDK_ShadowLib_RenderTargetView* __GFSDK_RESTRICT__ const pColorRTV,
+ // IN: The color of the shadow to be used in the modulation
+ gfsdk_float3 v3ShadowColor,
+ // IN: The write mask to use during modulative blending
+ GFSDK_ShadowLib_ModulateBufferMask eModulateMask ) = 0;
+
+
+/*===========================================================================
+Stereo fix up resource, NULL if in mono mode
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status SetStereoFixUpResource(
+ // IN: A platform specific texture containing stereo fix up information (NULL if stereo is nopt required)
+ const GFSDK_ShadowLib_ShaderResourceView* __GFSDK_RESTRICT__ const pStereoFixUpSRV ) = 0;
+
+
+/*===========================================================================
+Development mode functions...
+===========================================================================*/
+
+
+/*===========================================================================
+Helper function that creates a GFSDK_ShadowLib_Texture2D
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeCreateTexture2D(
+ GFSDK_ShadowLib_Texture2D* __GFSDK_RESTRICT__ const pTexture2D ) = 0;
+
+
+/*===========================================================================
+Enable perf makers
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeEnablePerfMarkers(
+ gfsdk_bool bEnable ) = 0;
+
+
+/*===========================================================================
+Display the shadow map
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeDisplayMap(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ const GFSDK_ShadowLib_RenderTargetView* __GFSDK_RESTRICT__ const pRTV,
+ GFSDK_ShadowLib_Map* __GFSDK_RESTRICT__ const pShadowMapHandle,
+ gfsdk_U32 uMapID,
+ // The origin is considered to be: DX = Top Left, GL = Bottom Left
+ gfsdk_U32 uPosX,
+ gfsdk_U32 uPosY,
+ gfsdk_F32 fScale ) = 0;
+
+
+/*===========================================================================
+Display the shadow map frustum
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeDisplayMapFrustum(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ const GFSDK_ShadowLib_RenderTargetView* __GFSDK_RESTRICT__ const pRTV,
+ const GFSDK_ShadowLib_DepthStencilView* __GFSDK_RESTRICT__ const pDSV,
+ GFSDK_ShadowLib_Map* __GFSDK_RESTRICT__ const pShadowMapHandle,
+ gfsdk_U32 uMapID,
+ gfsdk_float3 v3Color ) = 0;
+
+
+/*===========================================================================
+Display the shadow map
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeDisplayExternalMap(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ const GFSDK_ShadowLib_RenderTargetView* __GFSDK_RESTRICT__ const pRTV,
+ const GFSDK_ShadowLib_ExternalMapDesc* __GFSDK_RESTRICT__ const pExternalShadowMapDesc,
+ const GFSDK_ShadowLib_ShaderResourceView* __GFSDK_RESTRICT__ const pShadowMapSRV,
+ gfsdk_U32 uMapID,
+ // The origin is considered to be: DX = Top Left, GL = Bottom Left
+ gfsdk_U32 uPosX,
+ gfsdk_U32 uPosY,
+ gfsdk_F32 fScale ) = 0;
+
+
+/*===========================================================================
+Display the external shadow map frustum
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeDisplayExternalMapFrustum(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ const GFSDK_ShadowLib_RenderTargetView* __GFSDK_RESTRICT__ const pRTV,
+ const GFSDK_ShadowLib_DepthStencilView* __GFSDK_RESTRICT__ const pDSV,
+ const GFSDK_ShadowLib_ExternalMapDesc* __GFSDK_RESTRICT__ const pExternalShadowMapDesc,
+ gfsdk_U32 uMapID,
+ gfsdk_float3 v3Color ) = 0;
+
+
+/*===========================================================================
+Display the finalized shadow buffer
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeDisplayBuffer(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ const GFSDK_ShadowLib_RenderTargetView* __GFSDK_RESTRICT__ const pRTV,
+ gfsdk_float2 v2Scale,
+ const GFSDK_ShadowLib_ScissorRect* __GFSDK_RESTRICT__ const pSR ) = 0;
+
+
+/*===========================================================================
+Render cascades into the shadow buffer
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeToggleDebugCascadeShader(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ gfsdk_bool bUseDebugShader ) = 0;
+
+
+/*===========================================================================
+Render eye depth into the shadow buffer
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeToggleDebugEyeDepthShader(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ gfsdk_bool bUseDebugShader ) = 0;
+
+
+/*===========================================================================
+Render eye view z into the shadow buffer
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeToggleDebugEyeViewZShader(
+ GFSDK_ShadowLib_Buffer* __GFSDK_RESTRICT__ const pShadowBufferHandle,
+ gfsdk_bool bUseDebugShader ) = 0;
+
+
+/*===========================================================================
+Get shadow map data, basically used to test the external shadow map path
+===========================================================================*/
+virtual GFSDK_ShadowLib_Status DevModeGetMapData(
+ GFSDK_ShadowLib_Map* __GFSDK_RESTRICT__ const pShadowMapHandle,
+ GFSDK_ShadowLib_ShaderResourceView* __GFSDK_RESTRICT__ const pShadowMapSRV,
+ gfsdk_float4x4* __GFSDK_RESTRICT__ const pLightViewMatrix,
+ gfsdk_float4x4* __GFSDK_RESTRICT__ const pLightProjMatrix ) = 0;
+
+};
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*===========================================================================
+Use this function to get the version of the DLL being used,
+you should compare this to the version numbers you see in the header
+file. If there is a mismatch please contact devrel.
+===========================================================================*/
+__GFSDK_SHADOWLIB_EXTERN_INTERFACE__ GFSDK_ShadowLib_GetDLLVersion(
+ // OUT: The version information of the DLL being used
+ GFSDK_ShadowLib_Version* __GFSDK_RESTRICT__ const pVersion );
+
+
+/*===========================================================================
+Call once on device creation to initialize the lib
+===========================================================================*/
+__GFSDK_SHADOWLIB_EXTERN_INTERFACE__ GFSDK_ShadowLib_Create(
+ // IN: Pass in the version numbers defined in this header file (these will be checked against the DLL version)
+ const GFSDK_ShadowLib_Version* __GFSDK_RESTRICT__ const pVersion,
+ // OUT: The library context which will be used during all susequent calls into the library
+ GFSDK_ShadowLib_Context** __GFSDK_RESTRICT__ const ppContext,
+ // IN: Used to pass in platform specific graphics device/context (see GFSDK_ShadowLib_Common.h)
+ const GFSDK_ShadowLib_DeviceContext* __GFSDK_RESTRICT__ const pPlatformDevice,
+ // IN: Optionally provide your own custom allocator for the library to use
+ gfsdk_new_delete_t* customAllocator = NULL );
+
+
+#ifdef __cplusplus
+}; //extern "C" {
+#endif
+
+
+/*===========================================================================
+EOF
+===========================================================================*/ \ No newline at end of file
diff --git a/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_Common.h b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_Common.h
new file mode 100644
index 0000000..01b32b5
--- /dev/null
+++ b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_Common.h
@@ -0,0 +1,416 @@
+// This code contains NVIDIA Confidential Information and is disclosed
+// under the Mutual Non-Disclosure Agreement.
+//
+// Notice
+// ALL NVIDIA DESIGN SPECIFICATIONS AND CODE ("MATERIALS") ARE PROVIDED "AS IS" NVIDIA MAKES
+// NO REPRESENTATIONS, WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
+// THE MATERIALS, AND EXPRESSLY DISCLAIMS ANY IMPLIED WARRANTIES OF NONINFRINGEMENT,
+// MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
+//
+// NVIDIA Corporation assumes no responsibility for the consequences of use of such
+// information or for any infringement of patents or other rights of third parties that may
+// result from its use. No license is granted by implication or otherwise under any patent
+// or patent rights of NVIDIA Corporation. No third party distribution is allowed unless
+// expressly authorized by NVIDIA. Details are subject to change without notice.
+// This code supersedes and replaces all information previously supplied.
+// NVIDIA Corporation products are not authorized for use as critical
+// components in life support devices or systems without express written approval of
+// NVIDIA Corporation.
+//
+// Copyright (C) 2012, NVIDIA Corporation. All rights reserved.
+//
+// NVIDIA Corporation and its licensors retain all intellectual property and proprietary
+// rights in and to this software and related documentation and any modifications thereto.
+// Any use, reproduction, disclosure or distribution of this software and related
+// documentation without an express license agreement from NVIDIA Corporation is
+// strictly prohibited.
+
+#pragma once
+
+/*===========================================================================
+GFSDK_Common.h
+
+GFSDK_Common defines common macros, types and structs used generally by
+all NVIDIA TECH Libraries. You won't find anything particularly interesting
+here.
+
+For any issues with this particular header please contact:
+
+
+For any issues with the specific FX library you are using, see the header
+file for that library for contact information.
+
+===========================================================================*/
+
+#pragma pack(push,8) // Make sure we have consistent structure packings
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*===========================================================================
+AUTO CONFIG
+===========================================================================*/
+#ifndef __GFSDK_COMMON_AUTOCONFIG
+#define __GFSDK_COMMON_AUTOCONFIG
+
+ #ifdef __GNUC__
+ #define __GFSDK_CC_GNU__ 1
+ #define __GFSDK_CC_MSVC__ 0
+ #else
+ #define __GFSDK_CC_GNU__ 0
+ #define __GFSDK_CC_MSVC__ 1
+ #endif
+
+#endif
+
+
+/*===========================================================================
+FORWARD DECLARATIONS
+===========================================================================*/
+#ifndef __GFSDK_COMMON_FORWARDDECLS
+#define __GFSDK_COMMON_FORWARDDECLS
+
+ #if defined ( __GFSDK_GL__ )
+ // $ TODO Add common fwd decls for OGL
+ #elif defined ( __GFSDK_DX11__ )
+ // $ TODO Add common fwd decls for D3D11
+ #endif
+
+#endif // __GFSDK_COMMON_FORWARDDECLS
+
+
+/*===========================================================================
+TYPES
+===========================================================================*/
+#ifndef __GFSDK_COMMON_TYPES
+#define __GFSDK_COMMON_TYPES
+
+ typedef unsigned char gfsdk_U8;
+ typedef unsigned short gfsdk_U16;
+ typedef signed int gfsdk_S32;
+ typedef signed long long gfsdk_S64;
+ typedef unsigned int gfsdk_U32;
+ typedef unsigned long long gfsdk_U64;
+ typedef float gfsdk_F32;
+
+ typedef struct {
+ gfsdk_F32 x;
+ gfsdk_F32 y;
+ } gfsdk_float2;
+
+ typedef struct {
+ gfsdk_F32 x;
+ gfsdk_F32 y;
+ gfsdk_F32 z;
+ } gfsdk_float3;
+
+ typedef struct {
+ gfsdk_F32 x;
+ gfsdk_F32 y;
+ gfsdk_F32 z;
+ gfsdk_F32 w;
+ } gfsdk_float4;
+
+ // implicit row major
+ typedef struct {
+ gfsdk_F32 _11, _12, _13, _14;
+ gfsdk_F32 _21, _22, _23, _24;
+ gfsdk_F32 _31, _32, _33, _34;
+ gfsdk_F32 _41, _42, _43, _44;
+ } gfsdk_float4x4;
+
+ typedef bool gfsdk_bool;
+ typedef char gfsdk_char;
+ typedef const gfsdk_char* gfsdk_cstr;
+ typedef double gfsdk_F64;
+
+#endif // __GFSDK_COMMON_TYPES
+
+
+/*=========================================================================
+Useful default matrices/vectors
+===========================================================================*/
+
+static gfsdk_float4x4 GFSDK_Identity_Matrix = { 1,0,0,0,
+ 0,1,0,0,
+ 0,0,1,0,
+ 0,0,0,1 };
+
+static gfsdk_float2 GFSDK_Zero_Vector2 = { 0, 0 };
+static gfsdk_float2 GFSDK_One_Vector2 = { 1, 1 };
+static gfsdk_float3 GFSDK_Zero_Vector3 = { 0, 0, 0 };
+static gfsdk_float3 GFSDK_One_Vector3 = { 1, 1, 1 };
+
+
+/*===========================================================================
+MACROS
+===========================================================================*/
+#ifndef __GFSDK_COMMON_MACROS
+#define __GFSDK_COMMON_MACROS
+
+ // GNU
+ #if __GFSDK_CC_GNU__
+ #define __GFSDK_ALIGN__(bytes) __attribute__((aligned (bytes)))
+ #define __GFSDK_EXPECT__(exp,tf) __builtin_expect(exp, tf)
+ #define __GFSDK_INLINE__ __attribute__((always_inline))
+ #define __GFSDK_NOLINE__ __attribute__((noinline))
+ #define __GFSDK_RESTRICT__ __restrict
+ /*-------------------------------------------------------------------------*/
+ #define __GFSDK_CDECL__
+ #define __GFSDK_IMPORT__
+ #define __GFSDK_EXPORT__
+ #define __GFSDK_STDCALL__
+ #endif
+
+
+ // MSVC
+ #if __GFSDK_CC_MSVC__
+ #define __GFSDK_ALIGN__(bytes) __declspec(align(bytes))
+ #define __GFSDK_EXPECT__(exp, tf) (exp)
+ #define __GFSDK_INLINE__ __forceinline
+ #define __GFSDK_NOINLINE__
+ #define __GFSDK_RESTRICT__ __restrict
+ /*-------------------------------------------------------------------------*/
+ #define __GFSDK_CDECL__ __cdecl
+ #define __GFSDK_IMPORT__ __declspec(dllimport)
+ #define __GFSDK_EXPORT__ __declspec(dllexport)
+ #define __GFSDK_STDCALL__ __stdcall
+ #endif
+
+#endif // __GFSDK_COMMON_MACROS
+
+
+/*===========================================================================
+RETURN CODES
+===========================================================================*/
+#ifndef __GFSDK_COMMON_RETURNCODES
+#define __GFSDK_COMMON_RETURNCODES
+
+ #define GFSDK_RETURN_OK 0
+ #define GFSDK_RETURN_FAIL 1
+ #define GFSDK_RETURN_EMULATION 2
+
+#endif // __GFSDK_COMMON_RETURNCODES
+
+
+/*===========================================================================
+CUSTOM HEAP
+===========================================================================*/
+#ifndef __GFSDK_COMMON_CUSTOMHEAP
+#define __GFSDK_COMMON_CUSTOMHEAP
+
+ typedef struct {
+ void* (*new_)(size_t);
+ void (*delete_)(void*);
+ } gfsdk_new_delete_t;
+
+#endif // __GFSDK_COMMON_CUSTOMHEAP
+
+
+/*===========================================================================
+HANDLE DECLARATION
+===========================================================================*/
+#ifndef __GFSDK_COMMON_DECLHANDLE
+#define __GFSDK_COMMON_DECLHANDLE
+#define GFSDK_DECLARE_HANDLE(name) struct name##__ { int unused; }; typedef struct name##__ *name
+#endif // __GFSDK_COMMON_DECLHANDLE
+
+
+/*===========================================================================
+Forward Declarations
+===========================================================================*/
+
+// Shadow buffer handle
+struct GFSDK_ShadowLib_Buffer;
+
+// Shadow map handle
+struct GFSDK_ShadowLib_Map;
+
+
+/*===========================================================================
+Resource Structure Declarations (different for each platform)
+===========================================================================*/
+
+struct GFSDK_ShadowLib_DeviceContext
+{
+ #if defined ( __GFSDK_DX11__ )
+
+ ID3D11Device* pD3DDevice;
+ ID3D11DeviceContext* pDeviceContext;
+
+ GFSDK_ShadowLib_DeviceContext()
+ {
+ pD3DDevice = NULL;
+ pDeviceContext = NULL;
+ }
+
+ #elif defined ( __GFSDK_GL__ )
+
+ // $ TO implement
+
+ #endif
+};
+
+struct GFSDK_ShadowLib_RenderTargetView
+{
+ #if defined ( __GFSDK_DX11__ )
+
+ ID3D11RenderTargetView* pRTV;
+
+ GFSDK_ShadowLib_RenderTargetView()
+ {
+ pRTV = NULL;
+ }
+
+ #elif defined ( __GFSDK_GL__ )
+
+ GLuint FBO;
+
+ GFSDK_ShadowLib_RenderTargetView()
+ {
+ FBO = 0;
+ }
+
+ #endif
+};
+
+struct GFSDK_ShadowLib_ShaderResourceView
+{
+ #if defined ( __GFSDK_DX11__ )
+
+ ID3D11ShaderResourceView* pSRV;
+
+ GFSDK_ShadowLib_ShaderResourceView()
+ {
+ pSRV = NULL;
+ }
+
+ #elif defined ( __GFSDK_GL__ )
+
+ GLuint Texture;
+
+ GFSDK_ShadowLib_ShaderResourceView()
+ {
+ Texture = 0;
+ }
+
+ #endif
+};
+
+struct GFSDK_ShadowLib_DepthStencilView
+{
+ #if defined ( __GFSDK_DX11__ )
+
+ ID3D11DepthStencilView* pDSV;
+
+ GFSDK_ShadowLib_DepthStencilView()
+ {
+ pDSV = NULL;
+ }
+
+ #elif defined ( __GFSDK_GL__ )
+
+ GLuint Texture;
+
+ GFSDK_ShadowLib_DepthStencilView()
+ {
+ Texture = 0;
+ }
+
+ #endif
+};
+
+struct GFSDK_ShadowLib_ScissorRect
+{
+ #if defined ( __GFSDK_DX11__ )
+ D3D11_RECT* pSR;
+
+ GFSDK_ShadowLib_ScissorRect()
+ {
+ pSR = NULL;
+ }
+
+ #elif defined ( __GFSDK_GL__ )
+
+ // $ TO implement
+
+ #endif
+};
+
+struct GFSDK_ShadowLib_Texture2D
+{
+ gfsdk_U32 uWidth;
+ gfsdk_U32 uHeight;
+ gfsdk_U32 uSampleCount;
+
+ #if defined ( __GFSDK_DX11__ )
+
+ DXGI_FORMAT Format;
+ ID3D11Texture2D* pTexture;
+ ID3D11ShaderResourceView* pSRV;
+ ID3D11RenderTargetView* pRTV;
+
+ #elif defined ( __GFSDK_GL__ )
+
+ GLenum Type;
+ GLenum InternalFormat;
+ GLenum Format;
+ GLuint Texture;
+ GLuint FBO;
+
+ #endif
+
+ GFSDK_ShadowLib_Texture2D()
+ {
+ uWidth = 0;
+ uHeight = 0;
+ uSampleCount = 1;
+
+ #if defined ( __GFSDK_DX11__ )
+
+ Format = DXGI_FORMAT_UNKNOWN;
+ pTexture = NULL;
+ pSRV = NULL;
+ pRTV = NULL;
+
+ #elif defined ( __GFSDK_GL__ )
+
+ Type = 0;
+ InternalFormat = 0;
+ Format = 0;
+ Texture = 0;
+ FBO = 0;
+
+ #endif
+ }
+};
+
+
+/*===========================================================================
+Interface defines
+===========================================================================*/
+
+#define __GFSDK_SHADOWLIB_INTERFACE__ GFSDK_ShadowLib_Status __GFSDK_CDECL__
+
+#ifdef __DLL_GFSDK_SHADOWLIB_EXPORTS__
+ #define __GFSDK_SHADOWLIB_EXTERN_INTERFACE__ __GFSDK_EXPORT__ __GFSDK_SHADOWLIB_INTERFACE__
+#else
+ #define __GFSDK_SHADOWLIB_EXTERN_INTERFACE__ __GFSDK_IMPORT__ __GFSDK_SHADOWLIB_INTERFACE__
+#endif
+
+#define GFSDK_ShadowLib_FunctionPointer (void(*)(void*,gfsdk_float4x4*))
+
+#ifdef __cplusplus
+}; //extern "C" {
+
+#endif
+
+#pragma pack(pop)
+
+
+/*===========================================================================
+EOF
+===========================================================================*/
diff --git a/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.dll b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.dll
new file mode 100644
index 0000000..9a1e46d
--- /dev/null
+++ b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.dll
Binary files differ
diff --git a/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.lib b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.lib
new file mode 100644
index 0000000..8969b01
--- /dev/null
+++ b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win32.lib
Binary files differ
diff --git a/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.dll b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.dll
new file mode 100644
index 0000000..1c41950
--- /dev/null
+++ b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.dll
Binary files differ
diff --git a/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.lib b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.lib
new file mode 100644
index 0000000..dd918c6
--- /dev/null
+++ b/NvCloth/samples/external/shadow_lib/GFSDK_ShadowLib_DX11.win64.lib
Binary files differ
diff --git a/NvCloth/samples/resources/shaders/common_buffers.hlsl b/NvCloth/samples/resources/shaders/common_buffers.hlsl
new file mode 100644
index 0000000..1aa3386
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/common_buffers.hlsl
@@ -0,0 +1,28 @@
+#ifndef COMMON_BUFFERS_HLSL
+#define COMMON_BUFFERS_HLSL
+
+cbuffer Camera : register(b0)
+{
+ row_major matrix viewProjection;
+ row_major matrix projectionInv;
+ float3 viewPos;
+};
+
+cbuffer World : register(b1)
+{
+ float3 ambientColor;
+ float3 pointLightPos;
+ float3 pointLightColor;
+ float3 dirLightDir;
+ float specularPower;
+ float3 dirLightColor;
+ float specularIntensity;
+};
+
+cbuffer Object : register(b2)
+{
+ row_major matrix model;
+ float4 defaultColor;
+};
+
+#endif \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/debug_primitive.hlsl b/NvCloth/samples/resources/shaders/debug_primitive.hlsl
new file mode 100644
index 0000000..a24ebfb
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/debug_primitive.hlsl
@@ -0,0 +1,31 @@
+#include "common_buffers.hlsl"
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 color : COLOR0;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float3 color : COLOR0;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ float4 eyeSpacePos = mul(worldSpacePos, viewProjection);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.color = iV.color;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ return float4(iV.color, 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/lighting.hlsl b/NvCloth/samples/resources/shaders/lighting.hlsl
new file mode 100644
index 0000000..2dacc14
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/lighting.hlsl
@@ -0,0 +1,51 @@
+#include "common_buffers.hlsl"
+
+static const float att_c = 1.0f;
+static const float att_l = 0.014f;
+static const float att_q = 0.0007f;
+
+
+float CalcAttenuation(float distance)
+{
+ return 1 / (att_c + att_l * distance + att_q * distance * distance);
+};
+
+
+float3 CalcLight(float3 textureColor, float3 lightDir, float3 viewDir, float3 normal, float3 lightColor, float specPower, float specIntensity, float attenuation)
+{
+ normal = normalize(normal);
+
+ // diffuse
+ float3 dirToLight = normalize(-lightDir);
+ float diffuseFactor = max(dot(normal, dirToLight), 0.0);
+ float3 diffuse = lightColor * textureColor * diffuseFactor * attenuation;
+
+ // specular (Blinn-Phong)
+ float3 halfwayDir = normalize(dirToLight + viewDir);
+ float specFactor = pow(max(dot(viewDir, halfwayDir), 0.0), specPower);
+ float3 spec = lightColor * specFactor * attenuation * specIntensity;
+
+ return diffuse + spec;
+};
+
+float3 CalcPixelLight(float3 diffuseColor, float3 worldPos, float3 normal)
+{
+ float3 viewDir = normalize(viewPos - worldPos);
+
+ // ambient
+ float3 ambient = ambientColor * diffuseColor;
+
+ // dir light
+ float3 dirLight = CalcLight(diffuseColor, dirLightDir, viewDir, normal, dirLightColor, specularPower, specularIntensity, 1);
+
+ // point light
+ float3 pointLightDir = worldPos - pointLightPos;
+ float distance = length(pointLightDir);
+ float attenuation = CalcAttenuation(distance);
+ float3 pointLight = CalcLight(diffuseColor, pointLightDir, viewDir, normal, pointLightColor, specularPower, specularIntensity, attenuation);
+
+ // hacky hack: ambient attenuates within point light distance
+ ambient *= attenuation;
+
+ return ambient + dirLight + pointLight;
+}; \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/model_simple.hlsl b/NvCloth/samples/resources/shaders/model_simple.hlsl
new file mode 100644
index 0000000..7d55a72
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/model_simple.hlsl
@@ -0,0 +1,42 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+ float health : TEXCOORD1;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float3 normal : NORMAL0;
+ float health : TEXCOORD1;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 worldNormal = mul(iV.normal, (float3x3)model);
+ oV.normal = worldNormal;
+
+ oV.health = iV.health;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float3 lightColor = CalcPixelLight(defaultColor.xyz, iV.worldPos.xyz, iV.normal);
+ lightColor.r = 1.0f - iV.health; // hack for health
+ return float4(lightColor, 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/model_simple_textured.hlsl b/NvCloth/samples/resources/shaders/model_simple_textured.hlsl
new file mode 100644
index 0000000..5167837
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/model_simple_textured.hlsl
@@ -0,0 +1,76 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+SamplerState defaultSampler : register(s0);
+Texture2D diffuseTexture : register(t0);
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+ float2 uv : TEXCOORD0;
+ float health : TEXCOORD1;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float2 uv : TEXCOORD0;
+ float3 normal : NORMAL0;
+ float health : TEXCOORD1;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 worldNormal = mul(float4(iV.normal, 0.0f), model);
+ oV.normal = worldNormal;
+
+ oV.uv = iV.uv;
+ oV.health = iV.health;
+
+ return oV;
+}
+
+float noise2(float2 co)
+{
+ return frac(sin(dot(co.xy, float2(12.9898,78.233))) * 43758.5453);
+}
+
+float voronoi( float2 x )
+{
+ int2 p = floor( x );
+ float2 f = frac( x );
+
+ float res = 8.0;
+ for( int j=-1; j<=1; j++ )
+ for( int i=-1; i<=1; i++ )
+ {
+ int2 b = int2( i, j );
+ float2 r = float2( b ) - f + noise2( p + b );
+ float d = dot( r, r );
+
+ res = min( res, d );
+ }
+ return sqrt( res );
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float4 textureColor = diffuseTexture.Sample(defaultSampler, iV.uv);
+
+ // health cracks hack
+ float crack = 1.0f - voronoi(iV.uv * 50.0f);
+ crack = smoothstep(0.0f, 0.5f, crack);
+ textureColor = textureColor * lerp(1.0f, crack, (1.0f - iV.health) * 0.7f);
+
+ return float4(CalcPixelLight(textureColor, iV.worldPos, iV.normal), 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/model_skinned.hlsl b/NvCloth/samples/resources/shaders/model_skinned.hlsl
new file mode 100644
index 0000000..1e26c95
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/model_skinned.hlsl
@@ -0,0 +1,54 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+SamplerState defaultSampler : register(s0);
+Texture2D diffuseTexture : register(t0);
+Texture2D bonesTexture : register(t1);
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+ float2 uv : TEXCOORD0;
+ uint boneIndex : TEXCOORD1;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float2 uv : TEXCOORD0;
+ float3 normal : NORMAL0;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4x4 boneMatrix;
+ boneMatrix[0] = bonesTexture.Load(int3(0, iV.boneIndex, 0));
+ boneMatrix[1] = bonesTexture.Load(int3(1, iV.boneIndex, 0));
+ boneMatrix[2] = bonesTexture.Load(int3(2, iV.boneIndex, 0));
+ boneMatrix[3] = bonesTexture.Load(int3(3, iV.boneIndex, 0));
+
+ float3 skinnedPos = mul(float4(iV.position, 1.0f), boneMatrix);
+ float4 worldSpacePos = mul(float4(skinnedPos, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 localNormal = mul(float4(iV.normal, 0.0f), boneMatrix);
+ float3 worldNormal = mul(float4(localNormal, 0.0f), model);
+ oV.normal = worldNormal;
+
+ oV.uv = iV.uv;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float3 lightColor = CalcPixelLight(defaultColor.xyz, iV.worldPos.xyz, iV.normal);
+ return float4(lightColor, 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/model_skinned_textured.hlsl b/NvCloth/samples/resources/shaders/model_skinned_textured.hlsl
new file mode 100644
index 0000000..2b2bb0e
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/model_skinned_textured.hlsl
@@ -0,0 +1,54 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+SamplerState defaultSampler : register(s0);
+Texture2D diffuseTexture : register(t0);
+Texture2D bonesTexture : register(t1);
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+ float2 uv : TEXCOORD0;
+ uint boneIndex : TEXCOORD1;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float2 uv : TEXCOORD0;
+ float3 normal : NORMAL0;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4x4 boneMatrix;
+ boneMatrix[0] = bonesTexture.Load(int3(0, iV.boneIndex, 0));
+ boneMatrix[1] = bonesTexture.Load(int3(1, iV.boneIndex, 0));
+ boneMatrix[2] = bonesTexture.Load(int3(2, iV.boneIndex, 0));
+ boneMatrix[3] = bonesTexture.Load(int3(3, iV.boneIndex, 0));
+
+ float3 skinnedPos = mul(float4(iV.position, 1.0f), boneMatrix);
+ float4 worldSpacePos = mul(float4(skinnedPos, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 localNormal = mul(float4(iV.normal, 0.0f), boneMatrix);
+ float3 worldNormal = mul(float4(localNormal, 0.0f), model);
+ oV.normal = worldNormal;
+
+ oV.uv = iV.uv;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float4 textureColor = diffuseTexture.Sample(defaultSampler, iV.uv);
+ return float4(CalcPixelLight(textureColor, iV.worldPos, iV.normal), 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/physx_primitive.hlsl b/NvCloth/samples/resources/shaders/physx_primitive.hlsl
new file mode 100644
index 0000000..03fd137
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/physx_primitive.hlsl
@@ -0,0 +1,37 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float3 normal : NORMAL0;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 worldNormal = mul(iV.normal, (float3x3)model);
+ oV.normal = worldNormal;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float3 lightColor = CalcPixelLight(defaultColor.xyz, iV.worldPos.xyz, iV.normal);
+ return float4(lightColor, 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/physx_primitive_plane.hlsl b/NvCloth/samples/resources/shaders/physx_primitive_plane.hlsl
new file mode 100644
index 0000000..3b2ec5d
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/physx_primitive_plane.hlsl
@@ -0,0 +1,64 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+ float2 uv : TEXCOORD0;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float2 uv : TEXCOORD0;
+ float3 normal : NORMAL0;
+};
+
+float filterwidth(float2 v)
+{
+ float2 fw = max(abs(ddx(v)), abs(ddy(v)));
+ return max(fw.x, fw.y);
+}
+
+float2 bump(float2 x)
+{
+ return (floor(x/2) + 2.f * max((x/2) - floor(x/2) - .5f, 0.f));
+}
+
+float checker(float2 uv)
+{
+ float width = filterwidth(uv);
+ float2 p0 = uv - 0.5 * width;
+ float2 p1 = uv + 0.5 * width;
+
+ float2 i = (bump(p1) - bump(p0)) / width;
+ return i.x * i.y + (1 - i.x) * (1 - i.y);
+}
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.uv = iV.uv;
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 worldNormal = mul(iV.normal, (float3x3)model);
+ oV.normal = worldNormal;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float4 color = defaultColor;
+ color *= 1.0 - 0.25 * checker(iV.uv);
+ float3 lightColor = CalcPixelLight(color.xyz, iV.worldPos.xyz, iV.normal);
+ return float4(lightColor, 1);
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/physx_primitive_transparent.hlsl b/NvCloth/samples/resources/shaders/physx_primitive_transparent.hlsl
new file mode 100644
index 0000000..d52392e
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/physx_primitive_transparent.hlsl
@@ -0,0 +1,40 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 worldPos : POSITION0;
+ float3 normal : NORMAL0;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.worldPos = worldSpacePos;
+
+ // normals
+ float3 worldNormal = mul(iV.normal, (float3x3)model);
+ oV.normal = worldNormal;
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ float4 color = defaultColor;
+ float3 viewDir = normalize(viewPos - iV.worldPos.xyz);
+ float factor = max(0.0f, dot(normalize(iV.normal), viewDir));
+ color.a *= factor;
+ return color;
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/pointsprite.hlsl b/NvCloth/samples/resources/shaders/pointsprite.hlsl
new file mode 100644
index 0000000..2bff194
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/pointsprite.hlsl
@@ -0,0 +1,106 @@
+#include "common_buffers.hlsl"
+#include "lighting.hlsl"
+
+SamplerState linearSampler : register(s0);
+SamplerState pointSampler : register(s1);
+Texture2D diffuseTexture : register(t0);
+Texture2D<float> depthTexture : register(t1);
+
+static const float POINT_SIZE = 1.00f;
+static const float FADE_DISTANCE = 1.0f;
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float4 color : COLOR0;
+ float2 scale : TANGENT;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+ float4 color : COLOR0;
+ float2 uv : TEXCOORD0;
+ float2 screenPos : TEXCOORD1;
+ float2 depth : TEXCOORD2;
+ float2 pointSize : PSIZE;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ oV.color = iV.color;
+ oV.uv = float2(0, 0);
+
+ // uncomment to use scale
+ //oV.pointSize = iV.scale * POINT_SIZE;
+ oV.pointSize = float2(1, 1) * POINT_SIZE;
+
+ return oV;
+}
+
+static const float4 SPRITE_VERTEX_POSITIONS[4] =
+{
+ float4( 0.5, -0.5, 0, 0),
+ float4( 0.5, 0.5, 0, 0),
+ float4( -0.5, -0.5, 0, 0),
+ float4( -0.5, 0.5, 0, 0),
+};
+
+static const float2 SPRITE_VERTEX_TEXCOORDS[4] =
+{
+ float2(1, 0),
+ float2(1, 1),
+ float2(0, 0),
+ float2(0, 1),
+};
+
+[maxvertexcount(4)]
+void GS( point VS_OUTPUT sprite[1], inout TriangleStream<VS_OUTPUT> triStream )
+{
+ VS_OUTPUT v;
+
+ v.color = sprite[0].color;
+ v.pointSize = sprite[0].pointSize;
+
+ float4 aspectFactor = float4((projection[0][0] / projection[1][1]) * v.pointSize.x, 1.0 * v.pointSize.y, 0, 0);
+
+ [unroll] for(int i = 0; i < 4; ++i)
+ {
+ v.position = sprite[0].position + SPRITE_VERTEX_POSITIONS[i] * aspectFactor;
+ v.screenPos = v.position.xy / v.position.w;
+ v.depth = v.position.zw;
+ v.uv = SPRITE_VERTEX_TEXCOORDS[i];
+ triStream.Append(v);
+ }
+
+ triStream.RestartStrip();
+}
+
+float4 PS(VS_OUTPUT input) : SV_Target0
+{
+ // soft particles fade:
+ float2 screenPos = 0.5*( (input.screenPos) + float2(1,1));
+ screenPos.y = 1 - screenPos.y;
+
+ float particleDepth = input.depth.x / input.depth.y;
+
+ float depthSample = depthTexture.Sample(pointSampler, screenPos);
+
+ float4 depthViewSample = mul(float4(input.screenPos, depthSample, 1), projectionInv );
+ float4 depthViewParticle = mul(float4(input.screenPos, particleDepth, 1), projectionInv);
+
+ float depthDiff = depthViewSample.z / depthViewSample.w - depthViewParticle.z / depthViewParticle.w;
+ if( depthDiff < 0 )
+ discard;
+
+ float depthFade = saturate( depthDiff / FADE_DISTANCE );
+
+ float4 textureColor = diffuseTexture.Sample(linearSampler, input.uv) * input.color;
+ textureColor.a *= depthFade;
+ return textureColor;
+} \ No newline at end of file
diff --git a/NvCloth/samples/resources/shaders/unlit_transparent.hlsl b/NvCloth/samples/resources/shaders/unlit_transparent.hlsl
new file mode 100644
index 0000000..0c2158a
--- /dev/null
+++ b/NvCloth/samples/resources/shaders/unlit_transparent.hlsl
@@ -0,0 +1,27 @@
+#include "common_buffers.hlsl"
+
+struct VS_INPUT
+{
+ float3 position : POSITION0;
+ float3 normal : NORMAL0;
+};
+
+struct VS_OUTPUT
+{
+ float4 position : SV_POSITION;
+};
+
+VS_OUTPUT VS(VS_INPUT iV)
+{
+ VS_OUTPUT oV;
+
+ float4 worldSpacePos = mul(float4(iV.position, 1.0f), model);
+ oV.position = mul(worldSpacePos, viewProjection);
+
+ return oV;
+}
+
+float4 PS(VS_OUTPUT iV) : SV_Target0
+{
+ return defaultColor;
+} \ No newline at end of file